Compare commits

...

15 Commits

Author SHA1 Message Date
74fc93c4e1 Merge pull request 'Make WindowProc a static member, so we can hide processEvent...() methods.' (#29) from protect-events into main
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m21s
Reviewed-on: #29
2025-07-13 19:12:16 -04:00
f75825eb28 Make WindowProc a static member, so we can hide processEvent...() methods.
Some checks failed
Run ReCI Build Test / Explore-Gitea-Actions (push) Failing after 1m41s
2025-07-13 18:11:07 -05:00
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
16 changed files with 606 additions and 705 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

@@ -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,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,13 @@
#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>
#include <Windows.h>
namespace ReWindow {
struct KeyboardState { std::map<Key, bool> PressedKeys; };
struct GamepadState { std::map<GamepadButton, bool> PressedButtons; };
class MouseState;
class RWindow;
@@ -37,7 +35,7 @@ public:
}
Buttons;
IPair Position;
std::pair<int, int> Position;
int Wheel = 0;
public:
[[nodiscard]] bool IsDown(const MouseButton& btn) const;
@@ -48,35 +46,36 @@ public:
/// RWindow is a class implementation of a platform-independent window abstraction.
/// This library also provides abstractions for user-input devices, and their interaction with the window.
class ReWindow::RWindow {
protected:
class Platform;
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};
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;
@@ -84,12 +83,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.
@@ -136,30 +135,39 @@ 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; }
@@ -168,33 +176,42 @@ public:
[[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,
@@ -203,15 +220,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);
@@ -219,12 +235,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.
@@ -244,27 +260,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.
@@ -274,21 +288,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();
@@ -297,10 +334,14 @@ public:
/// Updates internals to account for the latest calculated frame time.
void UpdateFrameTiming(float frame_time);
public:
#ifdef WIN32
static LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
#endif
protected:
/// 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.
@@ -309,17 +350,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;
@@ -336,7 +383,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

@@ -3,8 +3,8 @@
#include <ReWindow/Logger.h>
using namespace ReWindow;
std::ostream& operator<<(std::ostream& os, const IPair& v) {
return os << "{" << v.x << ", " << v.y << "}";
std::ostream& operator<<(std::ostream& os, const std::pair<int, int>& v) {
return os << "{" << v.first << ", " << v.second << "}";
}
class MyWindow : public OpenGLWindow {
@@ -13,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;
@@ -33,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();
}
};
@@ -66,23 +52,27 @@ 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); };
window->OnMouseButtonDownEvent += [&] (MouseButtonDownEvent e) { jlog::Debug(e.Button.Mnemonic + std::to_string(e.Button.ButtonIndex)); };
window->OnMouseWheelEvent += [&, window] (MouseWheelEvent e) { std::cout << window->GetMouseWheelPersistent() << std::endl; };
while (!window->IsClosing())
window->ManagedRefresh();
while (!window->IsClosing()) {
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

@@ -77,8 +77,7 @@ void OpenGLWindow::SwapBuffers() {
}
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);
}
@@ -175,7 +174,6 @@ bool OpenGLWindow::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();
@@ -228,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

@@ -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

@@ -22,12 +22,44 @@ public:
Cursor invisible_cursor = 0;
XWMHints* wm_hints = nullptr;
bool window_visible = true;
IPair position = {0, 0};
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;
@@ -40,8 +72,24 @@ void RWindow::Flash() {
}
RWindow::RWindow() {
platform = new Platform();
extant = this;
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)
@@ -52,63 +100,65 @@ 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);
@@ -124,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);
@@ -132,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) {
@@ -152,17 +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);
this->resizable = false;
}
void RWindow::PollEvents() {
@@ -179,7 +227,18 @@ void RWindow::PollEvents() {
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;
@@ -191,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);
@@ -255,9 +326,26 @@ void RWindow::PollEvents() {
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 (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) {
@@ -270,13 +358,12 @@ void RWindow::PollEvents() {
auto eventData = WindowResizeRequestEvent();
eventData.Size = {platform->xev.xconfigurerequest.width, platform->xev.xconfigurerequest.height};
lastKnownWindowSize = eventData.Size;
OnResizeRequest(eventData);
OnResizeRequestEvent(eventData);
}
//Window Moved.
if (platform->position.x != platform->xev.xconfigurerequest.x || platform->position.y != 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 };
}
@@ -295,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;
@@ -304,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;
@@ -317,7 +404,7 @@ 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 {};
@@ -327,66 +414,108 @@ bool RWindow::IsVisible() const {
return platform->window_visible;
}
IPair RWindow::GetSize() const {
return { this->width, this->height};
}
//IPair RWindow::getLastKnownResize() const
//{
// return lastKnownWindowSize;
//}
// TODO: implement integer IPair/3 types
IPair RWindow::GetPos() const {
// 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);
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));
}
@@ -401,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

@@ -3,14 +3,13 @@
#include <ReWindow/Logger.h>
using namespace ReWindow;
RWindow::~RWindow() {
if (open)
DestroyOSWindowHandle();
}
IPair RWindow::GetMouseCoordinates() const {
std::pair<int, int> RWindow::GetCursorPosition() const {
return currentMouse.Position;
}
@@ -26,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);
@@ -53,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);
@@ -63,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);
@@ -97,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();
@@ -115,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 {
@@ -164,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() {
@@ -180,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();
@@ -196,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();
}
@@ -213,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);
@@ -223,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

@@ -9,15 +9,84 @@ 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;
//bool local_fullscreen_mode = false;
// TODO get rid of this.
bool local_focused = true;
//bool local_vsync = false;
//bool local_cursor_visible = true;
//bool local_closing = false;
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))
@@ -26,13 +95,12 @@ void RWindow::PollEvents() {
focused = local_focused;
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam) {
LRESULT CALLBACK RWindow::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: {
@@ -43,7 +111,6 @@ LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
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);
@@ -54,19 +121,23 @@ LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
window->processFocusIn();
local_focused = 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);
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;
}
@@ -76,13 +147,15 @@ LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
break;
}
case WM_KEYDOWN: {
case WM_KEYDOWN: {
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
//Key repeat fix.
if (!window->previousKeyboard.PressedKeys[key])
if (window->IsKeyRepeat())
window->processKeyPress(key);
else if ((lParam & 1 << 30) == 0)
window->processKeyPress(key);
break;
}
}
case WM_KEYUP: {
auto key = GetKeyFromWindowsScancode((WindowsScancode) wParam);
@@ -90,12 +163,12 @@ LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
break;
}
//Mouse Buttons.
// 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;
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;
@@ -152,8 +225,22 @@ LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
}
//This is the same as "Motion Notify" in the X Window System.
case WM_MOUSEMOVE:
break;
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);
}
@@ -189,27 +276,21 @@ void RWindow::DestroyOSWindowHandle() {
DestroyWindow(platform->hwnd);
}
void RWindow::SetResizable(bool resizable) {
if (!resizable) {
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::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);
@@ -224,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 {}
@@ -266,7 +385,7 @@ vsync(wVsync) {
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);
}
@@ -287,7 +406,6 @@ namespace OpenGL {
typedef HGLRC (WINAPI *WGLCREATECONTEXTPROC)(HDC hdc);
WGLCREATECONTEXTPROC wglCreateContext = nullptr;
}
bool OpenGLWindow::Open() {
@@ -297,21 +415,28 @@ bool OpenGLWindow::Open() {
platform->hInstance = GetModuleHandle(nullptr);
WNDCLASS wc = { };
wc.lpfnWndProc = WindowProc;
wc.lpfnWndProc = RWindow::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
);
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),

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;
}