Compare commits

...

24 Commits

Author SHA1 Message Date
99a5978448 Fixed window sizing issue on Windows.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 2m52s
2025-07-12 18:48:31 -04:00
3862fb602f WIndows fix bug in RestoreFromFullscreen
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m39s
2025-07-12 18:14:16 -04:00
13dfa1216d Linux Fullscreen Graphics Mode
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m47s
2025-07-12 17:21:30 -04:00
bc59e49402 SetCursorPosition Windows
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m36s
2025-07-12 17:08:37 -04:00
ac9512ef1d Cleanup
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m54s
2025-07-12 16:55:26 -04:00
87f862730b SetCursorFocused Windows
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 6m28s
2025-07-08 16:08:33 -04:00
bb776026ad SetCursorCenter Windows
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m50s
2025-06-29 19:44:33 -04:00
42deab60f4 XWindows SetCursorCenter & SetCursorFocused
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m50s
2025-06-15 16:38:04 -04:00
199642b1a9 Windows KeyRepeat
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 2m30s
2025-06-07 11:11:57 -04:00
c354b1deef std::pair
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m50s
2025-06-06 09:56:34 -04:00
c3c6a29dc6 XWindows KeyRepeat toggle
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m56s
2025-06-06 09:36:29 -04:00
f7d39b0174 Fix obscure ternary operator order, which somehow got missed for months.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m30s
2025-06-04 13:49:47 -05:00
f3cd2b6d82 Add return to VulkanWindow::GetGraphicsDriverVendor() to suppress warning.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m42s
This does need to be properly implemented, however.
2025-06-04 04:26:40 -04:00
ca459af9b1 Update OpenGLWindow.cpp
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m58s
Fix for our window not showing up in the window list on some floating window managers.
2025-05-29 11:47:34 -04:00
ffdafedb94 Fix OnClose not being called on Windows. Still doesn't work correctly on Linux (Are we handling the XEvent?)
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m35s
2025-05-22 17:25:38 -05:00
aebc6fcfd3 Fixed Windows MouseWheel Event being +120 or -120, we want +1 or -1
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 2m7s
2025-03-08 16:05:08 -05:00
0ba3618b3c Update OpenGLWindow.cpp
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m25s
Fixed a case where on some distros the OpenGL shared object is called something different.
2025-01-31 00:46:56 -05:00
778166c23f Cleanup
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m15s
2025-01-30 19:33:48 -05:00
8d4db443bd Get rid of the need for SetFlag
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m17s
2025-01-30 18:48:38 -05:00
0cfd66eb40 Fix Markdown error.
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m52s
2025-01-30 12:50:30 -05:00
c18fca517f Merge remote-tracking branch 'origin/josh-patch-1'
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m23s
2025-01-30 12:48:37 -05:00
515d428168 RWindow::IsVisible Windoze
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m33s
2025-01-30 00:43:05 -05:00
a77a8a3754 RWindow::IsVisible
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 1m23s
2025-01-29 22:34:00 -05:00
3fd2a8ce14 Update windows/Window.cpp
All checks were successful
Run ReCI Build Test / Explore-Gitea-Actions (push) Successful in 5m22s
On windows everything will be in the same cpp because their event loop is bad.
2025-01-29 13:01:52 -05:00
19 changed files with 912 additions and 1030 deletions

View File

@@ -45,7 +45,6 @@ file(GLOB_RECURSE HEADERS "include/*.h" "include/*.hpp")
file(GLOB_RECURSE HEADERS "include/logger/*.h" "include/logger/*.hpp")
if(UNIX AND NOT APPLE)
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/linux/*.cpp" "src/platform/shared/*.cpp" "src/ReWindow/*.cpp" )
endif()

View File

@@ -5,7 +5,7 @@ A library which allows easily creating and managing a window and it's events acr
## Features
- Window Creation - Create multiple windows at once. Windows can also create so-called `dialog-boxes`, which are technically windows too.
- Window Creation - Create multiple windows at once. Windows can also create so-called `message-boxes`, which are technically windows too.
- Window Management - Change the state of the window, title, size, fullscreen mode, v-sync, and more.
- Window Events - Callback function hooks for reading user-input and window state events, such as exit, focus, etc.
- State of the Art C++20
@@ -15,7 +15,7 @@ A library which allows easily creating and managing a window and it's events acr
- Supports OpenGL, Vulkan, Software Rendering(?)
- Public Domain.
- Lightweight AF.
- Painless integration with <your favorite graphics API>. (Ours is JGL!)
- Painless integration with \<your favorite graphics API\>. (Ours is JGL!)
- Straightforward, well-documented source code and API.
- Packaged with InputService as a built-in, portable input API.

View File

@@ -18,6 +18,6 @@ namespace InputService {
inline Event<MouseWheelEvent> OnMouseWheel;
bool IsKeyDown(const Key& key);
bool IsMouseButtonDown(const MouseButton& button);
IPair GetMousePosition();
IPair GetWindowSize();
std::pair<int, int> GetMousePosition();
std::pair<int, int> GetWindowSize();
};

View File

@@ -1,140 +0,0 @@
#pragma once
#ifdef _WIN32
#include <Windows.h>
#include <ReWindow/types/Window.h>
using namespace ReWindow;
//Event loop.
// TODO move this. It can't be in the RWindow class because it has to be publicly visible.
inline LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
RWindow* window = reinterpret_cast<RWindow*>( GetWindowLongPtr(hwnd, GWLP_USERDATA) );
switch (uMsg) {
case WM_CLOSE: {
DestroyWindow(hwnd);
window->processOnClose();
}
case WM_DESTROY: {
exit(0);
}
case WM_SIZE: {
window->SetSizeWithoutEvent({ LOWORD(lParam), HIWORD(lParam) });
auto eventData = WindowResizeRequestEvent();
eventData.Size = { window->GetWidth(), window->GetHeight() };
window->SetLastKnownWindowSize({ window->GetWidth(), window->GetHeight() });
// TODO: Implement eWindow->processOnResize()
window->OnResizeRequest(eventData);
window->OnResizeRequestEvent(eventData);
break;
}
case WM_SETFOCUS: {
window->processFocusIn();
window->SetFlag(WindowFlag::IN_FOCUS, true);
// TODO actually check if it's flashing.
FLASHWINFO fi;
fi.cbSize = sizeof(FLASHWINFO);
fi.hwnd = hwnd;
fi.dwFlags = FLASHW_STOP;
fi.uCount = 0;
fi.dwTimeout = 0;
FlashWindowEx(&fi);
break;
}
case WM_KILLFOCUS: {
window->processFocusOut();
window->SetFlag(WindowFlag::IN_FOCUS, false);
}
case WM_SETCURSOR: {
if (LOWORD(lParam) == HTCLIENT && window->GetCursorVisible() == false)
SetCursor(nullptr);
break;
}
case WM_KEYDOWN: {
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
//Key repeat fix.
if (!window->previousKeyboard.PressedKeys[key])
window->processKeyPress(key);
break;
}
case WM_KEYUP: {
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
window->processKeyRelease(key);
break;
}
//Mouse Buttons.
case WM_MOUSEWHEEL: {
int wheel_delta = GET_WHEEL_DELTA_WPARAM(wParam);
// TODO: Determine sign of wheel_delta for each direction, (and on linux too), and document this.
window->processMouseWheel(wheel_delta);\
break;
}
case WM_LBUTTONDOWN: {
window->processMousePress(MouseButtons::Left);
break;
}
case WM_LBUTTONUP: {
window->processMouseRelease(MouseButtons::Left);
break;
}
case WM_RBUTTONDOWN: {
window->processMousePress(MouseButtons::Right);
break;
}
case WM_RBUTTONUP: {
window->processMouseRelease(MouseButtons::Right);
break;
}
case WM_MBUTTONDOWN: {
window->processMousePress(MouseButtons::Middle);
break;
}
case WM_MBUTTONUP: {
window->processMouseRelease(MouseButtons::Middle);
break;
}
case WM_XBUTTONDOWN: {
WORD button = GET_XBUTTON_WPARAM(wParam);
if (button == XBUTTON1)
window->processMousePress(MouseButtons::Mouse4);
if (button == XBUTTON2)
window->processMousePress(MouseButtons::Mouse5);
break;
}
case WM_XBUTTONUP: {
WORD button = GET_XBUTTON_WPARAM(wParam);
if (button == XBUTTON1)
window->processMouseRelease(MouseButtons::Mouse4);
if (button == XBUTTON2)
window->processMouseRelease(MouseButtons::Mouse5);
break;
}
//This is the same as "Motion Notify" in the X Window System.
case WM_MOUSEMOVE:
break;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
#endif

View File

@@ -1,27 +0,0 @@
/// ReWindowLibrary
/// A C++20 Library for creating and managing windows in a platform-independent manner
/// Developed and Maintained by the boys @ Redacted Software.
/// (c) 2024 Redacted Software
/// This work is dedicated to the public domain.
/// @file gamepad.h
/// @desc A class that models the functionality of a gamepad / controller device.
/// @edit 2024-07-29
#pragma once
namespace ReWindow {
class Gamepad;
class Xbox360Gamepad;
class XboxOneGamepad;
class PS4Gamepad;
class Ultimate8BitDoPro2Gamepad;
}
class ReWindow::Gamepad {
public:
virtual ~Gamepad() = default;
};
class ReWindow::XboxOneGamepad : public Gamepad {};
class ReWindow::PS4Gamepad : public Gamepad {};

View File

@@ -1,105 +0,0 @@
/// ReWindowLibrary
/// A C++20 Library for creating and managing windows in a platform-independent manner
/// Developed and Maintained by the boys @ Redacted Software.
/// (c) 2024 Redacted Software
/// This work is dedicated to the public domain.
/// @file gamepadbutton.h
/// @desc GamepadButton class and enumerations to define standard buttons found on a Gamepad
/// @edit 2024-07-29
#include <string>
#include <utility>
#include <ReWindow/types/Pair.h>
namespace ReWindow {
class GamepadButton;
class GamepadTrigger;
class GamepadThumbstick;
}
class ReWindow::GamepadButton {
protected:
std::string mnemonic_btn_code;
public:
explicit GamepadButton(std::string mnemonic) : mnemonic_btn_code(std::move(mnemonic)){}
[[nodiscard]] std::string GetMnemonicButtonCode() const;
/// Compares two GamepadButtons by their mnemonic button codes, not their activation state.
bool operator ==(const GamepadButton& rhs) const;
};
class ReWindow::GamepadTrigger {
protected:
std::string mnemonic_trigger_code;
/// A float value between 0 and 1 representing how much the trigger has been pushed in by.
float position = 0.0f;
/// The minimum possible movement of the trigger from the at-rest position.
/// Movements less than this won't count.
float dead_zone = 0.0f;
public:
void SetDeadzone(float minimum = 0.01f);
[[nodiscard]] float GetActuation() const;
public:
explicit GamepadTrigger(std::string mnemonic) : mnemonic_trigger_code(std::move(mnemonic)){}
};
class ReWindow::GamepadThumbstick {
protected:
std::string mnemonic_stick_code;
// X -1 is all the way left, X +1 is all the way right.
// Y -1 is all the way down, Y +1 is all the way up.
FPair position = {0.0f, 0.0f};
// The minimum possible movement from the center in any direction.
float dead_zone = 0.0f;
public:
[[nodiscard]] FPair GetPosition() const;
void SetDeadzone(float minimum = 0.01f);
public:
explicit GamepadThumbstick(std::string mnemonic) : mnemonic_stick_code(std::move(mnemonic)){}
};
namespace ReWindow::GamepadButtons {
static const GamepadButton Triangle("");
static const GamepadButton Square("");
static const GamepadButton Circle("");
static const GamepadButton Cross("X");
// If you like xbox :shrug:
static const GamepadButton Y = Triangle;
static const GamepadButton X = Square;
static const GamepadButton A = Cross;
static const GamepadButton B = Circle;
static const GamepadButton LButton("LB");
static const GamepadButton RButton("RB");
/* For controllers where L2 & R2 is a button or counts as one when pressed all the way down.
* Gamecube & PS2 controllers do this. - Redacted. */
static const GamepadButton LButton2("LB2");
static const GamepadButton RButton2("RB2");
// The buttons when you press in the sticks.
static const GamepadButton LButton3("LB3");
static const GamepadButton RButton3("RB3");
// Will eventually need to handle making it not possible to, for ex. Press left and right at the same time.
static const GamepadButton DPadUp("DPU");
static const GamepadButton DPadDown("DPD");
static const GamepadButton DPadLeft("DPL");
static const GamepadButton DPadRight("DPR");
static const GamepadButton Select("SEL");
static const GamepadButton Start("START");
}
namespace ReWindow::GamepadTriggers {
static const ReWindow::GamepadTrigger Left {"LT"};
static const ReWindow::GamepadTrigger Right {"RT"};
}
namespace ReWindow::GamepadThumbsticks {
static const GamepadThumbstick Left {"LS"};
static const GamepadThumbstick Right {"RS"};
}

View File

@@ -1,53 +0,0 @@
#pragma once
namespace ReWindow {
class IPair;
class FPair;
}
class ReWindow::IPair {
public:
int x, y;
public:
IPair operator +(const IPair& rhs) const;
IPair operator -(const IPair& rhs) const;
IPair operator *(const IPair& rhs) const;
IPair operator /(const IPair& rhs) const;
public:
IPair& operator +=(const IPair& rhs);
IPair& operator -=(const IPair& rhs);
IPair& operator *=(const IPair& rhs);
IPair& operator /=(const IPair& rhs);
public:
bool operator ==(const IPair& rhs) const;
bool operator !=(const IPair& rhs) const;
public:
IPair(const IPair& rhs);
IPair() : x(0), y(0) {};
IPair(int x, int y) : x(x), y(y) {};
~IPair() = default;
};
class ReWindow::FPair {
public:
float x, y;
public:
FPair operator +(const FPair& rhs) const;
FPair operator -(const FPair& rhs) const;
FPair operator *(const FPair& rhs) const;
FPair operator /(const FPair& rhs) const;
public:
FPair& operator +=(const FPair& rhs);
FPair& operator -=(const FPair& rhs);
FPair& operator *=(const FPair& rhs);
FPair& operator /=(const FPair& rhs);
public:
bool operator ==(const FPair& rhs) const;
bool operator !=(const FPair& rhs) const;
public:
FPair(const FPair& rhs);
explicit FPair(const IPair& rhs);
FPair() : x(0), y(0) {};
FPair(float x, float y) : x(x), y(y) {};
~FPair() = default;
};

View File

@@ -7,15 +7,12 @@
#include <ReWindow/types/Key.h>
#include <ReWindow/types/Cursors.h>
#include <ReWindow/types/MouseButton.h>
#include <ReWindow/types/GamepadButton.h>
#include <ReWindow/types/Pair.h>
#include <ReWindow/types/WindowEvents.h>
#include <queue>
namespace ReWindow {
struct KeyboardState { std::map<Key, bool> PressedKeys; };
struct GamepadState { std::map<GamepadButton, bool> PressedButtons; };
class MouseState;
class RWindow;
@@ -23,12 +20,6 @@ namespace ReWindow {
class VulkanWindow;
}
enum class WindowFlag: uint8_t {
IN_FOCUS, FULLSCREEN, RESIZABLE,
VSYNC, QUIT, MAX_FLAG
};
std::string WindowFlagToStr(WindowFlag flag);
class ReWindow::MouseState {
public:
struct
@@ -43,7 +34,7 @@ public:
}
Buttons;
IPair Position;
std::pair<int, int> Position;
int Wheel = 0;
public:
[[nodiscard]] bool IsDown(const MouseButton& btn) const;
@@ -59,32 +50,30 @@ protected:
Platform* platform;
inline static RWindow* extant;
int width = 1280;
int height = 720;
int width = 640;
int height = 480;
bool open = false; // Is the underlying OS-Window-Handle actually open.
bool closing = false;
bool resizable = true;
bool fullscreen_mode = false;
bool focused = true;
bool vsync = false;
bool cursor_visible = true;
bool closing = false;
bool cursor_focused = false;
bool toggling_cursor_focus = false;
bool key_repeat = false;
float delta_time = 0.f;
float refresh_rate = 0.f;
unsigned int refresh_count = 0;
IPair render_area_position = {0, 0};
unsigned long long refresh_count = 0;
std::string title = "Redacted Window";
IPair lastKnownWindowSize {0, 0};
// TODO remove the flags.
bool flags[5];
std::vector<RWindowEvent> eventLog; // history of all logged window events.
std::queue<RWindowEvent> eventQueue; //
MouseState currentMouse; // purrent frame mouse state.
MouseState previousMouse; // previous frame mouse state
// TODO: Why tf are these on the header and not just in the cpp?
float refresh_rate_prev_1 = 0.f;
float refresh_rate_prev_2 = 0.f;
float refresh_rate_prev_3 = 0.f;
@@ -92,12 +81,12 @@ protected:
float refresh_rate_prev_5 = 0.f;
float avg_refresh_rate = 0.0f;
/// Returns the most accurate and recent available mouse coordinates.
/// Returns the most accurate and recent available mouse coordinates relative to the top left corner of the renderable area (not including the title bar).
/// @note Call this version at most **once** per-frame. It polls the X-Window server and therefore is quite slow.
/// @see getCursorPos();
[[nodiscard]] IPair GetAccurateMouseCoordinates() const;
[[nodiscard]] std::pair<int, int> GetAccurateCursorCoordinates() const;
protected:
void LogEvent(const RWindowEvent& e) { eventLog.push_back(e);}
void LogEvent(const RWindowEvent& e) { eventLog.push_back(e); }
//void EnqueueEvent(const RWindowEvent& e) { eventQueue.push(e);}
[[nodiscard]] RWindowEvent GetLastEvent() const { return eventLog.back(); }
/// Requests the operating system to make the window fullscreen. Saves the previous window size as well.
@@ -108,9 +97,6 @@ protected:
public:
KeyboardState currentKeyboard; // current frame keyboard state.
KeyboardState previousKeyboard; // previous frame keyboard state.
// TODO: Josh hates parameter-flags, it's not 1995 :/
[[nodiscard]] bool GetFlag(WindowFlag flag) const;
void SetFlag(WindowFlag flag, bool state);
/// The default constructor does not set any members, and are left uninitialized.
RWindow();
@@ -147,59 +133,83 @@ public:
/// These methods can also be overridden in derived classes.
/// Called upon the window requesting to open.
virtual void OnOpen() {}
/// Called right before the window closes.
virtual void OnClosing() {}
/// Called when the window loses focus.
virtual void OnFocusLost(const RWindowEvent& e) {}
/// Called when the window gains focus.
virtual void OnFocusGain(const RWindowEvent& e) {}
/// Called when the window is 'refreshed', in other words, a render pass is completed.
virtual void OnRefresh(float elapsed) {}
/// Called when a resize request has succeeded.
virtual void OnResizeSuccess() {}
/// Called when a resize request is sent to the operating system.
virtual bool OnResizeRequest(const WindowResizeRequestEvent& e) { return true;}
virtual void OnKeyDown(const KeyDownEvent&) {}
virtual void OnKeyUp(const KeyUpEvent&) {}
virtual void OnMouseMove(const MouseMoveEvent&) {}
virtual void OnMouseButtonDown(const MouseButtonDownEvent&) {}
virtual void OnMouseButtonUp(const MouseButtonUpEvent&) {}
virtual void OnMouseWheel(const MouseWheelEvent&) {}
/// Returns an IPair representing mouse coordinates relative to the top-left corner of the window.
/// This result is cached from the operating-system, and as such may be out-of-date.
/// @see GetAccurateMouseCoordinates().
[[nodiscard]] IPair GetMouseCoordinates() const;
[[nodiscard]] int GetMouseWheelPersistent() const { return currentMouse.Wheel; }
[[nodiscard]] bool IsOpen() const { return open; }
/// Returns whether the window is currently visible to the user.
// TODO On Linux, Some desktop environments don't always do this when switching workspaces.
[[nodiscard]] bool IsVisible() const;
[[nodiscard]] bool IsClosing() const { return closing; }
/// Returns whether the window currently has mouse and/or keyboard focus.
[[nodiscard]] bool IsFocused() const;
/// Returns whether the window is currently in Fullscreen.
// TODO: Support Fullscreen, FullscreenWindowed, and Windowed?
[[nodiscard]] bool IsFullscreen() const;
/// Returns whether the window can be resized.
[[nodiscard]] bool IsResizable() const;
/// Returns whether V-Sync is enabled.
[[nodiscard]] bool IsVsyncEnabled() const;
/// Returns whether the window is considered to be alive. Once dead, any logic loop should be terminated, and the cleanup procedure should run.
[[nodiscard]] bool IsAlive() const;
/// Returns whether the given key is currently being pressed.
[[nodiscard]] bool IsKeyDown(Key key) const;
/// Returns whether the given mouse button is currently being pressed.
[[nodiscard]] bool IsMouseButtonDown(const MouseButton &button) const;
[[nodiscard]] bool IsMouseButtonDown(const MouseButton& button) const;
[[nodiscard]] float GetDeltaTime() const;
/// Returns the approximate frames-per-second using delta time.
[[nodiscard]] float GetRefreshRate() const;
/// Returns the number of frames ran since the windows' creation.
[[nodiscard]] float GetRefreshCounter() const;
[[nodiscard]] unsigned long long GetRefreshCount() const;
/// Cleans up and closes the window object.
void Close();
/// Closes the window immediately, potentially without allowing finalization to occur.
void ForceClose();
void ForceCloseAndTerminateProgram();
/** Display a small window with some text and an "OK" button.
* I tried un-defining the macro, Calling it in a lambda,
@@ -208,15 +218,14 @@ public:
* It just wouldn't let me name it MessageBox - Redacted. */
/// @note Execution of the parent window is stopped while the message box is up.
void UniqueFunctionNameForMessageBoxBecauseMicrosoftUsesMacros(const std::string& title, const std::string& message);
void DialogOK(const std::string& title, const std::string& message);
/// Sets whether or not to make the window fullscreen.
/// @note This is implemented per-OS, and as such, it simply requests the OS to do what we want. No guarantee about follow-through can be given.
/// Sets whether the window is fullscreen.
void SetFullscreen(bool fs);
/// Sets whether or not to make the window resizable.
/// @note This is implemented per-OS, and as such, it simply requests the OS to do what we want. No guarantee about follow-through can be given.
void SetResizable(bool resizable);
/// Sets whether the window can be resized by the user.
/// @note Resize events will still be sent if fullscreen is toggled.
void DisableResizing();
/// Sets the title of this window.
void SetTitle(const std::string& title);
@@ -224,12 +233,12 @@ public:
/// Returns the horizontal length of this window, in pixels.
[[nodiscard]] int GetWidth() const;
/// Returns the vertical length of this window, in pixels.
[[nodiscard]] int GetHeight() const;
/// This is unfortunately here because of the poor design of windows. Maybe once interfaces are done this won't be required anymore.
void SetSizeWithoutEvent(const IPair& size);
void SetLastKnownWindowSize(const IPair& size);
void SetSizeWithoutEvent(const std::pair<int, int>& size);
/// Tells the underlying window manager to destroy this window and drop the handle.
/// The window, in theory, can not be re-opened after this.
@@ -249,27 +258,25 @@ public:
/// @param width
/// @param height
void SetSize(int width, int height);
/// Requests the operating system to change the window size.
/// @param size
void SetSize(const IPair& size);
void SetSize(const std::pair<int, int>& size);
/// Returns the position of the window's top-left corner relative to the display
IPair GetPos() const;
[[nodiscard]] std::pair<int, int> GetPosition() const;
/// Returns the known size of the window, in {x,y} pixel measurement.
IPair GetSize() const;
/// Returns the position of the "renderable area" of the window relative to it's top left corner.
/// (used to account for the width or the border & title bar).
IPair GetPositionOfRenderableArea() const;
[[nodiscard]] std::pair<int, int> GetSize() const;
/// Requests the operating system to move the window to the specified coordinates on the display.
/// @param x The horizontal screen position to place the window at.
/// @param y The vertical screen position to place the window at.
void SetPos(int x, int y);
void SetPosition(int x, int y);
/// Requests the operating system to move the window to the specified coordinates on the display.
/// @param pos A IPair representing the x,y coordinates of the desired window destination. Fractional values are ignored.
void SetPos(const IPair& pos);
/// @param pos A std::pair<int, int> representing the x,y coordinates of the desired window destination. Fractional values are ignored.
void SetPosition(const std::pair<int, int>& pos);
/// Pull the window to the top, such that it is displayed on top of everything else.
/// NOTE: The implementation is defined per-OS, and thus there is no guarantee of it always working.
@@ -279,21 +286,44 @@ public:
/// NOTE: The implementation is defined per-OS, and thus there is no guarantee of it always working.
void Lower();
// TODO verify functionality if the cursor is invisible.
void SetCursorStyle(CursorStyle style) const;
void SetCursorCustomIcon() const;
void SetCursorLocked();
/// @returns Where the cursor was just before we teleported it to the center.
/// @note You should check if our window is in focus before doing this.
/// @note This is useful for 3D games.
std::pair<int, int> SetCursorCenter();
void SetCursorCenter();
/// Set the position of the cursor relative to the top-left corner of the renderable area.
/// @returns False if the cursor could not be guaranteed to be teleported.
/// @note our window *must* be visible and in focus.
/// @note Moving the cursor outside our window is unsupported.
/// @note Doesn't update where the mouse is observed for this refresh.
[[nodiscard]] bool SetCursorPosition(const std::pair<int, int>& position);
[[nodiscard]] bool SetCursorPosition(int x, int y);
void RestoreCursorFromLastCenter(); // Feels nicer for users
/// Tells the operating system to not allow the cursor to go off our window.
/// @note This is useful for 3D games.
void SetCursorFocused(bool state);
/// Hides the cursor when it's inside of our window. Useful for 3D game camera.
/// Hides the cursor when it's inside our window.
/// @note This is useful for 3D games.
void SetCursorVisible(bool cursor_enable);
/// @returns Whether the cursor is visible.
bool GetCursorVisible();
/// @returns Whether the cursor is focused (cannot go off of our window).
/// @note Delayed until the next time our window is in focus.
bool GetCursorFocused();
/// Returns an std::pair<int, int> representing mouse coordinates relative to the top-left corner of the window.
/// This result is cached from the operating-system each time poll events is called.
/// @see GetAccurateMouseCoordinates().
[[nodiscard]] std::pair<int, int> GetCursorPosition() const;
/// Returns the current time, represented as a high-resolution std::chrono alias.
static std::chrono::steady_clock::time_point GetTimestamp();
@@ -304,8 +334,8 @@ public:
void UpdateFrameTiming(float frame_time);
public:
/// These unfortunately *have* to be public because of the poor design of the windows event loop.
void processKeyRelease (Key key);
void processKeyPress (Key key);
void processKeyRelease(Key key);
void processKeyPress(Key key);
/// @note This will be invoked **before** the window-close procedure begins.
void processOnClose();
/// @note This will be invoked **after** the window-open procedure completes.
@@ -314,17 +344,23 @@ public:
void processMouseRelease(const MouseButton& btn);
void processFocusIn();
void processFocusOut();
void processMouseMove(IPair last_pos, IPair new_pos);
void processMouseMove(const std::pair<int, int>& last_pos, const std::pair<int, int>& new_pos);
void processMouseWheel(int scrolls);
/// Virtual functions which *must* be overridden based on the Renderer.
public:
virtual void SwapBuffers() = 0;
/// Sets whether or not to enable vertical synchronization.
/// Sets whether vertical sync is enabled.
/// @note This is implemented per-OS, and as such, it simply requests the OS to do what we want. No guarantee about follow-through can be given.
virtual void SetVsyncEnabled(bool state) = 0;
/// Sets whether we're using key repeat.
void SetKeyRepeatEnabled(bool state);
/// @returns If key repeat is enabled.
[[nodiscard]] bool IsKeyRepeat() const { return key_repeat; };
/// Returns the name of the developer of the user's graphics driver, if it can be determined.
virtual std::string GetGraphicsDriverVendor() = 0;
@@ -341,7 +377,7 @@ public:
[[nodiscard]] virtual bool SoftwareRendered() { return false; }
};
// TODO in the event that we can't find OpenGL or the Open() fails, have a way to say so without throwing an exception.
// TODO Set flags in window constructor.
class ReWindow::OpenGLWindow : public RWindow {
protected:
uint8_t gl_major, gl_minor;

View File

@@ -3,7 +3,6 @@
#include <chrono>
#include <ReWindow/types/Key.h>
#include <ReWindow/types/MouseButton.h>
#include <ReWindow/types/Pair.h>
namespace ReWindow {
@@ -62,11 +61,11 @@ namespace ReWindow {
class MouseMoveEvent : public MouseEvent {
public:
IPair Position;
IPair Delta;
MouseMoveEvent(const IPair &pos) : MouseEvent(), Position(pos)
std::pair<int, int> Position;
std::pair<int, int> Delta;
MouseMoveEvent(const std::pair<int, int> &pos) : MouseEvent(), Position(pos)
{}
MouseMoveEvent(int x, int y) : MouseEvent(), Position(IPair(x, y))
MouseMoveEvent(int x, int y) : MouseEvent(), Position(std::pair<int, int>(x, y))
{}
};
@@ -93,6 +92,6 @@ namespace ReWindow {
class WindowResizeRequestEvent : public MouseButtonEvent
{
public:
IPair Size;
std::pair<int, int> Size;
};
}

View File

@@ -1,15 +1,10 @@
#include <iostream>
#include <ReWindow/types/Window.h>
#if _WIN32
#include <windows.h>
#endif
#include <ReWindow/Logger.h>
using namespace ReWindow;
std::ostream& operator<<(std::ostream& os, const IPair& v) {
return os << "{" << v.x << ", " << v.y << "}";
using namespace ReWindow;
std::ostream& operator<<(std::ostream& os, const std::pair<int, int>& v) {
return os << "{" << v.first << ", " << v.second << "}";
}
class MyWindow : public OpenGLWindow {
@@ -18,11 +13,18 @@ class MyWindow : public OpenGLWindow {
void OnMouseMove(const MouseMoveEvent& e) override {}
void OnKeyDown(const KeyDownEvent& e) override {}
void OnKeyDown(const KeyDownEvent& e) override {
if (e.key == Keys::F11)
SetFullscreen(!IsFullscreen());
}
void OnRefresh(float elapsed) override {
SwapBuffers();
bool OnResizeRequest(const WindowResizeRequestEvent& e) override { return true; }
void OnMouseButtonDown(const MouseButtonDownEvent& e) override { RWindow::OnMouseButtonDown(e); }
void OnMouseButtonUp(const MouseButtonUpEvent& e) override { RWindow::OnMouseButtonUp(e); }
void OnRefresh(float elapsed) override {
if (IsMouseButtonDown(MouseButtons::Left))
std::cout << "Left Mouse Button" << std::endl;
@@ -38,28 +40,7 @@ class MyWindow : public OpenGLWindow {
if (IsMouseButtonDown(MouseButtons::Mouse5))
std::cout << "Mouse5 Mouse Button" << std::endl;
if (IsKeyDown(Keys::N))
std::cout << "Gotteem" << std::endl;
RWindow::OnRefresh(elapsed);
}
bool OnResizeRequest(const WindowResizeRequestEvent& e) override {
//std::cout << "resized to " << e.Size.x << ", " << e.Size.y << std::endl;
return true;
}
void OnMouseButtonDown(const MouseButtonDownEvent &e) override
{
//std::cout << "Overload Down: " << e.Button.Mnemonic << std::endl;
RWindow::OnMouseButtonDown(e);
}
void OnMouseButtonUp(const MouseButtonUpEvent &e) override
{
//std::cout << "Overload Up: " << e.Button.Mnemonic << std::endl;
RWindow::OnMouseButtonUp(e);
SwapBuffers();
}
};
@@ -71,16 +52,16 @@ int main() {
Logger::Debug(std::format("Opened window '{}'", window->GetTitle()));
Logger::Debug("TODO: Cannot set flags until after window is open");
window->SetFullscreen(false);
window->SetVsyncEnabled(true);
window->SetResizable(true);
window->SetCursorVisible(false);
window->UniqueFunctionNameForMessageBoxBecauseMicrosoftUsesMacros("MessageBox", "Generic message from a ReWindow MessageBox.");
window->DisableResizing();
window->SetKeyRepeatEnabled(false);
Logger::Debug(std::format("Window '{}' flags: IN_FOCUS={} FULLSCREEN={} RESIZEABLE={} VSYNC={} QUIT={}",
window->GetTitle(), window->IsFocused(), window->IsFullscreen(),
window->IsResizable(), window->IsVsyncEnabled(), window->IsClosing()) );
Logger::Debug(std::format
(
"Window '{}' flags: IN_FOCUS={} FULLSCREEN={} RESIZEABLE={} VSYNC={} KEY_REPEAT={} QUIT={}",
window->GetTitle(), window->IsFocused(), window->IsFullscreen(), window->IsResizable(),
window->IsVsyncEnabled(), window->IsKeyRepeat(), window->IsClosing())
);
window->OnKeyDownEvent += [&] (KeyDownEvent e) { jlog::Debug(e.key.Mnemonic); };
@@ -88,8 +69,10 @@ int main() {
window->OnMouseWheelEvent += [&, window] (MouseWheelEvent e) { std::cout << window->GetMouseWheelPersistent() << std::endl; };
while (!window->IsClosing()) {
window->ManagedRefresh();
//window->Flash();
}
window->ManagedRefresh();
if (window->IsFocused())
window->SetCursorCenter();
}
delete window;
}

View File

@@ -8,10 +8,10 @@ namespace InputService
bool IsMouseButtonDown(const MouseButton &button) {
return RWindow::GetExtant()->IsMouseButtonDown(button);
}
IPair GetMousePosition() {
return RWindow::GetExtant()->GetMouseCoordinates();
std::pair<int, int> GetMousePosition() {
return RWindow::GetExtant()->GetCursorPosition();
}
IPair GetWindowSize() {
std::pair<int, int> GetWindowSize() {
return RWindow::GetExtant()->GetSize();
}
}

View File

@@ -22,6 +22,7 @@ public:
XSizeHints hints;
Cursor invisible_cursor = 0;
XWMHints* wm_hints = nullptr;
GLXContext gl_context;
};
void* glx_lib = nullptr;
@@ -57,16 +58,26 @@ namespace OpenGL {
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display *, GLXFBConfig, GLXContext, Bool, const int *);
}
GLXContext gl_context;
// Used to determine if we should force our window to start as floating on tiling window managers.
[[nodiscard]] bool TilingWindowManager() {
const char* xdg_env = std::getenv("XDG_CURRENT_DESKTOP");
const char* session_env = std::getenv("DESKTOP_SESSION");
std::string xdg_current_desktop = xdg_env ? xdg_env : "";
std::string desktop_session = session_env ? session_env : "";
if (xdg_current_desktop == "i3" || desktop_session == "i3")
return true;
return false;
// TODO check for dwm & sway.
}
void OpenGLWindow::SwapBuffers() {
OpenGL::glXSwapBuffers(platform->display,platform->window);
}
void OpenGLWindow::SetVsyncEnabled(bool state) {
PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT;
glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) OpenGL::glXGetProcAddressARB((const GLubyte *) "glXSwapIntervalEXT");
auto glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) OpenGL::glXGetProcAddressARB((const GLubyte *) "glXSwapIntervalEXT");
glXSwapIntervalEXT(platform->display, platform->window, state);
}
@@ -75,6 +86,8 @@ std::string OpenGLWindow::GetGraphicsDriverVendor() {
}
bool OpenGLWindow::Open() {
bool tiling = TilingWindowManager();
if (!OpenGL::constructor_success)
return false;
@@ -83,9 +96,11 @@ bool OpenGLWindow::Open() {
platform->xSetWindowAttributes.border_pixel = BlackPixel(platform->display, platform->defaultScreen);
platform->xSetWindowAttributes.background_pixel = BlackPixel(platform->display, platform->defaultScreen);
platform->xSetWindowAttributes.override_redirect = True;
platform->xSetWindowAttributes.event_mask = ExposureMask;
if (tiling)
platform->xSetWindowAttributes.override_redirect = True;
auto glXCreateContextAttribsARB = (OpenGL::glXCreateContextAttribsARBProc) OpenGL::glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB");
XVisualInfo* vi = nullptr;
@@ -93,7 +108,7 @@ bool OpenGLWindow::Open() {
if (!glXCreateContextAttribsARB) {
GLint glAttributes[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None};
platform->visual = OpenGL::glXChooseVisual(platform->display, platform->defaultScreen, glAttributes);
gl_context = OpenGL::glXCreateContext(platform->display, platform->visual, nullptr, GL_TRUE);
platform->gl_context = OpenGL::glXCreateContext(platform->display, platform->visual, nullptr, GL_TRUE);
platform->window = XCreateWindow(platform->display, RootWindow(platform->display, platform->defaultScreen), 0, 0, width, height, 0, platform->visual->depth,
InputOutput, platform->visual->visual, CWBackPixel | CWColormap | CWBorderPixel | NoEventMask, &platform->xSetWindowAttributes);
Logger::Debug("Created OpenGL Context with glXCreateContext.");
@@ -127,36 +142,38 @@ bool OpenGLWindow::Open() {
platform->window = XCreateWindow(platform->display, RootWindow(platform->display, vi->screen), 0, 0, width, height, 0, vi->depth, InputOutput,
vi->visual, CWBackPixel | CWColormap | CWBorderPixel, &platform->xSetWindowAttributes);
// TODO allow the user to specify what OpenGL version they want.
int context_attributes[] { GLX_CONTEXT_MAJOR_VERSION_ARB, gl_major, GLX_CONTEXT_MINOR_VERSION_ARB, gl_minor, None };
gl_context = glXCreateContextAttribsARB(platform->display, best_fbc, nullptr, True, context_attributes);
platform->gl_context = glXCreateContextAttribsARB(platform->display, best_fbc, nullptr, True, context_attributes);
XFree(fb_configurations);
Logger::Debug("Created OpenGL Context with glXCreateContextAttribsARB");
}
if (!gl_context)
if (!platform->gl_context)
return false;
if (!OpenGL::glXMakeCurrent(platform->display, platform->window, gl_context))
if (!OpenGL::glXMakeCurrent(platform->display, platform->window, platform->gl_context))
return false;
if (vi)
XFree(vi);
XSelectInput(platform->display, platform->window, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | CWColormap );
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | VisibilityChangeMask | CWColormap );
XMapWindow(platform->display, platform->window);
XStoreName(platform->display, platform->window, title.c_str());
platform->windowTypeAtom = XInternAtom(platform->display, "_NET_WM_WINDOW_TYPE", False);
platform->windowTypeUtilityAtom = XInternAtom(platform->display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
XChangeProperty(platform->display, platform->window, platform->windowTypeAtom, XA_ATOM, 32, PropModeReplace, (unsigned char*) &platform->windowTypeUtilityAtom, 1);
if (tiling) {
platform->windowTypeAtom = XInternAtom(platform->display, "_NET_WM_WINDOW_TYPE", False);
platform->windowTypeUtilityAtom = XInternAtom(platform->display, "_NET_WM_WINDOW_TYPE_UTILITY", False);
XChangeProperty(platform->display, platform->window, platform->windowTypeAtom, XA_ATOM, 32, PropModeReplace,
(unsigned char *) &platform->windowTypeUtilityAtom, 1);
}
platform->wmDeleteWindow = XInternAtom(platform->display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(platform->display, platform->window, &platform->wmDeleteWindow, 1);
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
render_area_position = { platform->windowAttributes.x, platform->windowAttributes.y };
open = true;
processOnOpen();
@@ -172,9 +189,22 @@ OpenGLWindow::OpenGLWindow(const std::string& title, int width, int height, uint
if (!glx_lib)
glx_lib = dlopen("libGLX.so", RTLD_LAZY);
if (!glx_lib)
glx_lib = dlopen("libGLX.so.0", RTLD_LAZY);
if (!opengl_lib)
opengl_lib = dlopen("libGL.so", RTLD_LAZY);
if (!opengl_lib)
opengl_lib = dlopen("libOpenGL.so", RTLD_LAZY);
if (!opengl_lib)
opengl_lib = dlopen("libOpenGL.so.0", RTLD_LAZY);
if (!opengl_lib)
opengl_lib = dlopen("libOpenGL.so.0.0.0", RTLD_LAZY);
if (!opengl_lib)
Logger::Error("libOpenGL.so couldn't be found in your LD_LIBRARY_PATH."),
OpenGL::constructor_success = false;
@@ -196,6 +226,7 @@ OpenGLWindow::OpenGLWindow(const std::string& title, int width, int height, uint
bool OpenGLWindow::SoftwareRendered() {
std::string renderer((const char*) OpenGL::glGetString(GL_RENDERER));
if (renderer.find("llvmpipe"))
return true;
if (renderer.find("softpipe"))

View File

@@ -211,7 +211,7 @@ bool VulkanWindow::Open() {
XSelectInput(platform->display, platform->window, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | CWColormap );
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask | SubstructureNotifyMask | VisibilityChangeMask | CWColormap );
XMapWindow(platform->display, platform->window);
XStoreName(platform->display, platform->window, title.c_str());
@@ -223,7 +223,6 @@ bool VulkanWindow::Open() {
XSetWMProtocols(platform->display, platform->window, &platform->wmDeleteWindow, 1);
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
render_area_position = { platform->windowAttributes.x, platform->windowAttributes.y };
open = true;
processOnOpen();
@@ -239,7 +238,7 @@ void VulkanWindow::SetVsyncEnabled(bool state) {
}
std::string VulkanWindow::GetGraphicsDriverVendor() {
return "Unknown OpenGL";// TODO: Implement properly!
}
VulkanWindow::VulkanWindow(const std::string& title, int width, int height) : RWindow(title, width, height) {

View File

@@ -21,11 +21,45 @@ public:
XSizeHints hints;
Cursor invisible_cursor = 0;
XWMHints* wm_hints = nullptr;
bool window_visible = true;
std::pair<int, int> position = { 0, 0 };
std::pair<int, int> size_before_fullscreen {0, 0};
};
using namespace ReWindow;
void RWindow::SetSize(const std::pair<int, int>& size) {
this->SetSize(size.first, size.second);
}
bool RWindow::SetCursorPosition(const std::pair<int, int>& position) {
if (!IsFocused())
return false;
if (!IsVisible())
return false;
if (position.first > GetWidth() || position.first < 0)
return false;
if (position.second > GetHeight() || position.second < 0)
return false;
// TODO XWarpPointer has no way to verify it actually happened.
XWarpPointer(platform->display, None, platform->window, 0, 0, 0, 0, position.first, position.second);
return true;
}
void RWindow::SetKeyRepeatEnabled(bool state) {
key_repeat = state;
if (state)
return (void) XAutoRepeatOn(platform->display);
XAutoRepeatOff(platform->display);
}
void RWindow::Flash() {
if (IsFocused())
return;
@@ -38,79 +72,93 @@ void RWindow::Flash() {
}
RWindow::RWindow() {
platform = new Platform();
extant = this;
}
IPair position;
RWindow::RWindow(const std::string& wTitle, int wWidth, int wHeight, bool wFullscreen, bool wResizable, bool wVsync)
: title(wTitle), width(wWidth), height(wHeight), fullscreen_mode(wFullscreen), resizable(wResizable), vsync(wVsync),
flags{false,wFullscreen,wResizable,wVsync} {
platform = new Platform();
extant = this;
}
void RWindow::SetCursorFocused(bool state) {
toggling_cursor_focus = state;
if (!state && cursor_focused) {
XUngrabPointer(platform->display, CurrentTime);
cursor_focused = state;
return;
}
}
std::pair<int, int> RWindow::SetCursorCenter() {
auto current_pos = GetAccurateCursorCoordinates();
XWarpPointer(platform->display, None, platform->window, 0, 0, 0, 0, width / 2, height / 2);
return current_pos;
}
RWindow::RWindow(const std::string& wTitle, int wWidth, int wHeight, bool wFullscreen, bool wResizable, bool wVsync)
: title(wTitle), width(wWidth), height(wHeight), fullscreen_mode(wFullscreen), resizable(wResizable), vsync(wVsync)
{ platform = new Platform(); extant = this; }
void RWindow::Raise() {
Logger::Debug(std::format("Raising window '{}'", this->title));
// Get the position of the renderable area relative to the rest of the window.
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
render_area_position = { platform->windowAttributes.x, platform->windowAttributes.y };
XRaiseWindow(platform->display, platform->window);
}
void RWindow::UniqueFunctionNameForMessageBoxBecauseMicrosoftUsesMacros(const std::string& window_title, const std::string& message) {
void RWindow::DialogOK(const std::string& window_title, const std::string& message) {
int padding = 10;
XFontStruct* font = XLoadQueryFont(platform->display, "6x13");
int text_width = XTextWidth(font, message.c_str(), message.size());
int button_text_width = XTextWidth(font, "OK", 2);
IPair button_size = {80, 30};
IPair dimensions = { std::max(text_width + 2 * padding, button_size.x + 2 * padding), 82};
IPair text_pos = {(dimensions.x - text_width) / 2, padding + font->ascent};
IPair button_pos = { (dimensions.x - button_size.x) / 2, text_pos.y + font->ascent + padding };
std::pair<int, int> button_size = {80, 30};
std::pair<int, int> dimensions = { std::max(text_width + 2 * padding, button_size.first + 2 * padding), 82};
std::pair<int, int> text_pos = {(dimensions.first - text_width) / 2, padding + font->ascent};
std::pair<int, int> button_pos = { (dimensions.first - button_size.first) / 2, text_pos.second + font->ascent + padding };
Window window = XCreateSimpleWindow(platform->display, RootWindow(platform->display, platform->defaultScreen),
100, 100, dimensions.x, dimensions.y, 1,
100, 100, dimensions.first, dimensions.second, 1,
BlackPixel(platform->display, platform->defaultScreen),
WhitePixel(platform->display, platform->defaultScreen));
XStoreName(platform->display, window, window_title.c_str());
XSelectInput(platform->display, window, ExposureMask | ButtonPressMask);
XSelectInput(platform->display, window, ExposureMask | ButtonPressMask | StructureNotifyMask);
// No resizing.
XSizeHints hints;
hints.flags = PMinSize | PMaxSize;
hints.min_width = hints.max_width = dimensions.x;
hints.min_height = hints.max_height = dimensions.y;
hints.min_width = hints.max_width = dimensions.first;
hints.min_height = hints.max_height = dimensions.second;
XSetWMNormalHints(platform->display, window, &hints);
Atom wm_delete_window = XInternAtom(platform->display, "WM_DELETE_WINDOW", False);
XSetWMProtocols(platform->display, window, &wm_delete_window, 1);
XMapWindow(platform->display, window);
GC gc = XCreateGC(platform->display, window, 0, nullptr);
XSetForeground(platform->display, gc, BlackPixel(platform->display, platform->defaultScreen));
/* TODO positioning the window to be in the center of the parent window doesn't always work.
if (platform->window) {
XWindowAttributes parent_window_attributes;
XGetWindowAttributes(platform->display, platform->window, &parent_window_attributes);
XMoveWindow(platform->display, window, (parent_window_attributes.width - dimensions.x) / 2, (parent_window_attributes.height - dimensions.y) / 2);
}
*/
XEvent event;
while (true) {
XNextEvent(platform->display, &event);
if (event.type == Expose) {
XDrawString(platform->display, window, gc, text_pos.x, text_pos.y, message.c_str(), message.size());
XDrawString(platform->display, window, gc, button_pos.x + (button_size.x - button_text_width) / 2, button_pos.y + 20, "OK", 2);
XDrawRectangle(platform->display, window, gc, button_pos.x, button_pos.y, button_size.x, button_size.y);
XDrawString(platform->display, window, gc, text_pos.first, text_pos.second, message.c_str(), message.size());
XDrawString(platform->display, window, gc, button_pos.first + (button_size.first - button_text_width) / 2, button_pos.second + 20, "OK", 2);
XDrawRectangle(platform->display, window, gc, button_pos.first, button_pos.second, button_size.first, button_size.second);
}
else if (event.type == ButtonPress)
if (event.xbutton.x >= button_pos.x && event.xbutton.x <= button_pos.x + button_size.x
&& event.xbutton.y >= button_pos.y && event.xbutton.y <= button_pos.y + button_size.y)
else if (event.type == ClientMessage) {
if (event.xclient.message_type == XInternAtom(platform->display, "WM_PROTOCOLS", False) &&
static_cast<Atom>(event.xclient.data.l[0]) == wm_delete_window)
break;
}
else if (event.type == ButtonPress) {
if (event.xbutton.x >= button_pos.first && event.xbutton.x <= button_pos.first + button_size.first
&& event.xbutton.y >= button_pos.second && event.xbutton.y <= button_pos.second + button_size.second)
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(5));
}
XFreeFont(platform->display, font);
@@ -126,6 +174,7 @@ void RWindow::Lower()
void RWindow::DestroyOSWindowHandle() {
// Turn key repeat back on.
XAutoRepeatOn(platform->display);
XFlush(platform->display);
Logger::Debug(std::format("Destroying sub-windows for window '{}'", this->title));
XDestroySubwindows(platform->display, platform->window);
@@ -134,10 +183,9 @@ void RWindow::DestroyOSWindowHandle() {
XDestroyWindow(platform->display, platform->window);
XCloseDisplay(platform->display);
delete platform;
}
//void RWindow::
void RWindow::SetCursorVisible(bool cursor_enable) {
cursor_visible = cursor_enable;
if (platform->invisible_cursor == 0) {
@@ -154,31 +202,15 @@ void RWindow::SetCursorVisible(bool cursor_enable) {
XUndefineCursor(platform->display, platform->window);
}
void RWindow::SetResizable(bool sizable) {
void RWindow::DisableResizing() {
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
this->resizable = sizable;
if (!sizable) {
Logger::Debug("Once you've done this you cannot make it resizable again.");
platform->hints.flags = PMinSize | PMaxSize;
platform->hints.min_width = platform->hints.max_width = platform->windowAttributes.width;
platform->hints.min_height = platform->hints.max_height = platform->windowAttributes.height;
XSetWMNormalHints(platform->display, platform->window, &platform->hints);
}
}
platform->hints.flags = PMinSize | PMaxSize;
platform->hints.min_width = platform->hints.max_width = platform->windowAttributes.width;
platform->hints.min_height = platform->hints.max_height = platform->windowAttributes.height;
XSetWMNormalHints(platform->display, platform->window, &platform->hints);
void RWindow::SetFlag(WindowFlag flag, bool state) {
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
flags[(int) flag] = state;
//Once you've done this you cannot make it resizable again.
if (flag == WindowFlag::RESIZABLE && !state) {
Logger::Debug("Once you've done this you cannot make it resizable again.");
platform->hints.flags = PMinSize | PMaxSize;
platform->hints.min_width = platform->hints.max_width = platform->windowAttributes.width;
platform->hints.min_height = platform->hints.max_height = platform->windowAttributes.height;
XSetWMNormalHints(platform->display, platform->window, &platform->hints);
}
Logger::Debug(std::format("Set flag '{}' to state '{}' for window '{}'", WindowFlagToStr(flag), state, this->title));
this->resizable = false;
}
void RWindow::PollEvents() {
@@ -188,13 +220,25 @@ void RWindow::PollEvents() {
if (platform->xev.type == ClientMessage)
Logger::Info(std::format("Event '{}'", "ClientMessage"));
if (platform->xev.xclient.message_type == XInternAtom(platform->display, "WM_PROTOCOLS", False) && static_cast<Atom>(platform->xev.xclient.data.l[0]) == platform->wmDeleteWindow) {
if (platform->xev.xclient.message_type == XInternAtom(platform->display, "WM_PROTOCOLS", False) &&
static_cast<Atom>(platform->xev.xclient.data.l[0]) == platform->wmDeleteWindow) {
Close();
}
if (platform->xev.type == FocusIn) {
Logger::Debug(std::format("Event'{}'", "FocusIn"));
XAutoRepeatOff(platform->display);
if (!key_repeat)
XAutoRepeatOff(platform->display);
else
XAutoRepeatOn(platform->display);
XFlush(platform->display);
if (cursor_focused) {
cursor_focused = false;
SetCursorFocused(true);
}
if (platform->wm_hints) {
platform->wm_hints->flags &= ~XUrgencyHint;
@@ -206,14 +250,26 @@ void RWindow::PollEvents() {
// Get the position of the renderable area relative to the rest of the window.
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
render_area_position = { platform->windowAttributes.x, platform->windowAttributes.y };
processFocusIn();
focused = true;
}
if (platform->xev.type == UnmapNotify) {
if (cursor_focused) {
SetCursorFocused(false);
cursor_focused = true;
}
}
if (platform->xev.type == FocusOut) {
Logger::Debug(std::format("Event '{}'", "FocusOut"));
XAutoRepeatOn(platform->display);
XFlush(platform->display);
if (cursor_focused) {
SetCursorFocused(false);
cursor_focused = true;
}
if (!cursor_visible)
XUndefineCursor(platform->display, platform->window);
@@ -257,8 +313,7 @@ void RWindow::PollEvents() {
processMouseWheel(-1);
} else if (platform->xev.xbutton.button == 5) {
processMouseWheel(1);
} else
{
} else {
MouseButton button = GetMouseButtonFromXButton(platform->xev.xbutton.button);
Logger::Debug(std::format("Event: MouseButtonPress {}", button.Mnemonic));
@@ -267,37 +322,58 @@ void RWindow::PollEvents() {
}
}
if (platform->xev.type == Expose)
{
if (platform->xev.type == Expose) {
Logger::Debug(std::format("Event '{}'", "Expose"));
}
// NOTE: This event is functionally useless, as it only informs of the very beginning and end of a mouse movement.
if (platform->xev.type == MotionNotify)
{
Logger::Debug(std::format("Event '{}'", "MotionNotify"));
if (platform->xev.type == MotionNotify) {
if (toggling_cursor_focus) {
XWindowAttributes attrs;
XGetWindowAttributes(platform->display, platform->window, &attrs);
if (attrs.map_state == IsViewable) {
int result = XGrabPointer
(
platform->display, platform->window, True,
ButtonPressMask | ButtonReleaseMask | PointerMotionMask,
GrabModeAsync, GrabModeAsync, platform->window, None, CurrentTime
);
if (result == GrabSuccess) {
toggling_cursor_focus = false;
cursor_focused = true;
}
}
}
}
if (platform->xev.type == ConfigureNotify) {
if (this->width != platform->xev.xconfigurerequest.width || this->height != platform->xev.xconfigurerequest.height) {
if (this->width != platform->xev.xconfigurerequest.width ||
this->height != platform->xev.xconfigurerequest.height) {
Logger::Debug(std::format("Event '{}'", "ResizeRequest"));
this->width = platform->xev.xconfigurerequest.width;
this->height = platform->xev.xconfigurerequest.height;
auto eventData = WindowResizeRequestEvent();
eventData.Size = { platform->xev.xconfigurerequest.width, platform->xev.xconfigurerequest.height };
lastKnownWindowSize = eventData.Size;
eventData.Size = {platform->xev.xconfigurerequest.width, platform->xev.xconfigurerequest.height};
OnResizeRequest(eventData);
OnResizeRequestEvent(eventData);
}
//Window Moved.
if (position.x != platform->xev.xconfigurerequest.x || position.y != platform->xev.xconfigurerequest.y)
position = { platform->xev.xconfigurerequest.x, platform->xev.xconfigurerequest.y };
if (platform->position.first != platform->xev.xconfigurerequest.x || platform->position.second != platform->xev.xconfigurerequest.y)
platform->position = { platform->xev.xconfigurerequest.x, platform->xev.xconfigurerequest.y };
}
if (platform->xev.type == VisibilityNotify) {
if (platform->xev.xvisibility.state == VisibilityFullyObscured)
platform->window_visible = false;
else if (platform->xev.xvisibility.state == VisibilityUnobscured ||
platform->xev.xvisibility.state == VisibilityPartiallyObscured)
platform->window_visible = true;
}
}
previousKeyboard = currentKeyboard;
previousMouse.Buttons = currentMouse.Buttons;
@@ -306,7 +382,8 @@ void RWindow::PollEvents() {
// Might make the window go off the screen on some window managers.
void RWindow::SetSize(int newWidth, int newHeight) {
if (!resizable) return;
if (!resizable)
return;
this->width = newWidth;
this->height = newHeight;
@@ -315,8 +392,7 @@ void RWindow::SetSize(int newWidth, int newHeight) {
Logger::Info(std::format("Set size for '{}' to {} x {}", this->title, newWidth, newHeight));
}
IPair RWindow::GetAccurateMouseCoordinates() const {
std::pair<int, int> RWindow::GetAccurateCursorCoordinates() const {
Window root_return, child_return;
int root_x_ret, root_y_ret;
int win_x_ret, win_y_ret;
@@ -328,72 +404,118 @@ IPair RWindow::GetAccurateMouseCoordinates() const {
if (mouseAvailable) {
// TODO: normalize coordinates from platform->displaySpace to windowSpace
// TODO: fire mouse movement event
IPair m_coords = { win_x_ret, win_y_ret };
std::pair<int, int> m_coords = { win_x_ret, win_y_ret };
return m_coords;
}
return {};
}
IPair RWindow::GetSize() const {
return { this->width, this->height};
bool RWindow::IsVisible() const {
return platform->window_visible;
}
//IPair RWindow::getLastKnownResize() const
//{
// return lastKnownWindowSize;
//}
// TODO: implement integer IPair/3 types
IPair RWindow::GetPos() const {
return position;
// TODO: implement integer std::pair<int, int>/3 types
std::pair<int, int> RWindow::GetPosition() const {
return platform->position;
}
void RWindow::SetPos(int x, int y) {
std::pair<int, int> RWindow::GetSize() const { return { this->width, this->height }; }
void RWindow::SetPosition(int x, int y) {
XMoveWindow(platform->display, platform->window, x, y);
position = {x, y};
platform->position = {x, y};
}
void RWindow::SetPos(const IPair& pos) {
SetPos(pos.x, pos.y);
void RWindow::SetPosition(const std::pair<int, int>& pos) {
SetPosition(pos.first, pos.second);
}
void RWindow::Fullscreen() {
Logger::Info(std::format("Fullscreening '{}'", this->title));
fullscreen_mode = true;
platform->size_before_fullscreen = GetSize();
XEvent xev;
Atom wm_state = XInternAtom(platform->display, "_NET_WM_STATE", true);
Atom wm_fullscreen = XInternAtom(platform->display, "_NET_WM_STATE_FULLSCREEN", true);
if (!this->resizable) {
XSizeHints hints;
hints.flags = PMinSize | PMaxSize;
hints.min_width = 0;
hints.min_height = 0;
hints.max_width = 100000;
hints.max_height = 100000;
XSetWMNormalHints(platform->display, platform->window, &hints);
XFlush(platform->display);
}
XChangeProperty(platform->display, platform->window, wm_state, XA_ATOM, 32, PropModeReplace, (unsigned char *)&wm_fullscreen, 1);
memset(&xev, 0, sizeof(xev));
Atom wm_state = XInternAtom(platform->display, "_NET_WM_STATE", False);
Atom wm_fullscreen = XInternAtom(platform->display, "_NET_WM_STATE_FULLSCREEN", False);
if (!wm_state || !wm_fullscreen) {
Logger::Error("We don't have the required atom for fullscreen graphics mode?");
return;
}
XEvent xev{};
xev.type = ClientMessage;
xev.xclient.window = platform->window;
xev.xclient.message_type = wm_state;
xev.xclient.format = 32;
xev.xclient.data.l[0] = 1; // _NET_WM_STATE_ADD
xev.xclient.data.l[1] = fullscreen_mode;
xev.xclient.data.l[0] = 1;
xev.xclient.data.l[1] = wm_fullscreen;
xev.xclient.data.l[2] = 0;
XSendEvent(platform->display, DefaultRootWindow(platform->display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
xev.xclient.data.l[3] = 1;
xev.xclient.data.l[4] = 0;
XSendEvent(platform->display,
DefaultRootWindow(platform->display),
False,
SubstructureNotifyMask | SubstructureRedirectMask,
&xev);
XFlush(platform->display);
fullscreen_mode = true;
Logger::Debug(std::format("Fullscreened '{}'", this->title));
}
void RWindow::RestoreFromFullscreen() {
Logger::Debug(std::format("Restoring '{}' from Fullscreen", this->title));
fullscreen_mode = false;
XEvent xev;
Atom wm_state = XInternAtom(platform->display, "_NET_WM_STATE", False);
Atom fullscreen = XInternAtom(platform->display, "_NET_WM_STATE_FULLSCREEN", False);
memset(&xev, 0, sizeof(xev));
if (!wm_state || !fullscreen) {
Logger::Error("We don't have the required atom for fullscreen graphics mode?");
return;
}
XEvent xev{};
xev.type = ClientMessage;
xev.xclient.window = platform->window;
xev.xclient.message_type = wm_state;
xev.xclient.format = 32;
xev.xclient.data.l[0] = 0; // _NET_WM_STATE_REMOVE
xev.xclient.data.l[1] = fullscreen_mode;
xev.xclient.data.l[0] = 0;
xev.xclient.data.l[1] = fullscreen;
xev.xclient.data.l[2] = 0;
XSendEvent(platform->display, DefaultRootWindow(platform->display), False, SubstructureNotifyMask | SubstructureRedirectMask, &xev);
xev.xclient.data.l[3] = 1;
xev.xclient.data.l[4] = 0;
XSendEvent(
platform->display,
DefaultRootWindow(platform->display),
False,
SubstructureNotifyMask | SubstructureRedirectMask,
&xev
);
if (!this->resizable) {
XSizeHints hints;
hints.flags = PMinSize | PMaxSize;
hints.min_width = hints.max_width = platform->size_before_fullscreen.first;
hints.min_height = hints.max_height = platform->size_before_fullscreen.second;
XSetWMNormalHints(platform->display, platform->window, &hints);
this->width = platform->size_before_fullscreen.first;
this->height = platform->size_before_fullscreen.second;
}
XFlush(platform->display);
fullscreen_mode = false;
Logger::Debug(std::format("Restored '{}' from Fullscreen", this->title));
}
@@ -408,9 +530,3 @@ void RWindow::SetTitle(const std::string& title) {
XStoreName(platform->display, platform->window, title.c_str());
}
IPair RWindow::GetPositionOfRenderableArea() const {
return render_area_position;
}

View File

@@ -1,18 +1,6 @@
#include <ReWindow/types/Window.h>
#include <ReWindow/InputService.h>
#include <ReWindow/Logger.h>
std::string WindowFlagToStr(WindowFlag flag) {
switch (flag) {
case WindowFlag::IN_FOCUS: return "IN_FOCUS";
case WindowFlag::FULLSCREEN: return "FULLSCREEN";
case WindowFlag::RESIZABLE: return "RESIZEABLE";
case WindowFlag::VSYNC: return "VSYNC";
case WindowFlag::QUIT: return "QUIT";
case WindowFlag::MAX_FLAG: return "MAX_FLAG";
default:
return "unimplemented flag";
}
};
using namespace ReWindow;
@@ -21,16 +9,10 @@ RWindow::~RWindow() {
DestroyOSWindowHandle();
}
IPair RWindow::GetMouseCoordinates() const {
std::pair<int, int> RWindow::GetCursorPosition() const {
return currentMouse.Position;
}
bool RWindow::GetFlag(WindowFlag flag) const {
return flags[(int) flag];
}
bool RWindow::IsAlive() const {
return (!closing) && open;
}
@@ -43,24 +25,21 @@ void RWindow::SetFullscreen(bool fs) {
}
#pragma region Event Processors Implementation
void RWindow::processFocusIn()
{
void RWindow::processFocusIn() {
RWindowEvent event {};
OnFocusGain(event);
OnFocusGainEvent(event);
LogEvent(event);
}
void RWindow::processFocusOut()
{
void RWindow::processFocusOut() {
RWindowEvent event {};
OnFocusLost(event);
OnFocusLostEvent(event);
LogEvent(event);
}
void RWindow::processMousePress(const MouseButton& btn)
{
void RWindow::processMousePress(const MouseButton& btn) {
currentMouse.Set(btn, true);
auto event = MouseButtonDownEvent(btn);
OnMouseButtonDown(event);
@@ -70,8 +49,7 @@ void RWindow::processMousePress(const MouseButton& btn)
LogEvent(event);
}
void RWindow::processMouseMove(IPair last_pos, IPair new_pos)
{
void RWindow::processMouseMove(const std::pair<int, int>& last_pos, const std::pair<int, int>& new_pos) {
currentMouse.Position = new_pos;
auto event = MouseMoveEvent(new_pos);
OnMouseMove(event);
@@ -80,8 +58,7 @@ void RWindow::processMouseMove(IPair last_pos, IPair new_pos)
LogEvent(event);
}
void RWindow::processMouseRelease(const MouseButton& btn)
{
void RWindow::processMouseRelease(const MouseButton& btn) {
currentMouse.Set(btn, false);
auto event = MouseButtonUpEvent(btn);
OnMouseButtonUp(event);
@@ -114,16 +91,14 @@ void RWindow::processKeyPress(Key key) {
LogEvent(event);
}
void RWindow::processOnClose()
{
void RWindow::processOnClose() {
auto event = RWindowEvent();
OnClosing();
OnClosingEvent();
LogEvent(event);
}
void RWindow::processOnOpen()
{
void RWindow::processOnOpen() {
auto event = RWindowEvent();
OnOpen();
OnOpenEvent();
@@ -132,40 +107,31 @@ void RWindow::processOnOpen()
#pragma endregion
std::string RWindow::GetTitle() const {
return this->title;
}
std::string RWindow::GetTitle() const { return this->title; }
/*
IPair RWindow::GetSize() const
{
return {this->width, this->height};
}
*/
int RWindow::GetWidth() const { return this->width; }
int RWindow::GetWidth() const
{
return this->width;
}
int RWindow::GetHeight() const { return this->height; }
int RWindow::GetHeight() const
{
return this->height;
}
bool RWindow::IsResizable() const { return resizable; }
void RWindow::SetSizeWithoutEvent(const IPair& size) {
width = size.x;
height = size.y;
}
bool RWindow::IsFullscreen() const { return fullscreen_mode; }
void RWindow::SetLastKnownWindowSize(const IPair& size) {
lastKnownWindowSize = size;
}
bool RWindow::IsFocused() const { return focused; }
void RWindow::SetSize(const IPair& size) {
this->width = size.x;
this->height = size.y;
this->SetSize(size.x, size.y);
bool RWindow::IsVsyncEnabled() const { return vsync; }
float RWindow::GetDeltaTime() const { return delta_time; }
float RWindow::GetRefreshRate() const { return refresh_rate; }
bool RWindow::SetCursorPosition(const int x, const int y) { return SetCursorPosition({x, y}); }
unsigned long long RWindow::GetRefreshCount() const { return refresh_count; }
void RWindow::SetSizeWithoutEvent(const std::pair<int, int>& size) {
width = size.first;
height = size.second;
}
bool RWindow::IsKeyDown(Key key) const {
@@ -181,15 +147,14 @@ bool RWindow::IsMouseButtonDown(const MouseButton& button) const {
}
void RWindow::ManagedRefresh()
{
auto begin = GetTimestamp();
Refresh();
auto end = GetTimestamp();
void RWindow::ManagedRefresh() {
auto begin = GetTimestamp();
Refresh();
auto end = GetTimestamp();
float dt = ComputeElapsedFrameTimeSeconds(begin, end);
float dt = ComputeElapsedFrameTimeSeconds(begin, end);
UpdateFrameTiming(dt);
UpdateFrameTiming(dt);
}
void RWindow::Refresh() {
@@ -197,15 +162,18 @@ void RWindow::Refresh() {
OnRefresh(delta_time);
// Only call once and cache the result.
currentMouse.Position = GetAccurateMouseCoordinates();
currentMouse.Position = GetAccurateCursorCoordinates();
/// TODO: Implement optional minimum epsilon to trigger a Mouse Update.
if (currentMouse.Position != previousMouse.Position) {
processMouseMove(previousMouse.Position, currentMouse.Position);
previousMouse.Position = currentMouse.Position;
}
}
bool RWindow::GetCursorFocused() {
return cursor_focused;
}
float RWindow::ComputeElapsedFrameTimeSeconds(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end) {
auto frame_time = end - start;
unsigned long int frame_time_us = std::chrono::duration_cast<std::chrono::microseconds>(frame_time).count();
@@ -213,7 +181,7 @@ float RWindow::ComputeElapsedFrameTimeSeconds(std::chrono::steady_clock::time_po
return frame_time_s;
}
std::chrono::steady_clock::time_point RWindow::GetTimestamp() {
std::chrono::steady_clock::time_point RWindow::GetTimestamp() {
return std::chrono::steady_clock::now();
}
@@ -230,8 +198,7 @@ void RWindow::UpdateFrameTiming(float frame_time) {
}
void RWindow::processMouseWheel(int scrolls)
{
void RWindow::processMouseWheel(int scrolls) {
currentMouse.Wheel += scrolls;
auto ev = MouseWheelEvent(scrolls);
OnMouseWheel(ev);
@@ -240,74 +207,46 @@ void RWindow::processMouseWheel(int scrolls)
previousMouse.Wheel = currentMouse.Wheel;
}
bool RWindow::IsResizable() const {
return resizable;
}
bool RWindow::IsFullscreen() const {
return fullscreen_mode;
}
bool RWindow::IsFocused() const {
return focused;
}
bool RWindow::IsVsyncEnabled() const {
return vsync;
}
float RWindow::GetDeltaTime() const { return delta_time; }
float RWindow::GetRefreshRate() const { return refresh_rate; }
float RWindow::GetRefreshCounter() const { return refresh_count; }
void RWindow::Close() {
void RWindow::Close() {
closing = true;
processOnClose();
}
}
void RWindow::ForceClose() {
void RWindow::ForceClose() {
Close();
DestroyOSWindowHandle();
}
}
void RWindow::ForceCloseAndTerminateProgram() {
ForceClose();
exit(0);
}
bool MouseState::IsDown(const MouseButton& btn) const {
if (btn == MouseButtons::Left) return Buttons.LMB;
if (btn == MouseButtons::Right) return Buttons.RMB;
if (btn == MouseButtons::Middle) return Buttons.MMB;
if (btn == MouseButtons::Mouse4) return Buttons.SideButton1;
if (btn == MouseButtons::Mouse5) return Buttons.SideButton2;
//if (btn == MouseButtons::MWheelUp) return Buttons.MWheelUp;
//if (btn == MouseButtons::MWheelDown) return Buttons.MWheelDown;
bool MouseState::IsDown(const MouseButton &btn) const {
if (btn == MouseButtons::Left) return Buttons.LMB;
if (btn == MouseButtons::Right) return Buttons.RMB;
if (btn == MouseButtons::Middle) return Buttons.MMB;
if (btn == MouseButtons::Mouse4) return Buttons.SideButton1;
if (btn == MouseButtons::Mouse5) return Buttons.SideButton2;
//if (btn == MouseButtons::MWheelUp) return Buttons.MWheelUp;
//if (btn == MouseButtons::MWheelDown) return Buttons.MWheelDown;
return false; // Unknown button?
}
return false; // Unknown button?
}
void MouseState::Set(const MouseButton& btn, bool state) {
if (btn == MouseButtons::Left) Buttons.LMB = state;
if (btn == MouseButtons::Right) Buttons.RMB = state;
if (btn == MouseButtons::Middle) Buttons.MMB = state;
if (btn == MouseButtons::Mouse4) Buttons.SideButton1 = state;
if (btn == MouseButtons::Mouse5) Buttons.SideButton2 = state;
void MouseState::Set(const MouseButton& btn, bool state) {
if (btn == MouseButtons::Left) Buttons.LMB = state;
if (btn == MouseButtons::Right) Buttons.RMB = state;
if (btn == MouseButtons::Middle) Buttons.MMB = state;
if (btn == MouseButtons::Mouse4) Buttons.SideButton1 = state;
if (btn == MouseButtons::Mouse5) Buttons.SideButton2 = state;
//if (btn == MouseButtons::MWheelUp) Buttons.MWheelUp = state;
//if (btn == MouseButtons::MWheelDown) Buttons.MWheelDown = state;
}
}
bool &MouseState::operator [](const MouseButton &btn) {
if (btn == MouseButtons::Left) return Buttons.LMB;
if (btn == MouseButtons::Right) return Buttons.RMB;
if (btn == MouseButtons::Middle) return Buttons.MMB;
if (btn == MouseButtons::Mouse4) return Buttons.SideButton1;
if (btn == MouseButtons::Mouse5) return Buttons.SideButton2;
//if (btn == MouseButtons::MWheelUp) return Buttons.MWheelUp;
//if (btn == MouseButtons::MWheelDown) return Buttons.MWheelDown;
bool &MouseState::operator [](const MouseButton& btn) {
if (btn == MouseButtons::Left) return Buttons.LMB;
if (btn == MouseButtons::Right) return Buttons.RMB;
if (btn == MouseButtons::Middle) return Buttons.MMB;
if (btn == MouseButtons::Mouse4) return Buttons.SideButton1;
if (btn == MouseButtons::Mouse5) return Buttons.SideButton2;
//if (btn == MouseButtons::MWheelUp) return Buttons.MWheelUp;
//if (btn == MouseButtons::MWheelDown) return Buttons.MWheelDown;
throw std::invalid_argument("Attempted to handle unmapped mouse button.");
}
throw std::invalid_argument("Attempted to handle unmapped mouse button.");
}

View File

@@ -1,128 +0,0 @@
#include <ReWindow/types/Window.h>
#include <ReWindow/data/WindowsEventLoop.h>
#include <ReWindow/Logger.h>
#include <GL/gl.h>
class RWindow::Platform {
public:
HINSTANCE hInstance;
HWND hwnd;
HDC hdc;
};
using namespace ReWindow;
HGLRC glContext;
HMODULE gl_lib = nullptr;
bool constructor_success = true;
namespace OpenGL {
typedef const GLubyte* (APIENTRY *GLGETSTRINGPROC)(GLenum name);
GLGETSTRINGPROC glGetString = nullptr;
typedef BOOL (WINAPI *WGLMAKECURRENTPROC)(HDC hdc, HGLRC hglrc);
WGLMAKECURRENTPROC wglMakeCurrent = nullptr;
typedef FARPROC (WINAPI *WGLGETPROCADDRPROC)(LPCSTR lpszProc);
WGLGETPROCADDRPROC wglGetProcAddress = nullptr;
typedef HGLRC (WINAPI *WGLCREATECONTEXTPROC)(HDC hdc);
WGLCREATECONTEXTPROC wglCreateContext = nullptr;
}
bool OpenGLWindow::Open() {
if (!constructor_success)
return false;
platform->hInstance = GetModuleHandle(nullptr);
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = platform->hInstance;
wc.lpszClassName = "RWindowClass";
RegisterClass(&wc);
platform->hwnd = CreateWindowEx(
0,
"RWindowClass",
title.c_str(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, width, height,
nullptr,
nullptr,
platform->hInstance,
nullptr
);
SetWindowLongPtr(platform->hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
24,
8,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
platform->hdc = GetDC(platform->hwnd);
int pixelFormat = ChoosePixelFormat(platform->hdc, &pfd);
SetPixelFormat(platform->hdc, pixelFormat, &pfd);
glContext = OpenGL::wglCreateContext(platform->hdc);
OpenGL::wglMakeCurrent(platform->hdc, glContext);
ShowWindow(platform->hwnd, SW_SHOW);
open = true;
return true;
}
std::string OpenGLWindow::GetGraphicsDriverVendor() {
return std::string(reinterpret_cast<const char*>(OpenGL::glGetString(GL_VENDOR)));
}
void OpenGLWindow::SwapBuffers() {
::SwapBuffers(platform->hdc);
}
void OpenGLWindow::SetVsyncEnabled(bool b) {
typedef BOOL(WINAPI* PFNWGLSWAPINTERVALEXTPROC)(int interval);
auto wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) OpenGL::wglGetProcAddress("wglSwapIntervalEXT");
if (wglSwapIntervalEXT)
wglSwapIntervalEXT(b ? 1 : 0);
}
bool OpenGLWindow::SoftwareRendered() {
std::string renderer(reinterpret_cast<const char*>(OpenGL::glGetString(GL_RENDERER)));
if (renderer.find("llvmpipe"))
return true;
if (renderer.find("softpipe"))
return true;
if (renderer.find("GDI Generic"))
return true;
if (GetGraphicsDriverVendor().find("Mesa"))
return true;
return false;
}
OpenGLWindow::OpenGLWindow(const std::string& title, int width, int height, uint8_t gl_major, uint8_t gl_minor)
: gl_major(gl_major), gl_minor(gl_minor), RWindow(title, width, height) {
gl_lib = LoadLibrary("opengl32.dll");
if (!gl_lib)
Logger::Error("opengl32.dll couldn't be found. If you have it, you can try putting it in the same directory as the executable."),
constructor_success = false;
OpenGL::glGetString = (OpenGL::GLGETSTRINGPROC) GetProcAddress(gl_lib, "glGetString");
OpenGL::wglMakeCurrent = (OpenGL::WGLMAKECURRENTPROC) GetProcAddress(gl_lib, "wglMakeCurrent");
OpenGL::wglGetProcAddress = (OpenGL::WGLGETPROCADDRPROC) GetProcAddress(gl_lib, "wglGetProcAddress");
OpenGL::wglCreateContext = (OpenGL::WGLCREATECONTEXTPROC) GetProcAddress(gl_lib, "wglCreateContext");
}

View File

@@ -1,23 +1,267 @@
#include <Windows.h>
#include <gl/GL.h>
#include <rewindow/types/window.h>
#include <ReWindow/types/Window.h>
#include <ReWindow/Logger.h>
class ReWindow::RWindow::Platform {
public:
HINSTANCE hInstance;
HWND hwnd;
HDC hdc;
std::pair<int, int> window_size_before_fullscreen;
std::pair<int, int> window_position_before_fullscreen;
};
using namespace ReWindow;
// TODO get rid of this.
bool local_focused = true;
bool local_toggling_cursor_focused = false;
void RWindow::SetSize(int newWidth, int newHeight) {
if (!resizable)
return;
this->width = newWidth;
this->height = newHeight;
DWORD style = GetWindowLong(platform->hwnd, GWL_STYLE);
DWORD exStyle = GetWindowLong(platform->hwnd, GWL_EXSTYLE);
RECT rect = { 0, 0, newWidth, newHeight };
AdjustWindowRectEx(&rect, style, FALSE, exStyle);
int totalWidth = rect.right - rect.left;
int totalHeight = rect.bottom - rect.top;
SetWindowPos(platform->hwnd, nullptr, 0, 0, totalWidth, totalHeight,
SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER | SWP_FRAMECHANGED);
}
void RWindow::SetCursorFocused(bool state) {
local_toggling_cursor_focused = state;
if (state)
cursor_focused = true;
else if (!state && cursor_focused) {
ClipCursor(nullptr);
cursor_focused = false;
local_toggling_cursor_focused = false;
}
}
bool RWindow::SetCursorPosition(const std::pair<int, int>& position) {
if (!IsFocused())
return false;
if (!IsVisible())
return false;
if (position.first < 0 || position.first > GetWidth())
return false;
if (position.second < 0 || position.second > GetHeight())
return false;
POINT screen_pos = { position.first, position.second };
if (!ClientToScreen(platform->hwnd, &screen_pos))
return false;
if (!SetCursorPos(screen_pos.x, screen_pos.y))
return false;
return true;
}
std::pair<int, int> RWindow::SetCursorCenter() {
auto current_cursor_pos = GetAccurateCursorCoordinates();
RECT client_rect;
GetClientRect(platform->hwnd, &client_rect);
POINT center((client_rect.right - client_rect.left) / 2, (client_rect.bottom - client_rect.top) / 2 );
ClientToScreen(platform->hwnd, &center);
SetCursorPos(center.x, center.y);
return current_cursor_pos;
}
void RWindow::PollEvents() {
MSG msg;
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE))
TranslateMessage(&msg),
DispatchMessage(&msg);
focused = local_focused;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
auto* window = reinterpret_cast<RWindow*>( GetWindowLongPtr(hwnd, GWLP_USERDATA) );
switch (uMsg) {
case WM_CLOSE: {
window->processOnClose();
DestroyWindow(hwnd);
}
case WM_DESTROY: {
exit(0);
}
case WM_SIZE: {
window->SetSizeWithoutEvent({ LOWORD(lParam), HIWORD(lParam) });
auto eventData = WindowResizeRequestEvent();
eventData.Size = { window->GetWidth(), window->GetHeight() };
// TODO: Implement eWindow->processOnResize()
window->OnResizeRequest(eventData);
window->OnResizeRequestEvent(eventData);
break;
}
case WM_SETFOCUS: {
window->processFocusIn();
local_focused = true;
if (window->GetCursorFocused())
local_toggling_cursor_focused = true;
// Cancels window flashing.
// TODO check if we're flashing before this.
static FLASHWINFO flash_inter {sizeof(FLASHWINFO), hwnd, FLASHW_STOP, 0, 0};
FlashWindowEx(&flash_inter);
break;
}
case WM_KILLFOCUS: {
window->processFocusOut();
if (window->GetCursorFocused()) {
ClipCursor(nullptr);
local_toggling_cursor_focused = true;
}
local_focused = false;
}
case WM_SETCURSOR: {
if (LOWORD(lParam) == HTCLIENT && window->GetCursorVisible() == false)
SetCursor(nullptr);
break;
}
case WM_KEYDOWN: {
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
if (window->IsKeyRepeat())
window->processKeyPress(key);
else if ((lParam & 1 << 30) == 0)
window->processKeyPress(key);
break;
}
case WM_KEYUP: {
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
window->processKeyRelease(key);
break;
}
// Mouse Buttons.
case WM_MOUSEWHEEL: {
int wheel_delta = GET_WHEEL_DELTA_WPARAM(wParam);
// Clamp to normalized range [+1 or -1].
// TODO: Test this and make sure sign is the same on both platforms for each direction.
wheel_delta = (wheel_delta > 0) ? 1 : -1;
// TODO: Determine sign of wheel_delta for each direction, (and on linux too), and document this.
window->processMouseWheel(wheel_delta);
break;
}
case WM_LBUTTONDOWN: {
window->processMousePress(MouseButtons::Left);
break;
}
case WM_LBUTTONUP: {
window->processMouseRelease(MouseButtons::Left);
break;
}
case WM_RBUTTONDOWN: {
window->processMousePress(MouseButtons::Right);
break;
}
case WM_RBUTTONUP: {
window->processMouseRelease(MouseButtons::Right);
break;
}
case WM_MBUTTONDOWN: {
window->processMousePress(MouseButtons::Middle);
break;
}
case WM_MBUTTONUP: {
window->processMouseRelease(MouseButtons::Middle);
break;
}
case WM_XBUTTONDOWN: {
WORD button = GET_XBUTTON_WPARAM(wParam);
if (button == XBUTTON1)
window->processMousePress(MouseButtons::Mouse4);
if (button == XBUTTON2)
window->processMousePress(MouseButtons::Mouse5);
break;
}
case WM_XBUTTONUP: {
WORD button = GET_XBUTTON_WPARAM(wParam);
if (button == XBUTTON1)
window->processMouseRelease(MouseButtons::Mouse4);
if (button == XBUTTON2)
window->processMouseRelease(MouseButtons::Mouse5);
break;
}
//This is the same as "Motion Notify" in the X Window System.
case WM_MOUSEMOVE: {
if (local_toggling_cursor_focused) {
RECT rect;
if (GetClientRect(hwnd, &rect)) {
POINT top_left = { rect.left, rect.top };
POINT bottom_right = { rect.right, rect.bottom };
MapWindowPoints(hwnd, nullptr, &top_left, 1);
MapWindowPoints(hwnd, nullptr, &bottom_right, 1);
RECT clip_rect = { top_left.x, top_left.y, bottom_right.x, bottom_right.y };
if (ClipCursor(&clip_rect))
local_toggling_cursor_focused = false;
}
}
}
break;
}
return DefWindowProc(hwnd, uMsg, wParam, lParam);
}
bool fullscreenmode = false;
bool open = false;
void RWindow::Raise() { SetWindowPos(platform->hwnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); }
void RWindow::Lower() { SetWindowPos(platform->hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); }
//TODO somehow check if our window is entirely obscured by other windows.
bool RWindow::IsVisible() const {
if (!IsWindow(platform->hwnd))
return false;
if (IsIconic(platform->hwnd))
return false;
return true;
}
void RWindow::Flash() {
if (!GetFlag(WindowFlag::IN_FOCUS)) {
if (!focused) {
FLASHWINFO fi;
fi.cbSize = sizeof(FLASHWINFO);
fi.hwnd = platform->hwnd;
@@ -32,40 +276,21 @@ void RWindow::DestroyOSWindowHandle() {
DestroyWindow(platform->hwnd);
}
void RWindow::SetFlag(WindowFlag flag, bool state) {
flags[(int) flag] = state;
if (flag == WindowFlag::RESIZABLE && !state) {
RECT rect;
GetWindowRect(platform->hwnd, &rect);
LONG style = GetWindowLong(platform->hwnd, GWL_STYLE);
style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
SetWindowLong(platform->hwnd, GWL_STYLE, style);
SetWindowPos(platform->hwnd, nullptr, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOOWNERZORDER);
}
void RWindow::DisableResizing() {
RECT rect;
GetWindowRect(platform->hwnd, &rect);
LONG style = GetWindowLong(platform->hwnd, GWL_STYLE);
style &= ~(WS_THICKFRAME | WS_MAXIMIZEBOX);
SetWindowLong(platform->hwnd, GWL_STYLE, style);
SetWindowPos(platform->hwnd, nullptr, rect.left, rect.top, rect.right - rect.left,
rect.bottom - rect.top, SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOOWNERZORDER);
this->resizable = false;
}
void RWindow::SetResizable(bool resizable) {
SetFlag(WindowFlag::RESIZABLE, resizable);;
}
void RWindow::PollEvents() {
MSG msg;
while (PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE)) {
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
void RWindow::SetSize(int newWidth, int newHeight) {
if (!resizable) return;
this->width = newWidth;
this->height = newHeight;
SetWindowPos(platform->hwnd, nullptr, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER);
}
IPair RWindow::GetAccurateMouseCoordinates() const {
std::pair<int, int> RWindow::GetAccurateCursorCoordinates() const {
POINT point;
GetCursorPos(&point);
ScreenToClient(platform->hwnd, &point);
@@ -80,31 +305,69 @@ bool RWindow::GetCursorVisible() {
return cursor_visible;
}
void RWindow::SetKeyRepeatEnabled(bool state) {
key_repeat = state;
}
IPair RWindow::GetSize() const {
std::pair<int, int> RWindow::GetSize() const {
RECT rect;
GetClientRect(platform->hwnd, &rect);
return { (rect.right - rect.left), (rect.bottom - rect.top) };
}
void RWindow::SetPos(int x, int y) {
std::pair<int, int> RWindow::GetPosition() const {
RECT rect;
if (GetWindowRect(platform->hwnd, &rect))
return { rect.left, rect.top };
return { -1, -1 };
}
void RWindow::SetPosition(int x, int y) {
SetWindowPos(platform->hwnd, nullptr, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER);
}
void RWindow::SetPos(const IPair& pos) {
SetPos(pos.x, pos.y);
void RWindow::SetPosition(const std::pair<int, int>& pos) {
SetPosition(pos.first, pos.second);
}
void RWindow::Fullscreen() {
// Implement fullscreen
platform->window_position_before_fullscreen = GetPosition();
platform->window_size_before_fullscreen = GetSize();
platform->window_position_before_fullscreen = this->GetPosition();
SetWindowLong(platform->hwnd, GWL_STYLE, GetWindowLong(platform->hwnd, GWL_STYLE) & ~WS_OVERLAPPEDWINDOW);
SetWindowPos(platform->hwnd, HWND_TOP, 0, 0, GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN), SWP_FRAMECHANGED | SWP_NOOWNERZORDER);
fullscreen_mode = true;
}
void RWindow::RestoreFromFullscreen() {
// Implement restore from fullscreen
SetWindowLong(platform->hwnd, GWL_STYLE, GetWindowLong(platform->hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW);
SetWindowPos(platform->hwnd, nullptr, 0, 0, width, height, SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOOWNERZORDER);
RECT rect = {0, 0, platform->window_size_before_fullscreen.first, platform->window_size_before_fullscreen.second };
AdjustWindowRectEx(&rect, GetWindowLong(platform->hwnd, GWL_STYLE), FALSE, GetWindowLong(platform->hwnd, GWL_EXSTYLE));
int window_width = rect.right - rect.left;
int window_height = rect.bottom - rect.top;
SetWindowPos(
platform->hwnd,
nullptr,
platform->window_position_before_fullscreen.first,
platform->window_position_before_fullscreen.second,
window_width,
window_height,
SWP_FRAMECHANGED | SWP_NOZORDER | SWP_NOOWNERZORDER
);
DisableResizing();
this->width = platform->window_position_before_fullscreen.first;
this->height = platform->window_position_before_fullscreen.second;
fullscreen_mode = false;
}
void RWindow::SetCursorStyle(CursorStyle style) const {}
@@ -117,11 +380,132 @@ RWindow::RWindow() {
RWindow::RWindow(const std::string& wTitle, int wWidth, int wHeight,
bool wFullscreen, bool wResizable, bool wVsync) :
title(wTitle), width(wWidth), height(wHeight), fullscreen_mode(wFullscreen), resizable(wResizable),
vsync(wVsync), flags{false,wFullscreen,wResizable,wVsync} {
vsync(wVsync) {
extant = this;
platform = new Platform();
}
void RWindow::UniqueFunctionNameForMessageBoxBecauseMicrosoftUsesMacros(const std::string& title, const std::string& message_box_text) {
void RWindow::DialogOK(const std::string& title, const std::string& message_box_text) {
MessageBox(nullptr, message_box_text.c_str(), title.c_str(), MB_OK);
}
}
HGLRC glContext;
HMODULE gl_lib = nullptr;
bool constructor_success = true;
namespace OpenGL {
typedef const GLubyte* (APIENTRY *GLGETSTRINGPROC)(GLenum name);
GLGETSTRINGPROC glGetString = nullptr;
typedef BOOL (WINAPI *WGLMAKECURRENTPROC)(HDC hdc, HGLRC hglrc);
WGLMAKECURRENTPROC wglMakeCurrent = nullptr;
typedef FARPROC (WINAPI *WGLGETPROCADDRPROC)(LPCSTR lpszProc);
WGLGETPROCADDRPROC wglGetProcAddress = nullptr;
typedef HGLRC (WINAPI *WGLCREATECONTEXTPROC)(HDC hdc);
WGLCREATECONTEXTPROC wglCreateContext = nullptr;
}
bool OpenGLWindow::Open() {
if (!constructor_success)
return false;
platform->hInstance = GetModuleHandle(nullptr);
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.hInstance = platform->hInstance;
wc.lpszClassName = "RWindowClass";
RegisterClass(&wc);
RECT rect = { 0, 0, width, height };
AdjustWindowRectEx(&rect, WS_OVERLAPPEDWINDOW, FALSE, 0);
int win_width = rect.right - rect.left;
int win_height = rect.bottom - rect.top;
platform->hwnd = CreateWindowEx(
0,
"RWindowClass",
title.c_str(),
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT, CW_USEDEFAULT, win_width, win_height,
nullptr,
nullptr,
platform->hInstance,
nullptr
);
SetWindowLongPtr(platform->hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR>(this));
PIXELFORMATDESCRIPTOR pfd = {
sizeof(PIXELFORMATDESCRIPTOR),
1,
PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER,
PFD_TYPE_RGBA,
24,
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
24,
8,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
platform->hdc = GetDC(platform->hwnd);
int pixelFormat = ChoosePixelFormat(platform->hdc, &pfd);
SetPixelFormat(platform->hdc, pixelFormat, &pfd);
glContext = OpenGL::wglCreateContext(platform->hdc);
OpenGL::wglMakeCurrent(platform->hdc, glContext);
ShowWindow(platform->hwnd, SW_SHOW);
open = true;
return true;
}
std::string OpenGLWindow::GetGraphicsDriverVendor() {
return std::string(reinterpret_cast<const char*>(OpenGL::glGetString(GL_VENDOR)));
}
void OpenGLWindow::SwapBuffers() {
::SwapBuffers(platform->hdc);
}
void OpenGLWindow::SetVsyncEnabled(bool b) {
typedef BOOL(WINAPI* PFNWGLSWAPINTERVALEXTPROC)(int interval);
auto wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) OpenGL::wglGetProcAddress("wglSwapIntervalEXT");
if (wglSwapIntervalEXT)
wglSwapIntervalEXT(b ? 1 : 0);
}
bool OpenGLWindow::SoftwareRendered() {
std::string renderer(reinterpret_cast<const char*>(OpenGL::glGetString(GL_RENDERER)));
if (renderer.find("llvmpipe"))
return true;
if (renderer.find("softpipe"))
return true;
if (renderer.find("GDI Generic"))
return true;
if (GetGraphicsDriverVendor().find("Mesa"))
return true;
return false;
}
OpenGLWindow::OpenGLWindow(const std::string& title, int width, int height, uint8_t gl_major, uint8_t gl_minor)
: gl_major(gl_major), gl_minor(gl_minor), RWindow(title, width, height) {
gl_lib = LoadLibrary("opengl32.dll");
if (!gl_lib)
Logger::Error("opengl32.dll couldn't be found. If you have it, you can try putting it in the same directory as the executable."),
constructor_success = false;
OpenGL::glGetString = (OpenGL::GLGETSTRINGPROC) GetProcAddress(gl_lib, "glGetString");
OpenGL::wglMakeCurrent = (OpenGL::WGLMAKECURRENTPROC) GetProcAddress(gl_lib, "wglMakeCurrent");
OpenGL::wglGetProcAddress = (OpenGL::WGLGETPROCADDRPROC) GetProcAddress(gl_lib, "wglGetProcAddress");
OpenGL::wglCreateContext = (OpenGL::WGLCREATECONTEXTPROC) GetProcAddress(gl_lib, "wglCreateContext");
}

View File

@@ -1,125 +0,0 @@
#include <ReWindow/types/Pair.h>
#include <stdexcept>
using namespace ReWindow;
IPair& IPair::operator +=(const IPair& rhs) {
x += rhs.x;
y += rhs.y;
return *this;
}
IPair& IPair::operator -=(const IPair& rhs) {
x -= rhs.x;
y -= rhs.y;
return *this;
}
IPair& IPair::operator *=(const IPair& rhs) {
x *= rhs.x;
y *= rhs.y;
return *this;
}
IPair& IPair::operator /=(const IPair& rhs) {
if (rhs.x == 0 || rhs.y == 0)
throw std::invalid_argument("Division by zero in IPair::operator /=");
x /= rhs.x;
y /= rhs.y;
return *this;
}
IPair::IPair(const IPair& rhs) {
x = rhs.x;
y = rhs.y;
}
IPair IPair::operator +(const IPair& rhs) const {
return { x + rhs.x, y + rhs.y };
}
IPair IPair::operator -(const IPair& rhs) const {
return { x - rhs.x, y - rhs.y };
}
IPair IPair::operator *(const IPair& rhs) const {
return { x * rhs.x, y * rhs.y };
}
IPair IPair::operator /(const IPair& rhs) const {
if (rhs.x == 0 || rhs.y == 0)
throw std::invalid_argument("Division by zero in IPair::operator /");
return { x / rhs.x, y * rhs.y};
}
bool IPair::operator ==(const IPair& rhs) const {
return x == rhs.x && y == rhs.y;
}
bool IPair::operator !=(const IPair& rhs) const {
return !(*this == rhs);
}
FPair FPair::operator +(const FPair& rhs) const {
return { x + rhs.x, y + rhs.y };
}
FPair FPair::operator -(const FPair& rhs) const {
return {x - rhs.x, y - rhs.y };
}
FPair FPair::operator *(const FPair& rhs) const {
return { x * rhs.x, y * rhs.y };
}
FPair FPair::operator /(const FPair& rhs) const {
if (rhs.x == 0 || rhs.y == 0)
throw std::invalid_argument("Division by zero in FPair::operator /");
return { x / rhs.x, y / rhs.y};
}
FPair& FPair::operator +=(const FPair& rhs) {
x += rhs.x;
y += rhs.y;
return *this;
}
FPair& FPair::operator -=(const FPair& rhs) {
x -= rhs.x;
y -= rhs.y;
return *this;
}
FPair& FPair::operator *=(const FPair& rhs) {
x *= rhs.x;
y *= rhs.y;
return *this;
}
FPair& FPair::operator /=(const FPair& rhs) {
if (rhs.x == 0 || rhs.y == 0)
throw std::invalid_argument("Division by zero in FPair::operator /=");
x /= rhs.x;
y /= rhs.y;
return *this;
}
bool FPair::operator ==(const FPair& rhs) const {
return x == rhs.x && y == rhs.y;
}
bool FPair::operator !=(const FPair& rhs) const {
return !(*this == rhs);
}
FPair::FPair(const FPair& rhs) {
x = rhs.x;
y = rhs.y;
}
FPair::FPair(const IPair& rhs) {
x = rhs.x;
y = rhs.y;
}

View File

@@ -1,26 +0,0 @@
#include <ReWindow/types/GamepadButton.h>
using namespace ReWindow;
bool GamepadButton::operator ==(const GamepadButton &rhs) const {
return this->GetMnemonicButtonCode() == rhs.GetMnemonicButtonCode();
}
std::string GamepadButton::GetMnemonicButtonCode() const {
return mnemonic_btn_code;
}
void GamepadThumbstick::SetDeadzone(float minimum) {
dead_zone = minimum;
}
FPair GamepadThumbstick::GetPosition() const {
return position;
}
void GamepadTrigger::SetDeadzone(float minimum) {
dead_zone = minimum;
}
float GamepadTrigger::GetActuation() const {
return position;
}