Compare commits
199 Commits
vA0.2.10
...
74fc93c4e1
Author | SHA1 | Date | |
---|---|---|---|
74fc93c4e1 | |||
f75825eb28 | |||
99a5978448 | |||
3862fb602f | |||
13dfa1216d | |||
bc59e49402 | |||
ac9512ef1d | |||
87f862730b | |||
bb776026ad | |||
42deab60f4 | |||
199642b1a9 | |||
c354b1deef | |||
c3c6a29dc6 | |||
f7d39b0174 | |||
f3cd2b6d82 | |||
ca459af9b1 | |||
ffdafedb94 | |||
aebc6fcfd3 | |||
0ba3618b3c | |||
778166c23f | |||
8d4db443bd | |||
0cfd66eb40 | |||
c18fca517f | |||
515d428168 | |||
a77a8a3754 | |||
3fd2a8ce14 | |||
ffeb4a99e0 | |||
d6c4c0b0f5 | |||
83d23eb3f4 | |||
c0ee42b782 | |||
1fec28b373 | |||
8f8f3304ba | |||
d657315bab | |||
47a9340eff | |||
7593c5f2c7 | |||
85d84c2828 | |||
3d5fdbc9c6 | |||
ff8fee6e90 | |||
3c4777c525 | |||
|
9707981cfd | ||
|
3b8763863a | ||
|
bf7351ac8e | ||
a627b22ecb | |||
1062b471b2 | |||
abff453347 | |||
8472bf754c | |||
e39881f2dc | |||
830dd954a2 | |||
e764dcf5b8 | |||
4b8479f1d3 | |||
f79164f89b | |||
a2ef397bdb | |||
6fd30ff25b | |||
8d8e14ef40 | |||
ee408c2fe6 | |||
f50280824d | |||
74d5f13c06 | |||
1950aee948 | |||
2d9f7e08b0 | |||
561e806b5f | |||
fa807256af | |||
b10a4d1d39 | |||
a3adbb6266 | |||
b75f44f1ee | |||
e4e860564c | |||
fb6825224f | |||
6b9bf4c2cc | |||
f25370cada | |||
f826b2a268 | |||
5dfa0fe114 | |||
216b7218e6 | |||
dc466e695f | |||
a4322c4b21 | |||
db63cc2272 | |||
1d9424a243 | |||
2e0d84d559 | |||
cc2cc6f7c1 | |||
fb6ed84b76 | |||
|
3085ad21a9 | ||
35b09cb026 | |||
6bd9ec0eb8 | |||
ae073b3a96 | |||
48091496d5 | |||
c202ca5c84 | |||
c5f94b7c49 | |||
b351577a20 | |||
fb3a77e2e3 | |||
b96dd03af1 | |||
3e99394b6f | |||
5b10e55f83 | |||
c0dc56bc8c | |||
a62c576d14 | |||
92b567e48f | |||
|
3617d610ea | ||
9500681420 | |||
bf41652336 | |||
68ae72e6be | |||
a4b68a5abc | |||
1345669c32 | |||
9d51ac0026 | |||
edb2e29246 | |||
bed600d4d4 | |||
acf66ae909 | |||
c319acfffb | |||
9b810101a4 | |||
4c616d68af | |||
4571016c4c | |||
a8c85a29dd | |||
483b5dadad | |||
9565bfeef9 | |||
e1fc2f289f | |||
7bc90af3d5 | |||
d9ee8ebedc | |||
94e61aa2ea | |||
c95ad0ee0d | |||
3b3d1ba197 | |||
1542224ffc | |||
8d92abdecf | |||
9247472a13 | |||
7e5d85c88a | |||
7dad83bbc1 | |||
c18fd72b74 | |||
663109da75 | |||
c7a2b42f1d | |||
1f81c0b843 | |||
c25983a87d | |||
1b02dcc364 | |||
254f991c49 | |||
b4c4827c9c | |||
ebf939d747 | |||
04c82df9c5 | |||
2f0cedcd04 | |||
a215d9f398 | |||
a3697cd022 | |||
68a1f52515 | |||
|
8f8eabfe47 | ||
|
a4ec53fdd9 | ||
c0ecb08a3b | |||
7d2921f598 | |||
850fe4aabb | |||
80904cf4b1 | |||
b6bb00e0de | |||
cb03a67f17 | |||
|
f8f9e78dab | ||
214c3e72fd | |||
f6b9bae45f | |||
074f0235c0 | |||
adec224701 | |||
5b8788f94f | |||
56fdc3d90b | |||
3adef96da7 | |||
2956c0b350 | |||
50a7e2cfe1 | |||
10a63d738c | |||
|
b914e9b563 | ||
|
4fb237f11a | ||
|
dfbf018807 | ||
ee5b2f18cd | |||
4336b2bfc9 | |||
4d587f9448 | |||
|
b73cc46ecb | ||
|
f5be8b2707 | ||
39990e587b | |||
|
51d370e045 | ||
|
4ee4cafad7 | ||
|
e1c0cdd1a2 | ||
|
7b149594fe | ||
|
350b12aa6d | ||
a8da7b6bdf | |||
50ccfe3860 | |||
|
3572ef01cd | ||
|
664d213c04 | ||
d3a971d598 | |||
|
52e1b6eb00 | ||
|
f47e6bc786 | ||
|
1d9169679f | ||
|
a7b7de93dd | ||
|
124cbedf4d | ||
|
4db3b5f908 | ||
9a4a4dddcc | |||
04fa303a81 | |||
4facfb11fa | |||
ef257765fe | |||
5696dd4ed8 | |||
|
9f0a511022 | ||
ffe49e4c67 | |||
28f904783f | |||
6969568549 | |||
bcc74ea3d4 | |||
ef57fb0732 | |||
2930391ee4 | |||
b1dfab70a1 | |||
bdc1427626 | |||
158fafaa79 | |||
426b02b3ea | |||
227ecdb64c | |||
089b110b87 | |||
7e8a1b4030 | |||
f0bf6c5871 |
23
.gitea/workflows/buildtest.yml
Normal file
23
.gitea/workflows/buildtest.yml
Normal file
@@ -0,0 +1,23 @@
|
||||
name: Run ReCI Build Test
|
||||
run-name: Run ReCI Build Test For ${{ gitea.repository }}.
|
||||
on: [push]
|
||||
|
||||
jobs:
|
||||
Explore-Gitea-Actions:
|
||||
runs-on: ubuntu-22.04
|
||||
env:
|
||||
RECI_GIT: https://git.redacted.cc/maxine/ReCI
|
||||
RECI: /RECI
|
||||
steps:
|
||||
- run: echo "The job was automatically triggered by a ${{ gitea.event_name }} event."
|
||||
- run: echo "This job is now running on a ${{ runner.os }} server hosted by Gitea!"
|
||||
- run: echo "The name of your branch is ${{ gitea.ref }} and your repository is ${{ gitea.repository }}."
|
||||
- name: Check out repository code
|
||||
uses: actions/checkout@v3
|
||||
- run: echo "The ${{ gitea.repository }} repository has been cloned to the runner."
|
||||
- run: echo "The workflow is now ready to run your tests on the runner."
|
||||
- run: echo "Install toolchain and run ReCI build test"
|
||||
- run: apt-get update && apt-get install -y lua5.3 git libxrandr-dev libvulkan-dev && git clone $RECI_GIT $RECI
|
||||
- run: lua $RECI/reci.lua -f $RECI/scripts/buildtools.reci -f reci/scripts/builddeps.reci -f $RECI/scripts/buildtest.reci
|
||||
- run: echo this exists so I can run the reci test
|
||||
- run: echo "This job's status is ${{ job.status }}."
|
2
.gitignore
vendored
2
.gitignore
vendored
@@ -1,2 +1,4 @@
|
||||
/cmake-build-debug
|
||||
/.idea
|
||||
build/*
|
||||
.vscode/*
|
||||
|
@@ -1,5 +1,5 @@
|
||||
cmake_minimum_required(VERSION 3.20)
|
||||
project(ReWindowLibrary
|
||||
cmake_minimum_required(VERSION 3.18..3.27)
|
||||
project(ReWindow
|
||||
VERSION 1.0
|
||||
LANGUAGES CXX
|
||||
)
|
||||
@@ -10,54 +10,73 @@ endif()
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
|
||||
if (WIN32)
|
||||
set(CMAKE_CXX_FLAGS "-municode")
|
||||
endif()
|
||||
|
||||
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_SOURCE_DIR}/cmake")
|
||||
|
||||
|
||||
# Enable Package Managers
|
||||
include(cmake/CPM.cmake)
|
||||
include(cmake/CPM.cmake)
|
||||
|
||||
CPMAddPackage(
|
||||
NAME J3ML
|
||||
URL https://git.redacted.cc/josh/j3ml/archive/Prerelease-14.zip
|
||||
NAME Event
|
||||
URL https://git.redacted.cc/josh/Event/archive/Release-12.zip
|
||||
)
|
||||
|
||||
CPMAddPackage(
|
||||
NAME JGL
|
||||
URL https://git.redacted.cc/josh/JGL/archive/pre-1.zip
|
||||
NAME jlog
|
||||
URL https://git.redacted.cc/josh/jlog/archive/Prerelease-16.zip
|
||||
)
|
||||
|
||||
find_package(OpenGL REQUIRED)
|
||||
include_directories({$OPENGL_INCLUDE_DIRS} ${J3ML_SOURCE_DIR}/include ${JGL_SOURCE_DIR}/include)
|
||||
#TODO dlopen these at runtime so if one isn't supported the program still works.
|
||||
|
||||
if (UNIX AND NOT APPLE)
|
||||
include_directories(${Vulkan_INCLUDE_DIR})
|
||||
endif()
|
||||
|
||||
if (WIN32)
|
||||
include_directories(${VULKAN_SDK}/Include)
|
||||
endif()
|
||||
|
||||
include_directories(${J3ML_SOURCE_DIR}/include)
|
||||
include_directories(${jlog_SOURCE_DIR}/include)
|
||||
|
||||
|
||||
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/linux/*.cpp")
|
||||
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/linux/*.cpp" "src/platform/shared/*.cpp" "src/ReWindow/*.cpp" )
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
file(GLOB_RECURSE SOURCES "src/windows/*.cpp")
|
||||
file(GLOB_RECURSE SOURCES "src/types/*.cpp" "src/platform/windows/*.cpp" "src/platform/shared/*.cpp" "src/ReWindow/*.cpp")
|
||||
endif()
|
||||
|
||||
include_directories("include")
|
||||
add_library(ReWindowLibrary SHARED ${SOURCES}
|
||||
include/rewindow/data/X11Scancodes.h
|
||||
include/rewindow/types/key.h
|
||||
include/rewindow/data/WindowsScancodes.h
|
||||
src/rewindow/types/key.cpp
|
||||
src/rewindow/types/window.cpp
|
||||
)
|
||||
# Why god???
|
||||
set_target_properties(ReWindowLibrary PROPERTIES LINKER_LANGUAGE CXX)
|
||||
|
||||
if(UNIX AND NOT APPLE)
|
||||
target_link_libraries(ReWindowLibrary PUBLIC X11 J3ML JGL ${OPENGL_LIBRARIES})
|
||||
add_executable(ReWindowLibraryDemo main.cpp)
|
||||
target_link_libraries(ReWindowLibraryDemo PUBLIC ReWindowLibrary)
|
||||
if(UNIX)
|
||||
add_library(ReWindow SHARED ${SOURCES})
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
endif()
|
||||
add_library(ReWindow STATIC ${SOURCES})
|
||||
endif()
|
||||
|
||||
target_include_directories(ReWindow PUBLIC ${Event_SOURCE_DIR}/include)
|
||||
|
||||
# Why god???
|
||||
set_target_properties(ReWindow PROPERTIES LINKER_LANGUAGE CXX)
|
||||
|
||||
if(UNIX AND NOT APPLE)
|
||||
target_link_libraries(ReWindow PUBLIC X11 Event jlog)
|
||||
target_link_libraries(ReWindow PUBLIC)
|
||||
add_executable(ReWindowDemo main.cpp)
|
||||
target_link_libraries(ReWindowDemo PUBLIC ReWindow)
|
||||
endif()
|
||||
|
||||
if(WIN32)
|
||||
target_compile_options(ReWindow PUBLIC /utf-8)
|
||||
target_link_libraries(ReWindow PUBLIC Event jlog)
|
||||
add_executable(ReWindowDemo main.cpp)
|
||||
target_link_libraries(ReWindowDemo PUBLIC ReWindow)
|
||||
endif()
|
||||
|
81
README.md
81
README.md
@@ -1,33 +1,48 @@
|
||||
|
||||
# ReWindow
|
||||
[](http://unlicense.org/)
|
||||
|
||||
A library which allows easily creating and managing a window and it's events across multiple platforms *primarily for games*.
|
||||
|
||||
|
||||
## Run Demo
|
||||
|
||||
|
||||
Install dependencies
|
||||
|
||||
```bash
|
||||
dnf install cmake make gcc-g++ libX11 libX11-devel
|
||||
```
|
||||
|
||||
Clone the repository
|
||||
|
||||
```bash
|
||||
git clone https://git.redacted.cc/Redacted/ReWindow.git
|
||||
```
|
||||
|
||||
Build
|
||||
|
||||
```bash
|
||||
cd ReWindow && mkdir build && cd build && cmake .. && make
|
||||
```
|
||||
|
||||
Run it
|
||||
|
||||
```bash
|
||||
./ReWindowDemo
|
||||
```
|
||||
# ReWindow
|
||||
[](http://unlicense.org/)
|
||||
|
||||
A library which allows easily creating and managing a window and it's events across multiple platforms *primarily for games*.
|
||||
|
||||
|
||||
## Features
|
||||
- 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
|
||||
- Supported Platforms: X11 on Linux, Windows
|
||||
- Builds on ARM.
|
||||
- One API supports all platforms.
|
||||
- Supports OpenGL, Vulkan, Software Rendering(?)
|
||||
- Public Domain.
|
||||
- Lightweight AF.
|
||||
- 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.
|
||||
|
||||
|
||||
## Run Demo
|
||||
|
||||
Install dependencies
|
||||
|
||||
```bash
|
||||
Fedora/RHEL: dnf install cmake make gcc-g++ libX11 libX11-devel mesa-libGL-devel vulkan-loader-devel
|
||||
Ubuntu/Debian: apt-get install cmake make gcc g++ libx11-6 libx11-dev libgl-dev libvulkan-dev libxrandr-dev
|
||||
```
|
||||
|
||||
Clone the repository
|
||||
|
||||
```bash
|
||||
git clone https://git.redacted.cc/Redacted/ReWindow.git
|
||||
```
|
||||
|
||||
Build
|
||||
|
||||
```bash
|
||||
cd ReWindow && mkdir build && cd build && cmake .. && make
|
||||
```
|
||||
|
||||
Run it
|
||||
|
||||
```bash
|
||||
./ReWindowDemo
|
||||
```
|
||||
|
10
include/ReWindow/ClipboardService.h
Normal file
10
include/ReWindow/ClipboardService.h
Normal file
@@ -0,0 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
/// X11 Clipboard API looked unhinged. So fuck it, use this system for now.
|
||||
namespace ClipboardService
|
||||
{
|
||||
std::string GetClipboard(int historyIndex = 0);
|
||||
void SetClipboard(const std::string& str, bool overwrites_last = false);
|
||||
unsigned int GetClipboardHistorySize();
|
||||
unsigned int GetClipboardHistoryMax();
|
||||
}
|
23
include/ReWindow/InputService.h
Normal file
23
include/ReWindow/InputService.h
Normal file
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
|
||||
#include <Event.h>
|
||||
#include <ReWindow/types/WindowEvents.h>
|
||||
|
||||
namespace InputService {
|
||||
using namespace ReWindow;
|
||||
|
||||
inline Event<KeyboardEvent> OnKeyboardEvent;
|
||||
inline Event<KeyboardEvent> OnKeyEvent;
|
||||
inline Event<KeyDownEvent> OnKeyDown;
|
||||
inline Event<KeyUpEvent> OnKeyUp;
|
||||
inline Event<MouseMoveEvent> OnMouseEvent;
|
||||
inline Event<MouseButtonEvent> OnMouseButtonEvent;
|
||||
inline Event<MouseMoveEvent> OnMouseMove;
|
||||
inline Event<MouseButtonDownEvent> OnMouseDown;
|
||||
inline Event<MouseButtonUpEvent> OnMouseUp;
|
||||
inline Event<MouseWheelEvent> OnMouseWheel;
|
||||
bool IsKeyDown(const Key& key);
|
||||
bool IsMouseButtonDown(const MouseButton& button);
|
||||
std::pair<int, int> GetMousePosition();
|
||||
std::pair<int, int> GetWindowSize();
|
||||
};
|
13
include/ReWindow/Logger.h
Normal file
13
include/ReWindow/Logger.h
Normal file
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include <jlog/Logger.hpp>
|
||||
|
||||
namespace ReWindow::Logger {
|
||||
using namespace jlog;
|
||||
|
||||
extern GenericLogger Info;
|
||||
extern GenericLogger Fatal;
|
||||
extern GenericLogger Error;
|
||||
extern GenericLogger Warning;
|
||||
extern GenericLogger Debug;
|
||||
}
|
57
include/ReWindow/data/GamepadScancodes.h
Normal file
57
include/ReWindow/data/GamepadScancodes.h
Normal file
@@ -0,0 +1,57 @@
|
||||
// @file GamepadScancodes.h
|
||||
// @
|
||||
|
||||
#pragma once
|
||||
|
||||
/*
|
||||
* These scancodes were obtained from some knockoff Xbox controller from PowerA.
|
||||
* I expect these to be fairly generic, so it's a good base to start from.
|
||||
*
|
||||
* Something to keep in mind is the seperation here. On Linux linux/joystick.h
|
||||
* is used to read controller inputs. It's a generic driver/library/whatever the
|
||||
* fuck it's called.
|
||||
*
|
||||
* 2 constants are defined in linux/joystick.h
|
||||
*
|
||||
* JS_EVENT_BUTTON
|
||||
* JS_EVENT_AXIS
|
||||
*
|
||||
* This is why I made seperate enum classes. Both the Axis and the Button scancode
|
||||
* count start from 0x00. Having this seperation is easier to work with.
|
||||
*
|
||||
* I may write a program in the future to let us harvest scancodes from controllers.
|
||||
* I hacked up some C code to get the scancodes for this one without the annoying
|
||||
* stick drift spamming the screen, so with a little more work I could probably turn
|
||||
* it into a generic test program
|
||||
*
|
||||
* P.S Windows is gonna make this slightly more annoying and different from what I've
|
||||
* seen.
|
||||
*
|
||||
* - Maxine
|
||||
*/
|
||||
|
||||
enum class GamepadScancode_AXIS {
|
||||
ABS_X = 0x00, // Xbox Left Thumbstick Axis
|
||||
ABS_Y = 0x01, // <-'
|
||||
ABS_Z = 0x02, // Xbox Left Trigger Axis
|
||||
ABS_RX = 0x03, // Xbox Right Thumbstick Axis
|
||||
ABS_RY = 0x04, // <-'
|
||||
ABS_RZ = 0x05, // Xbox Right Trigger Axis (I know strange ain't it?)
|
||||
ABS_HAT0X = 0x06, // Xbox DPad Axis (The Dpad is basically seen as a 3rd thumbstick)
|
||||
ABS_HAT0Y = 0x07, // <-'
|
||||
}
|
||||
|
||||
enum class GamepadScancode_BTN {
|
||||
BTN_SOUTH = 0x00 // Xbox A Button
|
||||
BTN_EAST = 0x01 // Xbox B Button
|
||||
BTN_WEST = 0x02 // Xbox X Button
|
||||
BTN_NORTH = 0x03 // Xbox Y Button
|
||||
BTN_TL = 0x04, // Xbox Left Bumper
|
||||
BTN_TR = 0x05, // Xbox Right Bumper
|
||||
BTN_START = 0x06, // Xbox Start Button
|
||||
BTN_SELECT = 0x07, // Xbox Select Button
|
||||
BTN_HOME = 0x08, // Xbox Home/Logo Button
|
||||
BTN_THUMBL = 0x09, // Xbox Left Thumstick Button
|
||||
BTN_THUMBR = 0x0a, // Xbox Right Thumbstick Button
|
||||
}
|
||||
|
107
include/ReWindow/data/WindowsScancodes.h
Normal file
107
include/ReWindow/data/WindowsScancodes.h
Normal file
@@ -0,0 +1,107 @@
|
||||
#pragma once
|
||||
|
||||
enum class WindowsScancode {
|
||||
Nothing = 0,
|
||||
ESCAPE = 0x1B, // VK_ESCAPE
|
||||
ONE = 0x31, // '1'
|
||||
TWO = 0x32, // '2'
|
||||
THREE = 0x33, // '3'
|
||||
FOUR = 0x34, // '4'
|
||||
FIVE = 0x35, // '5'
|
||||
SIX = 0x36, // '6'
|
||||
SEVEN = 0x37, // '7'
|
||||
EIGHT = 0x38, // '8'
|
||||
NINE = 0x39, // '9'
|
||||
ZERO = 0x30, // '0'
|
||||
MINUS = 0xBD, // VK_OEM_MINUS
|
||||
EQUALS = 0xBB, // VK_OEM_PLUS
|
||||
BACKSPACE = 0x08, // VK_BACK
|
||||
TAB = 0x09, // VK_TAB
|
||||
Q = 0x51, // 'Q'
|
||||
W = 0x57, // 'W'
|
||||
E = 0x45, // 'E'
|
||||
R = 0x52, // 'R'
|
||||
T = 0x54, // 'T'
|
||||
Y = 0x59, // 'Y'
|
||||
U = 0x55, // 'U'
|
||||
I = 0x49, // 'I'
|
||||
O = 0x4F, // 'O'
|
||||
P = 0x50, // 'P'
|
||||
LEFT_BRACKET = 0xDB, // VK_OEM_4
|
||||
RIGHT_BRACKET = 0xDD, // VK_OEM_6
|
||||
ENTER = 0x0D, // VK_RETURN
|
||||
CTRL = 0x11, // VK_CONTROL
|
||||
A = 0x41, // 'A'
|
||||
S = 0x53, // 'S'
|
||||
D = 0x44, // 'D'
|
||||
F = 0x46, // 'F'
|
||||
G = 0x47, // 'G'
|
||||
H = 0x48, // 'H'
|
||||
J = 0x4A, // 'J'
|
||||
K = 0x4B, // 'K'
|
||||
L = 0x4C, // 'L'
|
||||
SEMICOLON = 0xBA, // VK_OEM_1
|
||||
SINGLEQUOTE = 0xDE, // VK_OEM_7
|
||||
GRAVE = 0xC0, // VK_OEM_3
|
||||
LEFT_SHIFT = 0x10, // VK_LSHIFT
|
||||
BACKSLASH = 0xDC, // VK_OEM_5
|
||||
Z = 0x5A, // 'Z'
|
||||
X = 0x58, // 'X'
|
||||
C = 0x43, // 'C'
|
||||
V = 0x56, // 'V'
|
||||
B = 0x42, // 'B'
|
||||
N = 0x4E, // 'N'
|
||||
M = 0x4D, // 'M'
|
||||
PERIOD = 0xBE, // VK_OEM_PERIOD
|
||||
SLASH = 0xBF, // VK_OEM_2
|
||||
RIGHT_SHIFT = 0xA1, // VK_RSHIFT
|
||||
PRINTSCREEN = 0x2C, // VK_SNAPSHOT
|
||||
ALT = 0x12, // VK_MENU
|
||||
SPACE = 0x20, // VK_SPACE
|
||||
CAPS_LOCK = 0x14, // VK_CAPITAL
|
||||
F1 = 0x70, // VK_F1
|
||||
F2 = 0x71, // VK_F2
|
||||
F3 = 0x72, // VK_F3
|
||||
F4 = 0x73, // VK_F4
|
||||
F5 = 0x74, // VK_F5
|
||||
F6 = 0x75, // VK_F6
|
||||
F7 = 0x76, // VK_F7
|
||||
F8 = 0x77, // VK_F8
|
||||
F9 = 0x78, // VK_F9
|
||||
F10 = 0x79, // VK_F10
|
||||
NUM_LOCK = 0x90, // VK_NUMLOCK
|
||||
SCROLL_LOCK = 0x91, // VK_SCROLL
|
||||
HOME = 0x24, // VK_HOME
|
||||
UP_ARROW = 0x26, // VK_UP
|
||||
PAGE_UP = 0x21, // VK_PRIOR
|
||||
LEFT_ARROW = 0x25, // VK_LEFT
|
||||
DOWN_ARROW = 0x28, // VK_DOWN
|
||||
RIGHT_ARROW = 0x27, // VK_RIGHT
|
||||
END = 0x23, // VK_END
|
||||
PAGE_DOWN = 0x22, // VK_NEXT
|
||||
INSERT = 0x2D, // VK_INSERT
|
||||
DEL = 0x2E, // VK_DELETE
|
||||
F11 = 0x7A, // VK_F11
|
||||
F12 = 0x7B, // VK_F12
|
||||
|
||||
NUMPAD_ZERO = 0x60, // VK_NUMPAD0
|
||||
NUMPAD_ONE = 0x61, // VK_NUMPAD1
|
||||
NUMPAD_TWO = 0x62, // VK_NUMPAD2
|
||||
NUMPAD_THREE = 0x63, // VK_NUMPAD3
|
||||
NUMPAD_FOUR = 0x64, // VK_NUMPAD4
|
||||
NUMPAD_FIVE = 0x65, // VK_NUMPAD5
|
||||
NUMPAD_SIX = 0x66, // VK_NUMPAD6
|
||||
NUMPAD_SEVEN = 0x67, // VK_NUMPAD7
|
||||
NUMPAD_EIGHT = 0x68, // VK_NUMPAD8
|
||||
NUMPAD_NINE = 0x69, // VK_NUMPAD9
|
||||
NUMPAD_PLUS = 0x6B, // VK_ADD
|
||||
NUMPAD_MINUS = 0x6D, // VK_SUBTRACT
|
||||
NUMPAD_ASTERISK = 0x6A,
|
||||
NUMPAD_SLASH = 0x6F,
|
||||
NUMPAD_PERIOD = 0x6E, // VK_DECIMAL
|
||||
NUMPAD_ENTER = 0x0D, // VK_RETURN
|
||||
SUPER = 0x5B,
|
||||
COMMA = 0xBC,
|
||||
MENU = 93,
|
||||
BREAK = 0x13
|
||||
};
|
@@ -24,9 +24,10 @@ enum class X11Scancode {
|
||||
PAGEUP = 112,
|
||||
PAGEDOWN = 117,
|
||||
HOME = 110,
|
||||
MENU = 135,
|
||||
END = 115,
|
||||
INSERT = 118,
|
||||
DELETE = 119,
|
||||
DEL = 119,
|
||||
UP = 111,
|
||||
DOWN = 116,
|
||||
LEFT = 113,
|
||||
@@ -101,9 +102,10 @@ enum class X11Scancode {
|
||||
F8 = 74,
|
||||
F9 = 75,
|
||||
F10 = 76,
|
||||
F11 = 77,
|
||||
F12 = 78,
|
||||
F11 = 95,
|
||||
F12 = 96,
|
||||
PRINT = 107,
|
||||
SCROLL_LOCK = 78,
|
||||
BREAK = 127,
|
||||
|
||||
};
|
80
include/ReWindow/types/Cursors.h
Normal file
80
include/ReWindow/types/Cursors.h
Normal file
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
|
||||
#if __linux__
|
||||
#include <X11/cursorfont.h>
|
||||
#endif
|
||||
|
||||
namespace ReWindow
|
||||
{
|
||||
#if __linux__
|
||||
enum class X11CursorStyle
|
||||
{
|
||||
Default = XC_left_ptr,
|
||||
X = XC_X_cursor,
|
||||
Arrow = XC_arrow,
|
||||
IBeam = XC_xterm,
|
||||
BottomLeftCorner = XC_bottom_left_corner,
|
||||
BottomRightCorner = XC_bottom_right_corner,
|
||||
BottomSide = XC_bottom_side,
|
||||
Dot = XC_dot,
|
||||
DoubleArrow = XC_double_arrow,
|
||||
Exchange = XC_exchange,
|
||||
Hand = XC_hand2,
|
||||
LeftSide = XC_left_side,
|
||||
Plus = XC_plus,
|
||||
RightSide = XC_right_side,
|
||||
Pencil = XC_pencil
|
||||
};
|
||||
|
||||
class CursorStyle {
|
||||
public:
|
||||
X11CursorStyle X11Cursor;
|
||||
CursorStyle(X11CursorStyle style) : X11Cursor(style) {}
|
||||
};
|
||||
|
||||
namespace Cursors {
|
||||
static const CursorStyle Default {X11CursorStyle::Default};
|
||||
static const CursorStyle X {X11CursorStyle::X};
|
||||
static const CursorStyle Arrow {X11CursorStyle::Arrow};
|
||||
static const CursorStyle IBeam {X11CursorStyle::IBeam};
|
||||
static const CursorStyle BottomLeftCorner {X11CursorStyle::BottomLeftCorner};
|
||||
static const CursorStyle BottomRightCorner {X11CursorStyle::BottomRightCorner};
|
||||
static const CursorStyle BottomSide {X11CursorStyle::BottomSide};
|
||||
static const CursorStyle Dot {X11CursorStyle::Dot};
|
||||
static const CursorStyle DoubleArrow {X11CursorStyle::DoubleArrow};
|
||||
static const CursorStyle Exchange {X11CursorStyle::Exchange};
|
||||
static const CursorStyle Hand {X11CursorStyle::Hand};
|
||||
static const CursorStyle LeftSide {X11CursorStyle::LeftSide};
|
||||
static const CursorStyle Plus {X11CursorStyle::Plus};
|
||||
static const CursorStyle RightSide {X11CursorStyle::RightSide};
|
||||
static const CursorStyle Pencil {X11CursorStyle::Pencil};
|
||||
}
|
||||
|
||||
#else
|
||||
// https://learn.microsoft.com/en-us/windows/win32/menurc/about-cursors
|
||||
enum WindowsCursorStyle {
|
||||
Arrow,
|
||||
IBeam,
|
||||
Wait,
|
||||
Cross,
|
||||
Hand,
|
||||
AppStarting,
|
||||
};
|
||||
|
||||
class CursorStyle {
|
||||
public:
|
||||
WindowsCursorStyle WindowsCursor;
|
||||
CursorStyle (WindowsCursorStyle style): WindowsCursor(style) {}
|
||||
};
|
||||
|
||||
namespace Cursors {
|
||||
static const CursorStyle Default {WindowsCursorStyle::Arrow};
|
||||
static const CursorStyle Arrow {WindowsCursorStyle::Arrow};
|
||||
static const CursorStyle IBeam {WindowsCursorStyle::IBeam};
|
||||
static const CursorStyle Cross {WindowsCursorStyle::Cross};
|
||||
static const CursorStyle Wait {WindowsCursorStyle::Wait};
|
||||
static const CursorStyle Hand {WindowsCursorStyle::Hand};
|
||||
static const CursorStyle AppStarting {WindowsCursorStyle::AppStarting};
|
||||
}
|
||||
#endif
|
||||
}
|
154
include/ReWindow/types/Key.h
Normal file
154
include/ReWindow/types/Key.h
Normal file
@@ -0,0 +1,154 @@
|
||||
//
|
||||
// ~DAWSH
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <stdexcept>
|
||||
#include <iostream>
|
||||
#include <string>
|
||||
#include <ReWindow/data/X11Scancodes.h>
|
||||
#include <ReWindow/data/WindowsScancodes.h>
|
||||
|
||||
|
||||
class Key
|
||||
{
|
||||
private:
|
||||
//CLion on Linux falsely marks this as being wrong.
|
||||
static inline std::vector<Key> keyboard{};
|
||||
|
||||
public:
|
||||
static std::vector<Key> GetKeyboard();
|
||||
Key() = default;
|
||||
Key(const char* charcode, X11Scancode scancode, WindowsScancode wSc);
|
||||
std::string Mnemonic;
|
||||
X11Scancode x11ScanCode;
|
||||
WindowsScancode winScanCode;
|
||||
bool operator==(const Key& rhs) const;
|
||||
bool operator<(const Key& rhs) const;
|
||||
Key(const Key&) = default;
|
||||
};
|
||||
|
||||
namespace Keys {
|
||||
// TODO: Encode both Uppercase and Lowercase version for each keymap
|
||||
static const Key Escape {"ESC", X11Scancode::ESCAPE, WindowsScancode::ESCAPE};
|
||||
static const Key F1 {"F1", X11Scancode::F1, WindowsScancode::F1};
|
||||
static const Key F2 {"F2", X11Scancode::F2, WindowsScancode::F2};
|
||||
static const Key F3 {"F3", X11Scancode::F3, WindowsScancode::F3};
|
||||
static const Key F4 {"F4", X11Scancode::F4, WindowsScancode::F4};
|
||||
static const Key F5 {"F5", X11Scancode::F5, WindowsScancode::F5};
|
||||
static const Key F6 {"F6", X11Scancode::F6, WindowsScancode::F6};
|
||||
static const Key F7 {"F7", X11Scancode::F7, WindowsScancode::F7};
|
||||
static const Key F8 {"F8", X11Scancode::F8, WindowsScancode::F8};
|
||||
static const Key F9 {"F9", X11Scancode::F9, WindowsScancode::F9};
|
||||
static const Key F10 {"F10", X11Scancode::F10, WindowsScancode::F10};
|
||||
static const Key F11 {"F11", X11Scancode::F11, WindowsScancode::F11};
|
||||
static const Key F12 {"F12", X11Scancode::F12, WindowsScancode::F12};
|
||||
static const Key Print {"PRINT", X11Scancode::PRINT, WindowsScancode::PRINTSCREEN};
|
||||
static const Key ScrollLock {"SCROLL_LOCK", X11Scancode::SCROLL_LOCK, WindowsScancode::SCROLL_LOCK};
|
||||
static const Key Break {"BREAK", X11Scancode::BREAK, WindowsScancode::BREAK};
|
||||
|
||||
//TODO On Windows, Return & KP_RETURN are the same thing.
|
||||
static const Key NumPadReturn {"KP_↵", X11Scancode::KP_RETURN, WindowsScancode::NUMPAD_ENTER};
|
||||
static const Key NumPadPlus {"KP_+", X11Scancode::KP_PLUS, WindowsScancode::NUMPAD_PLUS};
|
||||
static const Key NumPadMinus {"KP_-", X11Scancode::KP_MINUS, WindowsScancode::NUMPAD_MINUS};
|
||||
static const Key NumPadAsterisk {"KP_*", X11Scancode::KP_ASTERISK, WindowsScancode::NUMPAD_ASTERISK};
|
||||
static const Key NumPadForwardSlash {"KP_/", X11Scancode::KP_SLASH, WindowsScancode::NUMPAD_SLASH};
|
||||
static const Key NumPadPeriod {"KP_.", X11Scancode::KP_PERIOD, WindowsScancode::NUMPAD_PERIOD};
|
||||
static const Key NumPadNumLock {"KP_NUMLOCK", X11Scancode::KP_NUMLOCK, WindowsScancode::NUM_LOCK};
|
||||
|
||||
static const Key NumPad1 {"KP_1", X11Scancode::KP_1, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad2 {"KP_2", X11Scancode::KP_2, WindowsScancode::NUMPAD_TWO};
|
||||
static const Key NumPad3 {"KP_3", X11Scancode::KP_3, WindowsScancode::NUMPAD_THREE};
|
||||
static const Key NumPad4 {"KP_4", X11Scancode::KP_4, WindowsScancode::NUMPAD_FOUR};
|
||||
static const Key NumPad5 {"KP_5", X11Scancode::KP_5, WindowsScancode::NUMPAD_FIVE};
|
||||
static const Key NumPad6 {"KP_6", X11Scancode::KP_6, WindowsScancode::NUMPAD_SIX};
|
||||
static const Key NumPad7 {"KP_7", X11Scancode::KP_7, WindowsScancode::NUMPAD_SEVEN};
|
||||
static const Key NumPad8 {"kP_8", X11Scancode::KP_8, WindowsScancode::NUMPAD_EIGHT};
|
||||
static const Key NumPad9 {"KP_9", X11Scancode::KP_9, WindowsScancode::NUMPAD_NINE};
|
||||
static const Key NumPad0 {"KP_0", X11Scancode::KP_0, WindowsScancode::NUMPAD_ZERO};
|
||||
|
||||
static const Key Grave {"`", X11Scancode::GRAVE, WindowsScancode::GRAVE};
|
||||
static const Key One {"1", X11Scancode::ONE, WindowsScancode::ONE};
|
||||
static const Key Two {"2", X11Scancode::TWO, WindowsScancode::TWO};
|
||||
static const Key Three {"3", X11Scancode::THREE, WindowsScancode::THREE};
|
||||
static const Key Four {"4", X11Scancode::FOUR, WindowsScancode::FOUR};
|
||||
static const Key Five {"5", X11Scancode::FIVE, WindowsScancode::FIVE};
|
||||
static const Key Six {"6", X11Scancode::SIX, WindowsScancode::SIX};
|
||||
static const Key Seven {"7", X11Scancode::SEVEN, WindowsScancode::SEVEN};
|
||||
static const Key Eight {"8", X11Scancode::EIGHT, WindowsScancode::EIGHT};
|
||||
static const Key Nine {"9", X11Scancode::NINE, WindowsScancode::NINE};
|
||||
static const Key Zero {"0", X11Scancode::ZERO, WindowsScancode::ZERO};
|
||||
static const Key Minus {"-", X11Scancode::MINUS, WindowsScancode::MINUS};
|
||||
static const Key Equals {"+", X11Scancode::EQUALS, WindowsScancode::EQUALS};
|
||||
static const Key Backspace {"⌫", X11Scancode::BACKSPACE, WindowsScancode::BACKSPACE};
|
||||
|
||||
static const Key Tab {"⇥", X11Scancode::TAB, WindowsScancode::TAB};
|
||||
static const Key Q {"Q", X11Scancode::Q, WindowsScancode::Q};
|
||||
static const Key W {"W", X11Scancode::W, WindowsScancode::W};
|
||||
static const Key E {"E", X11Scancode::E, WindowsScancode::E};
|
||||
static const Key R {"R", X11Scancode::R, WindowsScancode::R};
|
||||
static const Key T {"T", X11Scancode::T, WindowsScancode::T};
|
||||
static const Key Y {"Y", X11Scancode::Y, WindowsScancode::Y};
|
||||
static const Key U {"U", X11Scancode::U, WindowsScancode::U};
|
||||
static const Key I {"I", X11Scancode::I, WindowsScancode::I};
|
||||
static const Key O {"O", X11Scancode::O, WindowsScancode::O};
|
||||
static const Key P {"P", X11Scancode::P, WindowsScancode::P};
|
||||
static const Key LeftBracket {"[", X11Scancode::OPENING_SQUARE_BRACKET, WindowsScancode::LEFT_BRACKET};
|
||||
static const Key RightBracket {"]", X11Scancode::CLOSING_SQUARE_BRACKET, WindowsScancode::RIGHT_BRACKET};
|
||||
static const Key BackSlash {"\\", X11Scancode::BACKSLASH, WindowsScancode::BACKSLASH};
|
||||
|
||||
static const Key CapsLock = {"CAPS", X11Scancode::CAPSLOCK, WindowsScancode::CAPS_LOCK};
|
||||
static const Key A {"A", X11Scancode::A, WindowsScancode::A};
|
||||
static const Key S {"S", X11Scancode::S, WindowsScancode::S};
|
||||
static const Key D {"D", X11Scancode::D, WindowsScancode::D};
|
||||
static const Key F {"F", X11Scancode::F, WindowsScancode::F};
|
||||
static const Key G {"G", X11Scancode::G, WindowsScancode::G};
|
||||
static const Key H {"H", X11Scancode::H, WindowsScancode::H};
|
||||
static const Key J {"J", X11Scancode::J, WindowsScancode::J};
|
||||
static const Key K {"K", X11Scancode::K, WindowsScancode::K};
|
||||
static const Key L {"L", X11Scancode::L, WindowsScancode::L};
|
||||
static const Key Semicolon {";", X11Scancode::SEMICOLON, WindowsScancode::SEMICOLON};
|
||||
static const Key SingeQuote {"\'", X11Scancode::SINGLEQUOTE, WindowsScancode::SINGLEQUOTE};
|
||||
static const Key Return {"↵", X11Scancode::RETURN, WindowsScancode::ENTER};
|
||||
|
||||
static const Key LeftShift {"⇧", X11Scancode::LEFT_SHIFT, WindowsScancode::LEFT_SHIFT};
|
||||
static const Key Z {"Z", X11Scancode::Z, WindowsScancode::Z};
|
||||
static const Key X {"X", X11Scancode::X, WindowsScancode::X};
|
||||
static const Key C {"C", X11Scancode::C, WindowsScancode::C};
|
||||
static const Key V {"V", X11Scancode::V, WindowsScancode::V};
|
||||
static const Key B {"B", X11Scancode::B, WindowsScancode::B};
|
||||
static const Key N {"N", X11Scancode::N, WindowsScancode::N};
|
||||
static const Key M {"M", X11Scancode::M, WindowsScancode::M};
|
||||
static const Key Comma = {",", X11Scancode::COMMA, WindowsScancode::COMMA};
|
||||
static const Key Period {".", X11Scancode::PERIOD, WindowsScancode::PERIOD};
|
||||
static const Key ForwardSlash {"/", X11Scancode::SLASH, WindowsScancode::SLASH};
|
||||
|
||||
static const Key LeftControl {"LCTRL", X11Scancode::LEFT_CTRL, WindowsScancode::CTRL};
|
||||
static const Key Super {"❖", X11Scancode::SUPER, WindowsScancode::SUPER};
|
||||
static const Key LeftAlt {"🄰", X11Scancode::LEFT_ALT, WindowsScancode::ALT};
|
||||
static const Key Space {" ", X11Scancode::SPACE, WindowsScancode::SPACE};
|
||||
static const Key RightAlt {"R🄰", X11Scancode::RIGHT_ALT, WindowsScancode::ALT};
|
||||
static const Key Menu = {"▤", X11Scancode::MENU, WindowsScancode::MENU};
|
||||
static const Key RightControl {"RCTRL", X11Scancode::RIGHT_CONTROL, WindowsScancode::CTRL};
|
||||
static const Key RightShift {"R⇧", X11Scancode::RIGHT_SHIFT, WindowsScancode::RIGHT_SHIFT};
|
||||
|
||||
static const Key Insert {"INSERT", X11Scancode::INSERT, WindowsScancode::INSERT};
|
||||
static const Key Home {"HOME", X11Scancode::HOME, WindowsScancode::HOME};
|
||||
static const Key PageUp {"PAGEUP", X11Scancode::PAGEUP, WindowsScancode::PAGE_UP};
|
||||
static const Key Delete {"DELETE", X11Scancode::DEL, WindowsScancode::DEL};
|
||||
static const Key End {"End", X11Scancode::END, WindowsScancode::END};
|
||||
static const Key PageDown {"PAGEDOWN", X11Scancode::PAGEDOWN, WindowsScancode::PAGE_DOWN};
|
||||
|
||||
static const Key UpArrow {reinterpret_cast<const char*>(u8"↑"), X11Scancode::UP, WindowsScancode::UP_ARROW};
|
||||
static const Key DownArrow {reinterpret_cast<const char*>(u8"↓"), X11Scancode::DOWN, WindowsScancode::DOWN_ARROW};
|
||||
static const Key LeftArrow {reinterpret_cast<const char*>(u8"←"), X11Scancode::LEFT, WindowsScancode::LEFT_ARROW};
|
||||
static const Key RightArrow {reinterpret_cast<const char*>(u8"→"), X11Scancode::RIGHT, WindowsScancode::RIGHT_ARROW};
|
||||
|
||||
}
|
||||
|
||||
enum class KeyState {Pressed, Released};
|
||||
|
||||
|
||||
|
||||
Key GetKeyFromX11Scancode(X11Scancode code);
|
||||
Key GetKeyFromWindowsScancode(WindowsScancode code);
|
22
include/ReWindow/types/Keyboard.h
Normal file
22
include/ReWindow/types/Keyboard.h
Normal file
@@ -0,0 +1,22 @@
|
||||
/// 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 keyboard.h
|
||||
/// @desc A class that models the functionality of a keyboard device.
|
||||
/// @edit 2024-07-29
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
namespace ReWindow
|
||||
{
|
||||
class InputDevice {};
|
||||
|
||||
class Keyboard : public InputDevice
|
||||
{
|
||||
|
||||
};
|
||||
}
|
26
include/ReWindow/types/Mouse.h
Normal file
26
include/ReWindow/types/Mouse.h
Normal file
@@ -0,0 +1,26 @@
|
||||
/// 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 keyboard.h
|
||||
/// @desc A class that models the functionality of a mouse / pointer device.
|
||||
/// @edit 2024-07-29
|
||||
|
||||
#pragma once
|
||||
|
||||
|
||||
namespace ReWindow
|
||||
{
|
||||
|
||||
class InputDevice {}; // TODO: Remember to break InputDevice into it's own file and not define it twice!!!
|
||||
|
||||
class Pointer : public InputDevice {};
|
||||
|
||||
|
||||
class Mouse : public Pointer
|
||||
{
|
||||
|
||||
};
|
||||
}
|
46
include/ReWindow/types/MouseButton.h
Normal file
46
include/ReWindow/types/MouseButton.h
Normal file
@@ -0,0 +1,46 @@
|
||||
/// 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 mousebutton.hpp
|
||||
/// @desc MouseButton class and defined MouseButtons.
|
||||
/// @edit 2024-07-29
|
||||
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
class MouseButton {
|
||||
public:
|
||||
std::string Mnemonic;
|
||||
unsigned int ButtonIndex;
|
||||
|
||||
MouseButton() = default;
|
||||
explicit MouseButton(const std::string& charcode, unsigned int index);
|
||||
|
||||
bool operator == (const MouseButton& mb) const;
|
||||
bool operator<(const MouseButton& rhs) const;
|
||||
MouseButton(const MouseButton&) = default;
|
||||
};
|
||||
|
||||
|
||||
namespace MouseButtons
|
||||
{
|
||||
static const MouseButton Left ("L", 1);
|
||||
static const MouseButton Right ("R", 2);
|
||||
static const MouseButton Middle ("M", 3);
|
||||
static const MouseButton Mouse4 ("4", 8);
|
||||
static const MouseButton Mouse5 ("5", 9);
|
||||
static const MouseButton Unimplemented ("?", 0);
|
||||
|
||||
/// NOTE: IsMouseButtonDown will not return correctly for the mouse-wheel-buttons, because the action is effectively instantaneous.
|
||||
static const MouseButton MWheelUp ("U", 4);
|
||||
/// NOTE: IsMouseButtonDown will not return correctly for the mouse-wheel-buttons, because the action is effectively instantaneous.
|
||||
static const MouseButton MWheelDown ("D", 5);
|
||||
}
|
||||
|
||||
MouseButton GetMouseButtonFromXButton(unsigned int button);
|
||||
|
||||
|
407
include/ReWindow/types/Window.h
Normal file
407
include/ReWindow/types/Window.h
Normal file
@@ -0,0 +1,407 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <Event.h>
|
||||
#include <map>
|
||||
#include <thread>
|
||||
#include <ReWindow/types/Key.h>
|
||||
#include <ReWindow/types/Cursors.h>
|
||||
#include <ReWindow/types/MouseButton.h>
|
||||
#include <ReWindow/types/WindowEvents.h>
|
||||
#include <queue>
|
||||
#include <Windows.h>
|
||||
|
||||
|
||||
namespace ReWindow {
|
||||
struct KeyboardState { std::map<Key, bool> PressedKeys; };
|
||||
|
||||
class MouseState;
|
||||
class RWindow;
|
||||
class OpenGLWindow;
|
||||
class VulkanWindow;
|
||||
}
|
||||
|
||||
class ReWindow::MouseState {
|
||||
public:
|
||||
struct
|
||||
{
|
||||
bool LMB = false;
|
||||
bool RMB = false;
|
||||
bool MMB = false;
|
||||
bool SideButton1 = false;
|
||||
bool SideButton2 = false;
|
||||
bool MWheelUp = false;
|
||||
bool MWheelDown = false;
|
||||
}
|
||||
|
||||
Buttons;
|
||||
std::pair<int, int> Position;
|
||||
int Wheel = 0;
|
||||
public:
|
||||
[[nodiscard]] bool IsDown(const MouseButton& btn) const;
|
||||
void Set(const MouseButton& btn, bool state);
|
||||
bool& operator[](const MouseButton& btn);
|
||||
};
|
||||
|
||||
/// 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 = 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 cursor_focused = false;
|
||||
bool toggling_cursor_focus = false;
|
||||
bool key_repeat = false;
|
||||
|
||||
float delta_time = 0.f;
|
||||
float refresh_rate = 0.f;
|
||||
unsigned long long refresh_count = 0;
|
||||
std::string title = "Redacted Window";
|
||||
|
||||
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
|
||||
|
||||
float refresh_rate_prev_1 = 0.f;
|
||||
float refresh_rate_prev_2 = 0.f;
|
||||
float refresh_rate_prev_3 = 0.f;
|
||||
float refresh_rate_prev_4 = 0.f;
|
||||
float refresh_rate_prev_5 = 0.f;
|
||||
float avg_refresh_rate = 0.0f;
|
||||
|
||||
/// 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]] std::pair<int, int> GetAccurateCursorCoordinates() const;
|
||||
protected:
|
||||
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.
|
||||
void Fullscreen();
|
||||
/// Requests the operating system to take the window out of fullscreen mode. Previously saved window size is restored, if possible.
|
||||
void RestoreFromFullscreen();
|
||||
|
||||
public:
|
||||
KeyboardState currentKeyboard; // current frame keyboard state.
|
||||
KeyboardState previousKeyboard; // previous frame keyboard state.
|
||||
|
||||
/// The default constructor does not set any members, and are left uninitialized.
|
||||
RWindow();
|
||||
/// Constructs a window by explicitly setting the title, width, height, and optionally; rendering API, fullscreen, resizable, and vsync.
|
||||
/// @param wTitle The window title text.
|
||||
/// @param wWidth
|
||||
/// @param wHeight
|
||||
/// @param wFullscreen
|
||||
/// @param wResizable
|
||||
/// @param wVsync
|
||||
explicit RWindow(const std::string& wTitle, int wWidth = 640, int wHeight = 480,
|
||||
bool wFullscreen = false, bool wResizable = true, bool wVsync = false);
|
||||
|
||||
/// The destructor deallocates and cleans up any memory used by the RWindow program.
|
||||
/// @note If the window handle is not already destroyed, it will be done here.
|
||||
virtual ~RWindow();
|
||||
|
||||
static RWindow* GetExtant() { return extant; };
|
||||
|
||||
/// Bindables are provided for hooking into window instances conveniently, without the need to derive and override for simple use cases.
|
||||
Event<> OnOpenEvent;
|
||||
Event<> OnClosingEvent;
|
||||
Event<RWindowEvent> OnFocusLostEvent;
|
||||
Event<RWindowEvent> OnFocusGainEvent;
|
||||
Event<float> OnRefreshEvent;
|
||||
Event<WindowResizeRequestEvent> OnResizeRequestEvent;
|
||||
Event<KeyDownEvent> OnKeyDownEvent;
|
||||
Event<KeyUpEvent> OnKeyUpEvent;
|
||||
Event<MouseMoveEvent> OnMouseMoveEvent;
|
||||
Event<MouseButtonDownEvent> OnMouseButtonDownEvent;
|
||||
Event<MouseButtonUpEvent> OnMouseButtonUpEvent;
|
||||
Event<MouseWheelEvent> OnMouseWheelEvent;
|
||||
|
||||
/// 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&) {}
|
||||
|
||||
[[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]] 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]] 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();
|
||||
|
||||
/** Display a small window with some text and an "OK" button.
|
||||
* I tried un-defining the macro, Calling it in a lambda,
|
||||
* Calling MessageBoxA, Putting the call to the MessageBox
|
||||
* function in its own namespace and then calling that.
|
||||
* 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 DialogOK(const std::string& title, const std::string& message);
|
||||
|
||||
/// Sets whether the window is fullscreen.
|
||||
void SetFullscreen(bool fs);
|
||||
|
||||
/// 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);
|
||||
[[nodiscard]] std::string GetTitle() const;
|
||||
|
||||
/// 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 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.
|
||||
void DestroyOSWindowHandle();
|
||||
|
||||
/// Reads events from the operating system, and processes them accordingly.
|
||||
/// TODO: Move out of public API, consumers should call Refresh or ideally an update() call.
|
||||
void PollEvents();
|
||||
|
||||
/// Updates internal window state, similar to ManagedRefresh, but without accounting for any timekeeping. This is left up to the user.
|
||||
void Refresh();
|
||||
|
||||
/// Updates the window and handles timing internally.
|
||||
void ManagedRefresh();
|
||||
|
||||
/// Requests the operating system to change the window size.
|
||||
/// @param width
|
||||
/// @param height
|
||||
void SetSize(int width, int height);
|
||||
|
||||
/// Requests the operating system to change the window size.
|
||||
/// @param size
|
||||
void SetSize(const std::pair<int, int>& size);
|
||||
|
||||
/// Returns the position of the window's top-left corner relative to the display
|
||||
[[nodiscard]] std::pair<int, int> GetPosition() const;
|
||||
|
||||
/// Returns the known size of the window, in {x,y} pixel measurement.
|
||||
[[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 SetPosition(int x, int y);
|
||||
|
||||
/// Requests the operating system to move the window to the specified coordinates on the display.
|
||||
/// @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.
|
||||
void Raise();
|
||||
|
||||
/// Push the window Lower, such that it is effectively hidden behind other windows.
|
||||
/// 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;
|
||||
|
||||
/// @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();
|
||||
|
||||
/// 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);
|
||||
|
||||
/// 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 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();
|
||||
|
||||
/// Computes elapsed time from a start-point and end-point.
|
||||
float ComputeElapsedFrameTimeSeconds(std::chrono::steady_clock::time_point start, std::chrono::steady_clock::time_point end);
|
||||
|
||||
/// Updates internals to account for the latest calculated frame time.
|
||||
void UpdateFrameTiming(float frame_time);
|
||||
|
||||
#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);
|
||||
/// @note This will be invoked **before** the window-close procedure begins.
|
||||
void processOnClose();
|
||||
/// @note This will be invoked **after** the window-open procedure completes.
|
||||
void processOnOpen();
|
||||
void processMousePress(const MouseButton& btn);
|
||||
void processMouseRelease(const MouseButton& btn);
|
||||
void processFocusIn();
|
||||
void processFocusOut();
|
||||
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 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;
|
||||
|
||||
/// This function instructs the operating system to create the actual window, and give it to us to control.
|
||||
/// Calling this function, therefore, creates the real 'window' object on the operating system.
|
||||
[[nodiscard]] virtual bool Open() = 0;
|
||||
|
||||
/// Bring attention to the user, On X11 this flashes the entry for this window in the window list.
|
||||
/// @note If the window is already in focus when this is called nothing happens.
|
||||
void Flash();
|
||||
|
||||
/// @returns True if we are definitely running on a software renderer.
|
||||
/// @note For some APIs this isn't typically possible.
|
||||
[[nodiscard]] virtual bool SoftwareRendered() { return false; }
|
||||
};
|
||||
|
||||
// TODO Set flags in window constructor.
|
||||
class ReWindow::OpenGLWindow : public RWindow {
|
||||
protected:
|
||||
uint8_t gl_major, gl_minor;
|
||||
public:
|
||||
void SwapBuffers() override;
|
||||
void SetVsyncEnabled(bool state) override;
|
||||
std::string GetGraphicsDriverVendor() override;
|
||||
[[nodiscard]] bool Open() override;
|
||||
[[nodiscard]] bool SoftwareRendered() override;
|
||||
public:
|
||||
OpenGLWindow(const std::string& title, int width, int height, uint8_t gl_major, uint8_t gl_minor);
|
||||
};
|
||||
|
||||
class ReWindow::VulkanWindow : public RWindow {
|
||||
public:
|
||||
void SwapBuffers() override;
|
||||
void SetVsyncEnabled(bool state) override;
|
||||
std::string GetGraphicsDriverVendor() override;
|
||||
[[nodiscard]] bool Open() override;
|
||||
VulkanWindow(const std::string& title, int width, int height);
|
||||
};
|
97
include/ReWindow/types/WindowEvents.h
Normal file
97
include/ReWindow/types/WindowEvents.h
Normal file
@@ -0,0 +1,97 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <ReWindow/types/Key.h>
|
||||
#include <ReWindow/types/MouseButton.h>
|
||||
|
||||
namespace ReWindow {
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
using precision_clock = std::chrono::high_resolution_clock;
|
||||
using precision_timestamp = precision_clock::time_point;
|
||||
|
||||
class TimestampedEvent {
|
||||
public:
|
||||
precision_timestamp Timestamp;
|
||||
explicit TimestampedEvent(precision_timestamp timestamp) : Timestamp(timestamp) {}
|
||||
TimestampedEvent() : Timestamp(precision_clock::now())
|
||||
{ }
|
||||
};
|
||||
|
||||
class RWindowEvent : public TimestampedEvent {
|
||||
public:
|
||||
RWindowEvent() : TimestampedEvent() { }
|
||||
};
|
||||
|
||||
class InputDeviceEvent : public RWindowEvent {
|
||||
public:
|
||||
InputDeviceEvent() : RWindowEvent() { }
|
||||
};
|
||||
|
||||
class KeyboardEvent : public InputDeviceEvent {
|
||||
public:
|
||||
Key key;
|
||||
KeyState state;
|
||||
KeyboardEvent(const Key& key, KeyState state) : InputDeviceEvent(), key(key), state(state) {}
|
||||
};
|
||||
class MouseEvent : public InputDeviceEvent {};
|
||||
|
||||
class GamepadEvent : public InputDeviceEvent {};
|
||||
|
||||
class MouseButtonEvent : public MouseEvent {
|
||||
public:
|
||||
MouseButton Button;
|
||||
bool Pressed; // TODO: replace with MouseButtonState enum
|
||||
MouseButtonEvent() = default;
|
||||
MouseButtonEvent(const MouseButton& button, bool pressed) : MouseEvent(), Button(button), Pressed(pressed) {}
|
||||
};
|
||||
|
||||
class MouseButtonDownEvent : public MouseButtonEvent {
|
||||
public:
|
||||
MouseButtonDownEvent() = default;
|
||||
explicit MouseButtonDownEvent(const MouseButton& button) : MouseButtonEvent(button, true) {}
|
||||
};
|
||||
|
||||
class MouseButtonUpEvent : public MouseButtonEvent {
|
||||
public:
|
||||
|
||||
MouseButtonUpEvent() = default;
|
||||
explicit MouseButtonUpEvent(const MouseButton& button) : MouseButtonEvent(button, false) {}
|
||||
};
|
||||
|
||||
class MouseMoveEvent : public MouseEvent {
|
||||
public:
|
||||
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(std::pair<int, int>(x, y))
|
||||
{}
|
||||
};
|
||||
|
||||
class KeyDownEvent : public KeyboardEvent {
|
||||
public:
|
||||
explicit KeyDownEvent(const Key& key) : KeyboardEvent(key, KeyState::Pressed) {}
|
||||
};
|
||||
|
||||
class KeyUpEvent : public KeyboardEvent {
|
||||
public:
|
||||
explicit KeyUpEvent(const Key& key) : KeyboardEvent(key, KeyState::Released) {}
|
||||
};
|
||||
|
||||
class MouseWheelEvent : public MouseEvent
|
||||
{
|
||||
public:
|
||||
int WheelMovement;
|
||||
MouseWheelEvent() = default;
|
||||
MouseWheelEvent(int wheel) : MouseEvent(), WheelMovement(wheel) {}
|
||||
};
|
||||
|
||||
|
||||
|
||||
class WindowResizeRequestEvent : public MouseButtonEvent
|
||||
{
|
||||
public:
|
||||
std::pair<int, int> Size;
|
||||
};
|
||||
}
|
@@ -1,95 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
|
||||
enum class WindowsScancode {
|
||||
Nothing = 0,
|
||||
ESCAPE = 0x01,
|
||||
ONE = 0x02,
|
||||
TWO = 0x03,
|
||||
THREE = 0x04,
|
||||
FOUR = 0x05,
|
||||
FIVE = 0x06,
|
||||
SIX = 0x07,
|
||||
SEVEN = 0x08,
|
||||
EIGHT = 0x09,
|
||||
NINE = 0x0A,
|
||||
ZERO = 0x0B,
|
||||
MINUS = 0x0C,
|
||||
EQUALS = 0x0D,
|
||||
BACKSPACE = 0x0E,
|
||||
TAB = 0x0F,
|
||||
Q = 0x10,
|
||||
W = 0x11,
|
||||
E = 0x12,
|
||||
R = 0x13,
|
||||
T = 0x14,
|
||||
Y = 0x15,
|
||||
U = 0x16,
|
||||
I = 0x17,
|
||||
O = 0x18,
|
||||
P = 0x19,
|
||||
LEFT_BRACKET = 0x1A,
|
||||
RIGHT_BRACKET = 0x1B,
|
||||
ENTER = 0x1C,
|
||||
CTRL = 0x1D,
|
||||
A = 0x1E,
|
||||
S = 0x1F,
|
||||
D = 0x20,
|
||||
F = 0x21,
|
||||
G = 0x22,
|
||||
H = 0x23,
|
||||
J = 0x24,
|
||||
K = 0x25,
|
||||
L = 0x26,
|
||||
SEMICOLON = 0x27,
|
||||
SINGLEQUOTE = 0x28,
|
||||
GRAVE = 0x29,
|
||||
LEFT_SHIFT = 0x2A,
|
||||
BACKSLASH = 0x2B,
|
||||
Z = 0x2C,
|
||||
X = 0x2D,
|
||||
C = 0x2E,
|
||||
V = 0x2F,
|
||||
B = 0x30,
|
||||
N = 0x30,
|
||||
M = 0x32,
|
||||
COMMA = 0x33,
|
||||
PERIOD = 0x34,
|
||||
SLASH = 0x35,
|
||||
RIGHT_SHIFT = 0x36,
|
||||
PRINTSCREEN = 0x37,
|
||||
ALT = 0x38,
|
||||
SPACE = 0x39,
|
||||
CAPS_LOCK = 0x3A,
|
||||
F1 = 0x3B,
|
||||
F2 = 0x3C,
|
||||
F3 = 0x3D,
|
||||
F4 = 0x3E,
|
||||
F5 = 0x3F,
|
||||
F6 = 0x40,
|
||||
F7 = 0x41,
|
||||
F8 = 0x42,
|
||||
F9 = 0x43,
|
||||
F10 = 0x44,
|
||||
NUM_LOCK = 0x45,
|
||||
SCROLL_LOCK = 0x46,
|
||||
HOME = 0x47,
|
||||
UP_ARROW = 0x48,
|
||||
LEFT_ARROW,
|
||||
DOWN_ARROW,
|
||||
RIGHT_ARROW,
|
||||
PAGE_UP = 0x49,
|
||||
NUMPAD_MINUS = 0x4A,
|
||||
NUMPAD_4 = 0x4B,
|
||||
NUMPAD_5 = 0x4C,
|
||||
NUMPAD_6 = 0x4D,
|
||||
NUMPAD_PLUS = 0x4E,
|
||||
NUMPAD_ONE = 0x4F,
|
||||
NUMPAD_TWO = 0x50,
|
||||
NUMPAD_THREE = 0x51,
|
||||
NUMPAD_ZERO = 0x52,
|
||||
DELETE = 0x53,
|
||||
F11 = 0x85,
|
||||
F12 = 0x86, // FIX
|
||||
|
||||
};
|
@@ -1,81 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <chrono>
|
||||
#include <functional>
|
||||
|
||||
|
||||
template <typename ... Args>
|
||||
class Event;
|
||||
|
||||
template <typename ... Args>
|
||||
class EventConnection {
|
||||
private:
|
||||
using delegate = std::function<void(Args...)>;
|
||||
public:
|
||||
EventConnection(Event<Args...> *creator, delegate cb) : owner(creator), callback(std::move(cb)) {}
|
||||
bool Disconnect(); // Breaks the event connection, but does not destroy the instance
|
||||
void Invoke(Args... e);
|
||||
private:
|
||||
Event<Args...> * owner;
|
||||
delegate callback;
|
||||
bool active = true;
|
||||
};
|
||||
|
||||
template <typename ... Args>
|
||||
class Event {
|
||||
public:
|
||||
using delegate = std::function<void(Args...)>;
|
||||
using connection = EventConnection<Args ...>;
|
||||
using event_ptr = std::shared_ptr<connection>;
|
||||
public:
|
||||
void Await(Args& ... arg);
|
||||
void Invoke(Args... args);
|
||||
void operator()(Args... args);
|
||||
connection Connect(delegate callback);
|
||||
void Disconnect(connection &conn);
|
||||
connection operator+=(delegate callback);
|
||||
private:
|
||||
std::vector<event_ptr> listeners;
|
||||
uint64_t listenerCounter = 0;
|
||||
};
|
||||
|
||||
|
||||
template<typename... Args>
|
||||
EventConnection<Args...> Event<Args...>::operator+=(Event::delegate callback) { return Connect(callback); }
|
||||
|
||||
template<typename... Args>
|
||||
void Event<Args...>::operator()(Args... args) { Invoke(args...);}
|
||||
|
||||
template <typename... Args>
|
||||
void EventConnection<Args...>::Invoke(Args... e) { callback(e...); }
|
||||
|
||||
template <typename ... Args>
|
||||
bool EventConnection<Args...>::Disconnect() {
|
||||
if (active) {
|
||||
owner->Disconnect(this);
|
||||
active = false;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename ... Args>
|
||||
void Event<Args...>::Invoke(Args... args) {
|
||||
for (event_ptr &connection_ptr: this->listeners) {
|
||||
connection_ptr->Invoke(args...);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ... Args>
|
||||
EventConnection<Args...> Event<Args...>::Connect(delegate callback)
|
||||
{
|
||||
event_ptr retval(new connection(this, callback));
|
||||
this->listeners.push_back(retval);
|
||||
return *retval;
|
||||
}
|
||||
|
||||
template <typename ... Args>
|
||||
void Event<Args...>::Disconnect(connection &conn) {
|
||||
listeners.erase(std::remove(listeners.begin(), listeners.end(), 99), listeners.end());
|
||||
}
|
||||
|
@@ -1,169 +0,0 @@
|
||||
//
|
||||
// ~DAWSH
|
||||
#pragma once
|
||||
|
||||
|
||||
#include <vector>
|
||||
#include <J3ML/LinearAlgebra/Vector2.h>
|
||||
|
||||
#include <stdexcept>
|
||||
|
||||
#if __linux__
|
||||
#include <X11/X.h>
|
||||
#endif
|
||||
|
||||
#include "rewindow/data/X11Scancodes.h"
|
||||
#include "rewindow/data/WindowsScancodes.h"
|
||||
|
||||
using Vector2 = LinearAlgebra::Vector2;
|
||||
|
||||
class Key
|
||||
{
|
||||
private:
|
||||
static std::vector<Key> keyboard;
|
||||
public:
|
||||
inline static std::vector<Key> GetKeyboard();
|
||||
Key();
|
||||
Key(char charcode, X11Scancode scancode, WindowsScancode wSc);
|
||||
char CharCode;
|
||||
X11Scancode x11ScanCode;
|
||||
WindowsScancode winScanCode;
|
||||
bool operator==(const Key& rhs) const;
|
||||
bool operator<(const Key& rhs) const;
|
||||
Key(const Key&) = default;
|
||||
|
||||
};
|
||||
|
||||
namespace Keys {
|
||||
static const Key Escape {'\b', X11Scancode::ESCAPE, WindowsScancode::ESCAPE};
|
||||
static const Key F1 {'\u000f', X11Scancode::F1, WindowsScancode::F1};
|
||||
static const Key F2 {'\u000f', X11Scancode::F2, WindowsScancode::F2};
|
||||
static const Key F3 {'\u000f', X11Scancode::F3, WindowsScancode::F3};
|
||||
static const Key F4 {'\u000f', X11Scancode::F4, WindowsScancode::F4};
|
||||
static const Key F5 {'\u000f', X11Scancode::F5, WindowsScancode::F5};
|
||||
static const Key F6 {'\u000f', X11Scancode::F6, WindowsScancode::F6};
|
||||
static const Key F7 {'\u000f', X11Scancode::F7, WindowsScancode::F7};
|
||||
static const Key F8 {'\u000f', X11Scancode::F8, WindowsScancode::F8};
|
||||
static const Key F9 {'\u000f', X11Scancode::F9, WindowsScancode::F9};
|
||||
static const Key F10 {'\u000f', X11Scancode::F10, WindowsScancode::F10};
|
||||
static const Key F11 {'\u000f', X11Scancode::F11, WindowsScancode::F11};
|
||||
static const Key F12 {'\u000f', X11Scancode::F12, WindowsScancode::F12};
|
||||
|
||||
static const Key NumPad1 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad2 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad3 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad4 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad5 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad6 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad7 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad8 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad9 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
static const Key NumPad0 {'\b', X11Scancode::ONE, WindowsScancode::NUMPAD_ONE};
|
||||
|
||||
static const Key Q {'Q', X11Scancode::Q, WindowsScancode::Q};
|
||||
static const Key W {'W', X11Scancode::W, WindowsScancode::W};
|
||||
static const Key E {'E', X11Scancode::E, WindowsScancode::E};
|
||||
static const Key R {'R', X11Scancode::R, WindowsScancode::R};
|
||||
static const Key T {'T', X11Scancode::T, WindowsScancode::T};
|
||||
static const Key Y {'Y', X11Scancode::Y, WindowsScancode::Y};
|
||||
static const Key U {'U', X11Scancode::U, WindowsScancode::U};
|
||||
static const Key I {'I', X11Scancode::I, WindowsScancode::I};
|
||||
static const Key O {'O', X11Scancode::O, WindowsScancode::O};
|
||||
static const Key P {'P', X11Scancode::P, WindowsScancode::P};
|
||||
static const Key A {'A', X11Scancode::A, WindowsScancode::A};
|
||||
static const Key S {'S', X11Scancode::S, WindowsScancode::S};
|
||||
static const Key D {'D', X11Scancode::D, WindowsScancode::D};
|
||||
static const Key F {'F', X11Scancode::F, WindowsScancode::F};
|
||||
static const Key G {'G', X11Scancode::G, WindowsScancode::G};
|
||||
static const Key H {'H', X11Scancode::H, WindowsScancode::H};
|
||||
static const Key J {'J', X11Scancode::J, WindowsScancode::J};
|
||||
static const Key K {'K', X11Scancode::K, WindowsScancode::K};
|
||||
static const Key L {'L', X11Scancode::L, WindowsScancode::L};
|
||||
static const Key Semicolon {';', X11Scancode::SEMICOLON, WindowsScancode::SEMICOLON};
|
||||
static const Key SingeQuote {'\'', X11Scancode::SINGLEQUOTE, WindowsScancode::SEMICOLON};
|
||||
static const Key Enter {'\n', X11Scancode::RETURN, WindowsScancode::ENTER};
|
||||
//static const Key KeyPadEnter {'\n', X11Scancode::KP_RETURN};
|
||||
static const Key Minus {'-', X11Scancode::MINUS, WindowsScancode::MINUS};
|
||||
//static const Key KeyPadMinus {'-', X11Scancode::KP_MINUS};
|
||||
static const Key Equals {'=', X11Scancode::EQUALS, WindowsScancode::EQUALS};
|
||||
static const Key Z {'Z', X11Scancode::Z, WindowsScancode::Z};
|
||||
static const Key X {'X', X11Scancode::X, WindowsScancode::X};
|
||||
static const Key C {'C', X11Scancode::C, WindowsScancode::C};
|
||||
static const Key V {'V', X11Scancode::V, WindowsScancode::V};
|
||||
static const Key B {'B', X11Scancode::B, WindowsScancode::B};
|
||||
static const Key N {'N', X11Scancode::N, WindowsScancode::N};
|
||||
static const Key M {'M', X11Scancode::M, WindowsScancode::M};
|
||||
static const Key Period {'.', X11Scancode::PERIOD, WindowsScancode::PERIOD};
|
||||
static const Key ForwardSlash {'/', X11Scancode::SLASH, WindowsScancode::SLASH};
|
||||
static const Key BackSlash {'\\', X11Scancode::BACKSLASH, WindowsScancode::BACKSLASH};
|
||||
static const Key LShift;
|
||||
static const Key RShift;
|
||||
|
||||
// TODO: Get the right character codes for these
|
||||
static const Key UpArrow {'\u000a', X11Scancode::UP, WindowsScancode::UP_ARROW};
|
||||
static const Key DownArrow {'\u000a', X11Scancode::DOWN, WindowsScancode::DOWN_ARROW};
|
||||
static const Key LeftArrow {'\u000a', X11Scancode::LEFT, WindowsScancode::LEFT_ARROW};
|
||||
static const Key RightArrow {'\u000a', X11Scancode::RIGHT, WindowsScancode::RIGHT_ARROW};
|
||||
}
|
||||
|
||||
class GamepadButton {};
|
||||
class MouseButton {};
|
||||
|
||||
|
||||
class InputService {
|
||||
public:
|
||||
static Vector2 GetLeftJoystick();
|
||||
static Vector2 GetRightJoystick();
|
||||
};
|
||||
|
||||
namespace GamepadButtons {
|
||||
static const GamepadButton X;
|
||||
static const GamepadButton Y;
|
||||
static const GamepadButton A;
|
||||
static const GamepadButton B;
|
||||
}
|
||||
|
||||
|
||||
|
||||
namespace MouseButtons
|
||||
{
|
||||
static const MouseButton Left;
|
||||
static const MouseButton Right;
|
||||
static const MouseButton Middle;
|
||||
static const MouseButton Side1;
|
||||
static const MouseButton Side2;
|
||||
}
|
||||
|
||||
static MouseButton GetMouseButtonFromXButton(unsigned int button)
|
||||
{
|
||||
switch(button)
|
||||
{
|
||||
case Button1: return MouseButtons::Left;
|
||||
case Button2: return MouseButtons::Right;
|
||||
case Button3: return MouseButtons::Middle;
|
||||
case Button4: return MouseButtons::Side1;
|
||||
case Button5: return MouseButtons::Side2;
|
||||
default:
|
||||
{
|
||||
throw std::runtime_error("Undefined XButtonCode: " + button);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static Key GetKeyFromX11Scancode(X11Scancode code)
|
||||
{
|
||||
for (auto& key : Key::GetKeyboard()) {
|
||||
if (key.x11ScanCode == code)
|
||||
return key;
|
||||
}
|
||||
throw std::runtime_error("Unavaliable Scancode: " + std::to_string((int)code));
|
||||
}
|
||||
static Key GetKeyFromWindowsScancode(WindowsScancode code)
|
||||
{
|
||||
for (auto& key : Key::GetKeyboard()) {
|
||||
if (key.winScanCode == code)
|
||||
return key;
|
||||
}
|
||||
throw std::runtime_error("Unavaliable Scancode: " + std::to_string((int)code));
|
||||
}
|
@@ -1,233 +0,0 @@
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
#include <memory>
|
||||
#include <rewindow/types/event.h>
|
||||
#include <functional>
|
||||
#include <map>
|
||||
#include <rewindow/types/key.h>
|
||||
|
||||
|
||||
#if __linux__
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <GL/gl.h>
|
||||
#include <GL/glx.h>
|
||||
#endif
|
||||
|
||||
|
||||
using namespace std::chrono_literals;
|
||||
using precision_clock = std::chrono::high_resolution_clock;
|
||||
using precision_timestamp = precision_clock::time_point;
|
||||
|
||||
enum class RWindowFlags: uint8_t {
|
||||
IN_FOCUS = 0,
|
||||
FULLSCREEN = 1,
|
||||
RESIZABLE = 2,
|
||||
VSYNC = 4
|
||||
};
|
||||
|
||||
enum class RenderingAPI: uint8_t {
|
||||
OPENGL = 0,
|
||||
//Vulkan is unimplemented.
|
||||
VULKAN = 1,
|
||||
};
|
||||
|
||||
enum class CursorStyle
|
||||
{
|
||||
Default,
|
||||
X,
|
||||
Arrow,
|
||||
IBeam,
|
||||
BottomLeftCorner,
|
||||
BottomRightCorner,
|
||||
BottomSide,
|
||||
Dot,
|
||||
DoubleArrow,
|
||||
Exchange,
|
||||
Hand,
|
||||
LeftSide,
|
||||
Plus,
|
||||
RightSide,
|
||||
};
|
||||
|
||||
enum class KeyState { Pressed, Released };
|
||||
|
||||
namespace ReWindow
|
||||
{
|
||||
using LinearAlgebra::Vector2;
|
||||
|
||||
class TimestampedEvent {
|
||||
private:
|
||||
|
||||
public:
|
||||
precision_timestamp Timestamp;
|
||||
TimestampedEvent() : Timestamp(precision_clock::now())
|
||||
{ }
|
||||
};
|
||||
|
||||
class RWindowEvent : public TimestampedEvent {
|
||||
public:
|
||||
RWindowEvent() : TimestampedEvent() { }
|
||||
};
|
||||
const RWindowEvent EmptyRWindowEvent;
|
||||
|
||||
namespace WindowEvents
|
||||
{
|
||||
class KeyboardState {
|
||||
public:
|
||||
std::map<Key, bool> PressedKeys;
|
||||
};
|
||||
|
||||
class GamepadState {
|
||||
public:
|
||||
std::map<GamepadButton, bool> PressedButtons;
|
||||
};
|
||||
|
||||
class InputState {
|
||||
public:
|
||||
KeyboardState Keyboard;
|
||||
GamepadState Gamepad;
|
||||
};
|
||||
|
||||
class KeyboardEvent : public RWindowEvent {
|
||||
public:
|
||||
Key key;
|
||||
KeyState state;
|
||||
KeyboardEvent(Key key, KeyState state) : RWindowEvent(), key(key), state(state) {}
|
||||
};
|
||||
class MouseEvent : public RWindowEvent {};
|
||||
class GamepadEvent : public RWindowEvent {};
|
||||
|
||||
class MouseMoveEvent : public MouseEvent {
|
||||
public:
|
||||
Vector2 Position;
|
||||
Vector2 Delta;
|
||||
MouseMoveEvent(const Vector2 &pos) : MouseEvent(), Position(pos)
|
||||
{}
|
||||
MouseMoveEvent(int x, int y) : MouseEvent(), Position(Vector2(x, y))
|
||||
{}
|
||||
};
|
||||
|
||||
class KeyDownEvent : public KeyboardEvent {
|
||||
public:
|
||||
KeyDownEvent(Key key) : KeyboardEvent(key, KeyState::Pressed) {}
|
||||
};
|
||||
|
||||
class KeyUpEvent : public KeyboardEvent {
|
||||
public:
|
||||
KeyUpEvent(Key key) : KeyboardEvent(key, KeyState::Released) {}
|
||||
};
|
||||
|
||||
|
||||
class MouseButtonDownEvent : public MouseEvent {
|
||||
public:
|
||||
MouseButton Button;
|
||||
};
|
||||
|
||||
class MouseButtonUpEvent : public MouseEvent {
|
||||
public:
|
||||
MouseButton Button;
|
||||
};
|
||||
}
|
||||
|
||||
using namespace WindowEvents;
|
||||
|
||||
class RWindow {
|
||||
|
||||
private:
|
||||
bool flags[4];
|
||||
std::vector<RWindowEvent> eventLog;
|
||||
KeyboardState currentKeyboard; // Current Frame's Keyboard State
|
||||
KeyboardState previousKeyboard; // Previous Frame's Keyboard State
|
||||
bool fullscreenmode = false;
|
||||
public:
|
||||
Event<> focusGained;
|
||||
Event<> focusLost;
|
||||
// TODO: Integrate J3ML
|
||||
Event<MouseMoveEvent&> mouseMoved;
|
||||
Event<MouseButton> mouseBtnPressed;
|
||||
Event<MouseButton> mouseBtnReleased;
|
||||
Event<KeyDownEvent> onKeyboardPress;
|
||||
Event<KeyUpEvent> onKeyboardRelease;
|
||||
|
||||
virtual void OnFocusLost(const RWindowEvent& e) {}
|
||||
virtual void OnFocusGain(const RWindowEvent& e) {}
|
||||
virtual void OnRefresh(float elapsed) {}
|
||||
virtual void OnResizeSuccess() {}
|
||||
virtual bool OnResizeRequest() {}
|
||||
virtual void OnKeyDownEvent(const KeyDownEvent&) {}
|
||||
virtual void OnKeyUpEvent(const KeyUpEvent&) {}
|
||||
virtual void OnMouseMove(const MouseMoveEvent&) {}
|
||||
virtual void OnMouseButtonDown(const MouseButtonDownEvent&) {}
|
||||
virtual void OnMouseButtonUp(const MouseButtonUpEvent&) {}
|
||||
|
||||
|
||||
RWindow();
|
||||
|
||||
// TODO: Must be implemented from scratch as a Motif Window in x11
|
||||
void MessageBox();
|
||||
|
||||
bool isFocused() const;
|
||||
bool isFullscreen() const
|
||||
{
|
||||
return fullscreenmode;
|
||||
}
|
||||
bool isResizable() const;
|
||||
bool isVsyncEnabled() const;
|
||||
|
||||
bool isAlive() const;
|
||||
|
||||
void setMouseVisible(bool visible);
|
||||
void setMouseLocked();
|
||||
void setMouseCenter();
|
||||
void restoreMouseFromLastCenter(); // Feels nicer for users
|
||||
|
||||
|
||||
void setFullscreen(bool fs);
|
||||
void setResizable(bool resizable);
|
||||
void setVsyncEnabled(bool);
|
||||
void setTitle(const std::string& title);
|
||||
|
||||
void fullscreen();
|
||||
void restoreFromFullscreen();
|
||||
|
||||
bool getFlag(RWindowFlags flag) const;
|
||||
void setFlag(RWindowFlags flag, bool state);
|
||||
void init(RenderingAPI api, const char* title, int width, int height, bool vsync);
|
||||
void destroyWindow();
|
||||
void pollEvents();
|
||||
void refresh();
|
||||
|
||||
void setSize(int width, int height);
|
||||
void setSize(const Vector2& size);
|
||||
|
||||
Vector2 getPos() const;
|
||||
Vector2 getSize() const;
|
||||
void setPos(int x, int y);
|
||||
void setPos(const Vector2& pos);
|
||||
|
||||
void raise() const;
|
||||
void lower() const;
|
||||
|
||||
void setCursor(CursorStyle style) const;
|
||||
|
||||
// TODO: Implement
|
||||
// void setCursor(Icon* icon) const;
|
||||
|
||||
static void glSwapBuffers();
|
||||
//Initialize to false because it's not guaranteed that they will be cleared first
|
||||
|
||||
};
|
||||
|
||||
|
||||
class WindowsImplementationRWindow : public RWindow
|
||||
{
|
||||
|
||||
};
|
||||
|
||||
class X11ImplementationRWindow : public RWindow
|
||||
{
|
||||
|
||||
};
|
||||
}
|
168
main.cpp
168
main.cpp
@@ -1,124 +1,78 @@
|
||||
#include <iostream>
|
||||
#include <rewindow/types/window.h>
|
||||
#include <JGL/JGL.h>
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
|
||||
#if __linux__
|
||||
|
||||
void KeyDown(const ReWindow::WindowEvents::KeyDownEvent& e)
|
||||
{
|
||||
std::cout << e.key.CharCode << " pressed" << std::endl;
|
||||
using namespace ReWindow;
|
||||
std::ostream& operator<<(std::ostream& os, const std::pair<int, int>& v) {
|
||||
return os << "{" << v.first << ", " << v.second << "}";
|
||||
}
|
||||
|
||||
Vector2 mouse_pos;
|
||||
class MyWindow : public OpenGLWindow {
|
||||
public:
|
||||
MyWindow(const std::string& title, int w, int h) : OpenGLWindow(title, w, h, 2, 1) {}
|
||||
|
||||
std::ostream& operator<<(std::ostream& os, const Vector2& v)
|
||||
{
|
||||
return os << "{" << v.x << ", " << v.y << "}";
|
||||
}
|
||||
void OnMouseMove(const MouseMoveEvent& e) override {}
|
||||
|
||||
void OnKeyDown(const KeyDownEvent& e) override {
|
||||
if (e.key == Keys::F11)
|
||||
SetFullscreen(!IsFullscreen());
|
||||
}
|
||||
|
||||
class MyWindow : public ReWindow::RWindow
|
||||
{
|
||||
public:
|
||||
void OnMouseMove(const ReWindow::MouseMoveEvent& e) override
|
||||
{
|
||||
std::cout << "Mouse Moved: " << e.Position << " @ " << std::endl;
|
||||
}
|
||||
void OnRefresh(float elapsed) override
|
||||
{
|
||||
JGL::J2D::FillRect2D(JGL::Colors::White, {400.f, 400.f}, {200.f, 200.f});
|
||||
glSwapBuffers();
|
||||
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;
|
||||
|
||||
if (IsMouseButtonDown(MouseButtons::Right))
|
||||
std::cout << "Right Mouse Button" << std::endl;
|
||||
|
||||
if (IsMouseButtonDown(MouseButtons::Middle))
|
||||
std::cout << "Middle Mouse Button" << std::endl;
|
||||
|
||||
if (IsMouseButtonDown(MouseButtons::Mouse4))
|
||||
std::cout << "Mouse4 Mouse Button" << std::endl;
|
||||
|
||||
if (IsMouseButtonDown(MouseButtons::Mouse5))
|
||||
std::cout << "Mouse5 Mouse Button" << std::endl;
|
||||
|
||||
SwapBuffers();
|
||||
}
|
||||
};
|
||||
|
||||
int main() {
|
||||
auto* window = new MyWindow();
|
||||
window->init(RenderingAPI::OPENGL, "name",100,100, true);
|
||||
window->setFlag(RWindowFlags::RESIZABLE, false);
|
||||
auto* window = new MyWindow("Test Window", 600, 480);
|
||||
Logger::Debug(std::format("New window '{}' created. width={} height={}", window->GetTitle(), window->GetWidth(), window->GetHeight()));
|
||||
|
||||
window->onKeyboardPress += KeyDown;
|
||||
window->onKeyboardRelease += [&](ReWindow::WindowEvents::KeyUpEvent e)
|
||||
{
|
||||
if (e.key == Keys::F)
|
||||
window->setFullscreen(!window->isFullscreen());
|
||||
};
|
||||
if (window->Open())
|
||||
Logger::Debug(std::format("Opened window '{}'", window->GetTitle()));
|
||||
|
||||
while (window->isAlive()) {
|
||||
window->pollEvents();
|
||||
window->refresh();
|
||||
}
|
||||
}
|
||||
Logger::Debug("TODO: Cannot set flags until after window is open");
|
||||
window->SetVsyncEnabled(true);
|
||||
window->DisableResizing();
|
||||
window->SetKeyRepeatEnabled(false);
|
||||
|
||||
#endif
|
||||
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())
|
||||
);
|
||||
|
||||
#ifdef WIN32
|
||||
|
||||
#ifndef UNICODE
|
||||
#define UNICODE
|
||||
#endif
|
||||
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; };
|
||||
|
||||
#include <windows.h>
|
||||
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
|
||||
|
||||
int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, PWSTR pCmdLine, int nCmdShow)
|
||||
{
|
||||
auto* window = new RWindow();
|
||||
window->init(RenderingAPI::OPENGL, "mame", 100, 100);
|
||||
window->setFlag
|
||||
|
||||
// Register the window class.
|
||||
const wchar_t CLASS_NAME[] = L"Sample Window Class";
|
||||
|
||||
WNDCLASS wc = { };
|
||||
wc.lpfnWndProc = WindowProc;
|
||||
wc.hInstance = hInstance;
|
||||
wc.lpszClassName = CLASS_NAME;
|
||||
|
||||
RegisterClass(&wc);
|
||||
|
||||
// Create the window.
|
||||
HWND hwnd = CreateWindowEx(
|
||||
0,
|
||||
CLASS_NAME,
|
||||
CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
|
||||
NULL, // Parent Window
|
||||
NULL, // Menu
|
||||
hInstance, // Instancehandle
|
||||
NULL
|
||||
);
|
||||
if (hwnd == NULL)
|
||||
return 0;
|
||||
|
||||
ShowWindow(hwnd, nCmdShow);
|
||||
|
||||
// Run the message loop
|
||||
MSG msg = {};
|
||||
while (GetMessage(&msg, NULL, 0, 0) > 0)
|
||||
{
|
||||
TranslateMessage(&msg);
|
||||
DispatchMessage(&msg);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
|
||||
{
|
||||
switch(uMsg) {
|
||||
case WM_DESTROY:
|
||||
PostQuitMessage(0);
|
||||
return 0;
|
||||
case WM_PAINT:
|
||||
{
|
||||
PAINTSTRUCT ps;
|
||||
HDC hdc = BeginPaint(hwnd, &ps);
|
||||
|
||||
// All painting occurs here, between BeginPaint and EndPaint
|
||||
FillRect(hdc, &ps.rcPaint, (HBRUSH) (COLOR_WINDOW+1));
|
||||
EndPaint(hwnd, &ps);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
return DefWindowProc(hwnd, uMsg, wParam, lParam);
|
||||
}
|
||||
|
||||
#endif
|
||||
while (!window->IsClosing()) {
|
||||
window->ManagedRefresh();
|
||||
if (window->IsFocused())
|
||||
window->SetCursorCenter();
|
||||
}
|
||||
|
||||
delete window;
|
||||
}
|
1
reci/scripts/builddeps.reci
Normal file
1
reci/scripts/builddeps.reci
Normal file
@@ -0,0 +1 @@
|
||||
Main:new("Install build dependencies", "apt-get install -yq libx11-6 libx11-dev libgl-dev libvulkan-dev")
|
28
src/ReWindow/ClipboardService.cpp
Normal file
28
src/ReWindow/ClipboardService.cpp
Normal file
@@ -0,0 +1,28 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include "ReWindow/ClipboardService.h"
|
||||
|
||||
std::vector<std::string> clipboard_history;
|
||||
std::string clipboard;
|
||||
|
||||
|
||||
namespace ClipboardService {
|
||||
std::string GetClipboard(int historyIndex) {
|
||||
|
||||
if (historyIndex > 0) {
|
||||
return clipboard_history[historyIndex - 1];
|
||||
}
|
||||
|
||||
return clipboard;
|
||||
}
|
||||
|
||||
void SetClipboard(const std::string& str, bool overwrites_last) {
|
||||
|
||||
if (!overwrites_last) {
|
||||
clipboard_history.push_back(clipboard);
|
||||
}
|
||||
|
||||
clipboard = str;
|
||||
}
|
||||
|
||||
}
|
17
src/ReWindow/InputService.cpp
Normal file
17
src/ReWindow/InputService.cpp
Normal file
@@ -0,0 +1,17 @@
|
||||
#include "ReWindow/InputService.h"
|
||||
#include "ReWindow/types/Window.h"
|
||||
namespace InputService
|
||||
{
|
||||
bool IsKeyDown(const Key &key) {
|
||||
return RWindow::GetExtant()->IsKeyDown(key);
|
||||
}
|
||||
bool IsMouseButtonDown(const MouseButton &button) {
|
||||
return RWindow::GetExtant()->IsMouseButtonDown(button);
|
||||
}
|
||||
std::pair<int, int> GetMousePosition() {
|
||||
return RWindow::GetExtant()->GetCursorPosition();
|
||||
}
|
||||
std::pair<int, int> GetWindowSize() {
|
||||
return RWindow::GetExtant()->GetSize();
|
||||
}
|
||||
}
|
11
src/ReWindow/Logger.cpp
Normal file
11
src/ReWindow/Logger.cpp
Normal file
@@ -0,0 +1,11 @@
|
||||
#include "ReWindow/Logger.h"
|
||||
|
||||
namespace ReWindow::Logger {
|
||||
using namespace jlog;
|
||||
using namespace Colors;
|
||||
|
||||
GenericLogger Info {"ReWindow", GlobalLogFile, Gray, Gray, Gray, Gray};
|
||||
GenericLogger Fatal {"ReWindow::Fatal", GlobalLogFile, Reds::Crimson, Gray, Gray, Reds::Crimson, White};
|
||||
GenericLogger Debug {"ReWindow::Debug", GlobalLogFile, Purples::Purple, Gray, Gray, Purples::Purple, White};
|
||||
GenericLogger Error {"ReWindow::Error", GlobalLogFile, Red, Gray, Gray, Gray};
|
||||
}
|
@@ -1 +0,0 @@
|
||||
#include "../include/rewindow/types/event.h"
|
@@ -1,314 +0,0 @@
|
||||
#include <iostream>
|
||||
#include <rewindow/types/window.h>
|
||||
#include <rewindow/data/WindowsScancodes.h>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <X11/Xatom.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <thread>
|
||||
|
||||
// TODO: Move all "global" members to be instantiated class members of Window
|
||||
// Doing this would break the intended "Platform-Specific" Encapsulation
|
||||
// So should we do derived platform-specific subclasses?
|
||||
// The intended goal of the ReWindow class is a one-stop object that handles window management on **ALL** platforms
|
||||
|
||||
Window window;
|
||||
XEvent xev;
|
||||
Display* display = XOpenDisplay(nullptr);
|
||||
int defaultScreen = DefaultScreen(display);
|
||||
XVisualInfo* visual;
|
||||
XSetWindowAttributes xSetWindowAttributes;
|
||||
XWindowAttributes windowAttributes;
|
||||
Atom wmDeleteWindow;
|
||||
XSizeHints hints;
|
||||
GLXContext glContext;
|
||||
|
||||
namespace ReWindow {
|
||||
|
||||
RWindow::RWindow() : flags(false,false,false,false) {
|
||||
|
||||
}
|
||||
|
||||
void RWindow::raise() const { XRaiseWindow(display, window); }
|
||||
void RWindow::lower() const { XLowerWindow(display, window); }
|
||||
|
||||
void RWindow::init(RenderingAPI api, const char* title, int width, int height, bool vsync) {
|
||||
if (api == RenderingAPI::OPENGL) {
|
||||
xSetWindowAttributes.border_pixel = BlackPixel(display, defaultScreen);
|
||||
xSetWindowAttributes.background_pixel = BlackPixel(display, defaultScreen);
|
||||
xSetWindowAttributes.override_redirect = True;
|
||||
xSetWindowAttributes.event_mask = ExposureMask;
|
||||
setVsyncEnabled(vsync);
|
||||
GLint glAttributes[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None};
|
||||
visual = glXChooseVisual(display, defaultScreen, glAttributes);
|
||||
glContext = glXCreateContext(display, visual, nullptr, GL_TRUE);
|
||||
vsync = sync;
|
||||
xSetWindowAttributes.colormap = XCreateColormap(display, RootWindow(display, defaultScreen), visual->visual,
|
||||
AllocNone);
|
||||
|
||||
window = XCreateWindow(display, RootWindow(display, defaultScreen), 0, 0, width, height, 0, visual->depth,
|
||||
InputOutput, visual->visual, CWBackPixel | CWColormap | CWBorderPixel | NoEventMask,
|
||||
&xSetWindowAttributes);
|
||||
XSelectInput(display, window,
|
||||
ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask |
|
||||
PointerMotionMask |
|
||||
PointerMotionHintMask | FocusChangeMask | StructureNotifyMask | SubstructureRedirectMask |
|
||||
SubstructureNotifyMask | CWColormap);
|
||||
XMapWindow(display, window);
|
||||
XStoreName(display, window, title);
|
||||
wmDeleteWindow = XInternAtom(display, "WM_DELETE_WINDOW", False);
|
||||
XSetWMProtocols(display, window, &wmDeleteWindow, 1);
|
||||
glXMakeCurrent(display, window, glContext);
|
||||
setVsyncEnabled(vsync);
|
||||
} else {exit(0);}
|
||||
}
|
||||
|
||||
void RWindow::destroyWindow() {
|
||||
XDestroySubwindows(display, window);
|
||||
XAutoRepeatOn(display);
|
||||
XDestroyWindow(display, window);
|
||||
delete this;
|
||||
}
|
||||
|
||||
void RWindow::refresh() {
|
||||
// TODO: Implement refresh time keeping
|
||||
OnRefresh(0.f);
|
||||
|
||||
|
||||
Window root = XDefaultRootWindow(display);
|
||||
Window root_return;
|
||||
Window child_return;
|
||||
int root_x_ret;
|
||||
int root_y_ret;
|
||||
int win_x_ret;
|
||||
int win_y_ret;
|
||||
uint32_t mask_return;
|
||||
unsigned m;
|
||||
bool mouseAvailable = XQueryPointer(display, root, &root_return, &child_return, &root_x_ret, &root_y_ret, &win_x_ret, &win_y_ret, &mask_return);
|
||||
|
||||
if (mouseAvailable)
|
||||
{
|
||||
// TODO: process retrieved mouse coordinates
|
||||
// TODO: normalize coordinates from displaySpace to windowSpace
|
||||
// TODO: fire mouse movement event
|
||||
//std::cout << win_x_ret << ", " << win_y_ret << std::endl;
|
||||
Vector2 mouse_coords_raw = {(float)win_x_ret, (float)win_y_ret};
|
||||
auto window_pos = getPos();
|
||||
Vector2 mouse_coords = mouse_coords_raw - window_pos;
|
||||
|
||||
auto eventData = MouseMoveEvent(mouse_coords);
|
||||
OnMouseMove(eventData);
|
||||
}
|
||||
|
||||
std::this_thread::sleep_for(1ms);
|
||||
}
|
||||
|
||||
bool RWindow::getFlag(RWindowFlags flag) const
|
||||
{
|
||||
if (flags[(int)flag])
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
void RWindow::setFlag(RWindowFlags flag, bool state) {
|
||||
XGetWindowAttributes(display,window,&windowAttributes);
|
||||
flags[(int) flag] = state;
|
||||
//Once you've done this you cannot make it resizable again.
|
||||
if (flag == RWindowFlags::RESIZABLE && !state) {
|
||||
hints.flags = PMinSize | PMaxSize;
|
||||
hints.min_width = hints.max_width = windowAttributes.width;
|
||||
hints.min_height = hints.max_height = windowAttributes.height;
|
||||
XSetWMNormalHints(display, window, &hints);
|
||||
}
|
||||
}
|
||||
|
||||
void RWindow::pollEvents() {
|
||||
while(XPending(display)) {
|
||||
XNextEvent(display, &xev);
|
||||
|
||||
if (xev.type == ClientMessage) {
|
||||
if (xev.xclient.message_type == XInternAtom(display, "WM_PROTOCOLS", False) &&
|
||||
static_cast<Atom>(xev.xclient.data.l[0]) == wmDeleteWindow) {
|
||||
destroyWindow();
|
||||
exit(0);
|
||||
}
|
||||
}
|
||||
|
||||
if (xev.type == FocusIn) {
|
||||
XAutoRepeatOff(display);
|
||||
focusGained.Invoke();
|
||||
RWindowEvent event {};
|
||||
OnFocusGain(event);
|
||||
setFlag(RWindowFlags::IN_FOCUS, true);
|
||||
}
|
||||
|
||||
if (xev.type == FocusOut) {
|
||||
XAutoRepeatOn(display);
|
||||
focusLost.Invoke();
|
||||
RWindowEvent event {};
|
||||
OnFocusLost(event);
|
||||
setFlag(RWindowFlags::IN_FOCUS, false);
|
||||
}
|
||||
|
||||
if (xev.type == KeyRelease) {
|
||||
auto scancode = (X11Scancode) xev.xkey.keycode;
|
||||
auto key = GetKeyFromX11Scancode(scancode);
|
||||
currentKeyboard.PressedKeys[key] = false;
|
||||
KeyUpEvent eventData = KeyUpEvent(key);
|
||||
OnKeyUpEvent(eventData);
|
||||
|
||||
}
|
||||
|
||||
if (xev.type == KeyPress) {
|
||||
auto scancode = (X11Scancode) xev.xkey.keycode;
|
||||
auto key = GetKeyFromX11Scancode(scancode);
|
||||
currentKeyboard.PressedKeys[key] = true;
|
||||
KeyDownEvent eventData = KeyDownEvent(key);
|
||||
OnKeyDownEvent(eventData);
|
||||
eventLog.push_back(eventData);
|
||||
}
|
||||
|
||||
if (xev.type == ButtonRelease) {
|
||||
MouseButton button = GetMouseButtonFromXButton(xev.xbutton.button);
|
||||
auto eventData = MouseButtonUpEvent();
|
||||
eventData.Button = button;
|
||||
|
||||
OnMouseButtonUp(eventData);
|
||||
}
|
||||
|
||||
if (xev.type == ButtonPress)
|
||||
{
|
||||
MouseButton button = GetMouseButtonFromXButton(xev.xbutton.button);
|
||||
auto eventData = MouseButtonDownEvent();
|
||||
eventData.Button = button;
|
||||
|
||||
OnMouseButtonDown(eventData);
|
||||
}
|
||||
|
||||
if (xev.type == Expose) {
|
||||
}
|
||||
|
||||
if (xev.type == MotionNotify)
|
||||
{
|
||||
//auto eventData = MouseMoveEvent(xev.xmotion.x, xev.xmotion.y);
|
||||
|
||||
//OnMouseMove(eventData);
|
||||
}
|
||||
}
|
||||
|
||||
previousKeyboard = currentKeyboard;
|
||||
}
|
||||
|
||||
// Might make the window go off the screen on some window managers.
|
||||
void RWindow::setSize(int width, int height)
|
||||
{
|
||||
if (!getFlag(RWindowFlags::RESIZABLE))
|
||||
return;
|
||||
XResizeWindow(display, window, width, height);
|
||||
}
|
||||
|
||||
void RWindow::setSize(const Vector2& size)
|
||||
{
|
||||
this->setSize(size.x, size.y);
|
||||
}
|
||||
|
||||
// TODO: implement integer vector2/3 types
|
||||
Vector2 RWindow::getSize() const
|
||||
{
|
||||
XGetWindowAttributes(display,window,&windowAttributes);
|
||||
return {(float)windowAttributes.width, (float)windowAttributes.height};
|
||||
}
|
||||
|
||||
// TODO: implement integer vector2/3 types
|
||||
Vector2 RWindow::getPos() const
|
||||
{
|
||||
auto root = XDefaultRootWindow(display);
|
||||
XGetWindowAttributes(display,root,&windowAttributes);
|
||||
return {(float)windowAttributes.x, (float)windowAttributes.y};
|
||||
}
|
||||
|
||||
void RWindow::setPos(int x, int y)
|
||||
{
|
||||
XMoveWindow(display, window, x, y);
|
||||
}
|
||||
|
||||
void RWindow::setPos(const Vector2& pos)
|
||||
{
|
||||
this->setPos(pos.x, pos.y);
|
||||
}
|
||||
|
||||
|
||||
void RWindow::glSwapBuffers() {
|
||||
glXSwapBuffers(display,window);
|
||||
}
|
||||
|
||||
bool RWindow::isResizable() const {
|
||||
return this->getFlag(RWindowFlags::RESIZABLE);
|
||||
}
|
||||
|
||||
bool RWindow::isAlive() const {
|
||||
return true;
|
||||
}
|
||||
|
||||
void RWindow::setResizable(bool resizable) {
|
||||
this->setFlag(RWindowFlags::RESIZABLE, resizable);
|
||||
}
|
||||
|
||||
|
||||
|
||||
void RWindow::setFullscreen(bool fs) {
|
||||
if (fs)
|
||||
fullscreen();
|
||||
else
|
||||
restoreFromFullscreen();
|
||||
}
|
||||
|
||||
void RWindow::fullscreen() {
|
||||
fullscreenmode = true;
|
||||
|
||||
XEvent xev;
|
||||
Atom wm_state = XInternAtom (display, "_NET_WM_STATE", true );
|
||||
Atom wm_fullscreen = XInternAtom (display, "_NET_WM_STATE_FULLSCREEN", true );
|
||||
|
||||
XChangeProperty(display, window, wm_state, XA_ATOM, 32,
|
||||
PropModeReplace, (unsigned char *)&wm_fullscreen, 1);
|
||||
memset(&xev, 0, sizeof(xev));
|
||||
xev.type = ClientMessage;
|
||||
xev.xclient.window = 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] = fullscreenmode;
|
||||
xev.xclient.data.l[2] = 0;
|
||||
XSendEvent(display, DefaultRootWindow(display), False,
|
||||
SubstructureNotifyMask | SubstructureRedirectMask, &xev);
|
||||
}
|
||||
|
||||
void RWindow::restoreFromFullscreen() {
|
||||
fullscreenmode = false;
|
||||
XEvent xev;
|
||||
Atom wm_state = XInternAtom(display, "_NET_WM_STATE", False);
|
||||
Atom fullscreen = XInternAtom(display, "_NET_WM_STATE_FULLSCREEN", False);
|
||||
memset(&xev, 0, sizeof(xev));
|
||||
xev.type = ClientMessage;
|
||||
xev.xclient.window = 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] = fullscreenmode;
|
||||
xev.xclient.data.l[2] = 0;
|
||||
XSendEvent(display, DefaultRootWindow(display), False,
|
||||
SubstructureNotifyMask | SubstructureRedirectMask, &xev);
|
||||
}
|
||||
|
||||
void RWindow::setVsyncEnabled(bool b) {
|
||||
PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = nullptr;
|
||||
glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddressARB((const GLubyte*)"glXSwapIntervalEXT");
|
||||
glXSwapIntervalEXT(display, None, b);
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
235
src/platform/linux/OpenGLWindow.cpp
Normal file
235
src/platform/linux/OpenGLWindow.cpp
Normal file
@@ -0,0 +1,235 @@
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
#include <GL/glx.h>
|
||||
#include <dlfcn.h>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <X11/Xatom.h>
|
||||
|
||||
using namespace ReWindow;
|
||||
class ReWindow::RWindow::Platform {
|
||||
public:
|
||||
Window window;
|
||||
XEvent xev;
|
||||
Display* display;
|
||||
int defaultScreen;
|
||||
XVisualInfo* visual;
|
||||
XSetWindowAttributes xSetWindowAttributes;
|
||||
XWindowAttributes windowAttributes;
|
||||
Atom wmDeleteWindow;
|
||||
Atom windowTypeAtom;
|
||||
Atom windowTypeUtilityAtom;
|
||||
XSizeHints hints;
|
||||
Cursor invisible_cursor = 0;
|
||||
XWMHints* wm_hints = nullptr;
|
||||
GLXContext gl_context;
|
||||
};
|
||||
|
||||
void* glx_lib = nullptr;
|
||||
void* opengl_lib = nullptr;
|
||||
|
||||
namespace OpenGL {
|
||||
bool constructor_success = false;
|
||||
|
||||
typedef const GLubyte *(*glGetString_t)(GLenum name);
|
||||
glGetString_t glGetString = nullptr;
|
||||
|
||||
typedef Bool (*glXMakeCurrent_t)(Display *dpy, GLXDrawable drawable, GLXContext ctx);
|
||||
glXMakeCurrent_t glXMakeCurrent = nullptr;
|
||||
|
||||
typedef void *(*glXGetProcAddressARB_t)(const GLubyte *procname);
|
||||
glXGetProcAddressARB_t glXGetProcAddressARB = nullptr;
|
||||
|
||||
typedef void (*glXSwapBuffers_t)(Display *dpy, GLXDrawable drawable);
|
||||
glXSwapBuffers_t glXSwapBuffers = nullptr;
|
||||
|
||||
typedef GLXContext (*glXCreateContext_t)(Display *dpy, XVisualInfo *vis, GLXContext shareList, Bool direct);
|
||||
glXCreateContext_t glXCreateContext = nullptr;
|
||||
|
||||
typedef GLXFBConfig *(*glXChooseFBConfig_t)(Display *dpy, int screen, const int *attribList, int *nItems);
|
||||
glXChooseFBConfig_t glXChooseFBConfig = nullptr;
|
||||
|
||||
typedef XVisualInfo *(*glXGetVisualFromFBConfig_t)(Display *dpy, GLXFBConfig config);
|
||||
glXGetVisualFromFBConfig_t glXGetVisualFromFBConfig = nullptr;
|
||||
|
||||
typedef XVisualInfo *(*glXChooseVisual_t)(Display *dpy, int screen, const int *attribList);
|
||||
glXChooseVisual_t glXChooseVisual = nullptr;
|
||||
|
||||
typedef GLXContext (*glXCreateContextAttribsARBProc)(Display *, GLXFBConfig, GLXContext, Bool, const int *);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
auto glXSwapIntervalEXT = (PFNGLXSWAPINTERVALEXTPROC) OpenGL::glXGetProcAddressARB((const GLubyte *) "glXSwapIntervalEXT");
|
||||
glXSwapIntervalEXT(platform->display, platform->window, state);
|
||||
}
|
||||
|
||||
std::string OpenGLWindow::GetGraphicsDriverVendor() {
|
||||
return std::string((const char*) OpenGL::glGetString(GL_VENDOR));
|
||||
}
|
||||
|
||||
bool OpenGLWindow::Open() {
|
||||
bool tiling = TilingWindowManager();
|
||||
|
||||
if (!OpenGL::constructor_success)
|
||||
return false;
|
||||
|
||||
platform->display = XOpenDisplay(nullptr);
|
||||
platform->defaultScreen = DefaultScreen(platform->display);
|
||||
|
||||
platform->xSetWindowAttributes.border_pixel = BlackPixel(platform->display, platform->defaultScreen);
|
||||
platform->xSetWindowAttributes.background_pixel = BlackPixel(platform->display, platform->defaultScreen);
|
||||
platform->xSetWindowAttributes.event_mask = ExposureMask;
|
||||
|
||||
if (tiling)
|
||||
platform->xSetWindowAttributes.override_redirect = True;
|
||||
|
||||
auto glXCreateContextAttribsARB = (OpenGL::glXCreateContextAttribsARBProc) OpenGL::glXGetProcAddressARB((const GLubyte*)"glXCreateContextAttribsARB");
|
||||
XVisualInfo* vi = nullptr;
|
||||
|
||||
// Fallback to the old way if you somehow don't have this.
|
||||
if (!glXCreateContextAttribsARB) {
|
||||
GLint glAttributes[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None};
|
||||
platform->visual = OpenGL::glXChooseVisual(platform->display, platform->defaultScreen, glAttributes);
|
||||
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.");
|
||||
|
||||
if (!platform->window)
|
||||
return false;
|
||||
}
|
||||
|
||||
else {
|
||||
static int visual_attributes[]
|
||||
{
|
||||
GLX_X_RENDERABLE, True, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT,
|
||||
GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_X_VISUAL_TYPE, GLX_TRUE_COLOR,
|
||||
GLX_RED_SIZE, 8, GLX_GREEN_SIZE, 8, GLX_BLUE_SIZE, 8,
|
||||
GLX_ALPHA_SIZE, 8, GLX_DEPTH_SIZE, 24, GLX_STENCIL_SIZE, 8,
|
||||
GLX_DOUBLEBUFFER, True, None
|
||||
};
|
||||
|
||||
int fb_count;
|
||||
GLXFBConfig* fb_configurations = OpenGL::glXChooseFBConfig(platform->display, platform->defaultScreen, visual_attributes, &fb_count);
|
||||
if (!fb_configurations || fb_count == 0)
|
||||
return false;
|
||||
|
||||
GLXFBConfig best_fbc = fb_configurations[0];
|
||||
vi = OpenGL::glXGetVisualFromFBConfig(platform->display, best_fbc);
|
||||
|
||||
if (!vi)
|
||||
return false;
|
||||
|
||||
platform->xSetWindowAttributes.colormap = XCreateColormap(platform->display, RootWindow(platform->display, vi->screen), vi->visual, AllocNone);
|
||||
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);
|
||||
|
||||
int context_attributes[] { GLX_CONTEXT_MAJOR_VERSION_ARB, gl_major, GLX_CONTEXT_MINOR_VERSION_ARB, gl_minor, None };
|
||||
platform->gl_context = glXCreateContextAttribsARB(platform->display, best_fbc, nullptr, True, context_attributes);
|
||||
XFree(fb_configurations);
|
||||
Logger::Debug("Created OpenGL Context with glXCreateContextAttribsARB");
|
||||
}
|
||||
|
||||
if (!platform->gl_context)
|
||||
return false;
|
||||
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 | VisibilityChangeMask | CWColormap );
|
||||
|
||||
XMapWindow(platform->display, platform->window);
|
||||
XStoreName(platform->display, platform->window, title.c_str());
|
||||
|
||||
|
||||
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);
|
||||
|
||||
open = true;
|
||||
processOnOpen();
|
||||
return true;
|
||||
}
|
||||
|
||||
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) {
|
||||
|
||||
// Try this first.
|
||||
glx_lib = dlopen("libGLX.so", RTLD_NOLOAD);
|
||||
opengl_lib = dlopen("libOpenGL.so", RTLD_NOLOAD);
|
||||
|
||||
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;
|
||||
|
||||
if (!glx_lib)
|
||||
Logger::Error("libGLX.so couldn't be found in your LD_LIBRARY_PATH."),
|
||||
OpenGL::constructor_success = false;
|
||||
|
||||
OpenGL::glGetString = (OpenGL::glGetString_t) dlsym(opengl_lib, "glGetString");
|
||||
OpenGL::glXMakeCurrent = (OpenGL::glXMakeCurrent_t) dlsym(glx_lib, "glXMakeCurrent");
|
||||
OpenGL::glXGetProcAddressARB = (OpenGL::glXGetProcAddressARB_t) dlsym(glx_lib, "glXGetProcAddressARB");
|
||||
OpenGL::glXSwapBuffers = (OpenGL::glXSwapBuffers_t) dlsym(glx_lib, "glXSwapBuffers");
|
||||
OpenGL::glXCreateContext = (OpenGL::glXCreateContext_t) dlsym(glx_lib, "glXCreateContext");
|
||||
OpenGL::glXChooseFBConfig = (OpenGL::glXChooseFBConfig_t) dlsym(glx_lib, "glXChooseFBConfig");
|
||||
OpenGL::glXGetVisualFromFBConfig = (OpenGL::glXGetVisualFromFBConfig_t) dlsym(glx_lib, "glXGetVisualFromFBConfig");
|
||||
OpenGL::glXChooseVisual = (OpenGL::glXChooseVisual_t) dlsym(glx_lib, "glXChooseVisual");
|
||||
OpenGL::constructor_success = true;
|
||||
}
|
||||
|
||||
bool OpenGLWindow::SoftwareRendered() {
|
||||
std::string renderer((const char*) OpenGL::glGetString(GL_RENDERER));
|
||||
|
||||
if (renderer.find("llvmpipe"))
|
||||
return true;
|
||||
if (renderer.find("softpipe"))
|
||||
return true;
|
||||
return false;
|
||||
}
|
255
src/platform/linux/VulkanWindow.cpp
Normal file
255
src/platform/linux/VulkanWindow.cpp
Normal file
@@ -0,0 +1,255 @@
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
#include <dlfcn.h>
|
||||
#include <set>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <X11/Xatom.h>
|
||||
#include <vulkan/vulkan.h>
|
||||
#include <vulkan/vulkan_xlib.h>
|
||||
|
||||
using namespace ReWindow;
|
||||
class ReWindow::RWindow::Platform {
|
||||
public:
|
||||
Window window;
|
||||
XEvent xev;
|
||||
Display* display;
|
||||
int defaultScreen;
|
||||
XVisualInfo* visual;
|
||||
XSetWindowAttributes xSetWindowAttributes;
|
||||
XWindowAttributes windowAttributes;
|
||||
Atom wmDeleteWindow;
|
||||
Atom windowTypeAtom;
|
||||
Atom windowTypeUtilityAtom;
|
||||
XSizeHints hints;
|
||||
Cursor invisible_cursor = 0;
|
||||
XWMHints* wm_hints = nullptr;
|
||||
};
|
||||
|
||||
namespace Vulkan {
|
||||
bool constructor_success = false;
|
||||
PFN_vkGetInstanceProcAddr vkGetInstanceProcAddr = nullptr;
|
||||
PFN_vkCreateInstance vkCreateInstance = nullptr;
|
||||
PFN_vkGetPhysicalDeviceProperties vkGetPhysicalDeviceProperties = nullptr;
|
||||
PFN_vkEnumeratePhysicalDevices vkEnumeratePhysicalDevices = nullptr;
|
||||
PFN_vkGetPhysicalDeviceQueueFamilyProperties vkGetPhysicalDeviceQueueFamilyProperties = nullptr;
|
||||
PFN_vkGetDeviceQueue vkGetDeviceQueue = nullptr;
|
||||
PFN_vkCreateDevice vkCreateDevice = nullptr;
|
||||
PFN_vkCreateXlibSurfaceKHR vkCreateXlibSurfaceKHR = nullptr;
|
||||
PFN_vkGetPhysicalDeviceSurfaceSupportKHR vkGetPhysicalDeviceSurfaceSupportKHR = nullptr;
|
||||
}
|
||||
|
||||
void* vulkan_lib = nullptr;
|
||||
VkInstance vulkan_context = nullptr;
|
||||
VkApplicationInfo vulkan_application_info{};
|
||||
VkSurfaceKHR vulkan_surface = nullptr;
|
||||
VkDevice vulkan_logical_device = nullptr;
|
||||
VkQueue vulkan_graphics_queue = nullptr;
|
||||
VkQueue vulkan_present_queue = nullptr;
|
||||
|
||||
// Necessary because some functions aren't available until you have a context (Vulkan is weird).
|
||||
void LoadVulkanInstancedFunctions(VkInstance vulkan_ctx) {
|
||||
Vulkan::vkGetPhysicalDeviceProperties = (PFN_vkGetPhysicalDeviceProperties) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkGetPhysicalDeviceProperties");
|
||||
Vulkan::vkEnumeratePhysicalDevices = (PFN_vkEnumeratePhysicalDevices) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkEnumeratePhysicalDevices");
|
||||
Vulkan::vkGetPhysicalDeviceQueueFamilyProperties = (PFN_vkGetPhysicalDeviceQueueFamilyProperties) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkGetPhysicalDeviceQueueFamilyProperties");
|
||||
Vulkan::vkGetDeviceQueue = (PFN_vkGetDeviceQueue) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkGetDeviceQueue");
|
||||
Vulkan::vkCreateDevice = (PFN_vkCreateDevice) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkCreateDevice");
|
||||
Vulkan::vkCreateXlibSurfaceKHR = (PFN_vkCreateXlibSurfaceKHR) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkCreateXlibSurfaceKHR");
|
||||
Vulkan::vkGetPhysicalDeviceSurfaceSupportKHR = (PFN_vkGetPhysicalDeviceSurfaceSupportKHR) Vulkan::vkGetInstanceProcAddr(vulkan_ctx, "vkGetPhysicalDeviceSurfaceSupportKHR");
|
||||
}
|
||||
|
||||
bool VulkanWindow::Open() {
|
||||
if (!Vulkan::constructor_success)
|
||||
return false;
|
||||
|
||||
platform->display = XOpenDisplay(nullptr);
|
||||
platform->defaultScreen = DefaultScreen(platform->display);
|
||||
|
||||
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;
|
||||
|
||||
vulkan_application_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
|
||||
vulkan_application_info.pApplicationName = title.c_str();
|
||||
vulkan_application_info.applicationVersion = VK_MAKE_VERSION(1, 0, 0);
|
||||
vulkan_application_info.pEngineName = "";
|
||||
vulkan_application_info.engineVersion = VK_MAKE_VERSION(1, 0, 0);
|
||||
|
||||
vulkan_application_info.apiVersion = VK_API_VERSION_1_0;
|
||||
|
||||
VkInstanceCreateInfo create_info{};
|
||||
create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
|
||||
create_info.pApplicationInfo = &vulkan_application_info;
|
||||
|
||||
const char* extensions[] = { "VK_KHR_surface", "VK_KHR_xlib_surface" };
|
||||
create_info.enabledExtensionCount = 2;
|
||||
create_info.ppEnabledExtensionNames = extensions;
|
||||
|
||||
if (Vulkan::vkCreateInstance(&create_info, nullptr, &vulkan_context) != VK_SUCCESS) {
|
||||
Logger::Error("Couldn't create Vulkan instance.");
|
||||
return false;
|
||||
}
|
||||
|
||||
LoadVulkanInstancedFunctions(vulkan_context);
|
||||
XVisualInfo visual_info_t{};
|
||||
visual_info_t.screen = platform->defaultScreen;
|
||||
int visual_count;
|
||||
XVisualInfo* vi = XGetVisualInfo(platform->display, VisualScreenMask, &visual_info_t, &visual_count);
|
||||
|
||||
if (!vi)
|
||||
return false;
|
||||
|
||||
Colormap colormap = XCreateColormap(platform->display, RootWindow(platform->display, vi->screen), vi->visual, AllocNone);
|
||||
platform->xSetWindowAttributes.colormap = colormap;
|
||||
|
||||
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);
|
||||
|
||||
if (!platform->window) {
|
||||
Logger::Error("Failed to create X11 window for Vulkan.");
|
||||
return false;
|
||||
}
|
||||
|
||||
XFree(vi);
|
||||
|
||||
VkXlibSurfaceCreateInfoKHR surface_create_info{};
|
||||
surface_create_info.sType = VK_STRUCTURE_TYPE_XLIB_SURFACE_CREATE_INFO_KHR;
|
||||
surface_create_info.dpy = platform->display;
|
||||
surface_create_info.window = platform-> window;
|
||||
|
||||
if (Vulkan::vkCreateXlibSurfaceKHR(vulkan_context, &surface_create_info, nullptr, &vulkan_surface) != VK_SUCCESS) {
|
||||
Logger::Error("Failed to create Vulkan X11 surface.");
|
||||
return false;
|
||||
}
|
||||
|
||||
unsigned int device_count = 0;
|
||||
Vulkan::vkEnumeratePhysicalDevices(vulkan_context, &device_count, nullptr);
|
||||
|
||||
if (device_count == 0) {
|
||||
Logger::Error("Opening the window as Vulkan but there isn't a Vulkan compatible graphics card?");
|
||||
return false;
|
||||
}
|
||||
|
||||
std::vector<VkPhysicalDevice> vulkan_devices(device_count);
|
||||
Vulkan::vkEnumeratePhysicalDevices(vulkan_context, &device_count, vulkan_devices.data());
|
||||
|
||||
VkPhysicalDevice selected_device = VK_NULL_HANDLE;
|
||||
|
||||
int graphics_family = -1;
|
||||
int present_family = -1;
|
||||
for (const auto& d : vulkan_devices) {
|
||||
unsigned int queue_family_count = 0;
|
||||
Vulkan::vkGetPhysicalDeviceQueueFamilyProperties(d, &queue_family_count, nullptr);
|
||||
|
||||
std::vector<VkQueueFamilyProperties> queue_families(queue_family_count);
|
||||
Vulkan::vkGetPhysicalDeviceQueueFamilyProperties(d, &queue_family_count, queue_families.data());
|
||||
|
||||
bool has_graphics = false;
|
||||
bool has_present = false;
|
||||
for (unsigned int i = 0; i < queue_family_count; i++) {
|
||||
if (queue_families[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) { has_graphics = true; graphics_family = i; }
|
||||
|
||||
VkBool32 present_support = false;
|
||||
Vulkan::vkGetPhysicalDeviceSurfaceSupportKHR(d, i, vulkan_surface, &present_support);
|
||||
|
||||
if (present_support) { has_present = true; present_family = i; }
|
||||
|
||||
if (has_graphics && has_present) { selected_device = d; break; }
|
||||
}
|
||||
if (selected_device != VK_NULL_HANDLE)
|
||||
break;
|
||||
}
|
||||
|
||||
if (selected_device == VK_NULL_HANDLE) {
|
||||
Logger::Error("There isn't a Vulkan device which supports rendering & presenting?");
|
||||
return false;
|
||||
}
|
||||
|
||||
VkPhysicalDeviceProperties device_properties;
|
||||
Vulkan::vkGetPhysicalDeviceProperties(selected_device, &device_properties);
|
||||
Logger::Debug("Vulkan continuing with selected device: " + std::string(device_properties.deviceName));
|
||||
|
||||
float queue_prio = 1.0f;
|
||||
std::vector<VkDeviceQueueCreateInfo> queue_create_info;
|
||||
std::set<unsigned int> unique_queue_families = { (unsigned int) graphics_family, (unsigned int) present_family};
|
||||
|
||||
for (unsigned int qf : unique_queue_families) {
|
||||
VkDeviceQueueCreateInfo vdqci{};
|
||||
vdqci.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
|
||||
vdqci.queueFamilyIndex = qf;
|
||||
vdqci.queueCount = 1;
|
||||
vdqci.pQueuePriorities = &queue_prio;
|
||||
queue_create_info.push_back(vdqci);
|
||||
}
|
||||
|
||||
// TODO allow the user to specify this.
|
||||
VkPhysicalDeviceFeatures enabled_features{};
|
||||
|
||||
VkDeviceCreateInfo device_create_info{};
|
||||
device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
|
||||
device_create_info.queueCreateInfoCount = queue_create_info.size();
|
||||
device_create_info.pQueueCreateInfos = queue_create_info.data();
|
||||
device_create_info.pEnabledFeatures = &enabled_features;
|
||||
|
||||
// TODO allow the user to specify this.
|
||||
std::vector<const char*> device_ext = {VK_KHR_SWAPCHAIN_EXTENSION_NAME};
|
||||
device_create_info.enabledExtensionCount = device_ext.size();
|
||||
device_create_info.ppEnabledExtensionNames = device_ext.data();
|
||||
|
||||
if (Vulkan::vkCreateDevice(selected_device, &device_create_info, nullptr, &vulkan_logical_device) != VK_SUCCESS) {
|
||||
Logger::Error("Couldn't create the Vulkan logical device.");
|
||||
return false;
|
||||
}
|
||||
|
||||
Vulkan::vkGetDeviceQueue(vulkan_logical_device, graphics_family, 0, &vulkan_graphics_queue);
|
||||
Vulkan::vkGetDeviceQueue(vulkan_logical_device, present_family, 0, &vulkan_present_queue);
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
XSelectInput(platform->display, platform->window, ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask |
|
||||
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);
|
||||
|
||||
platform->wmDeleteWindow = XInternAtom(platform->display, "WM_DELETE_WINDOW", False);
|
||||
XSetWMProtocols(platform->display, platform->window, &platform->wmDeleteWindow, 1);
|
||||
|
||||
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
|
||||
|
||||
open = true;
|
||||
processOnOpen();
|
||||
return true;
|
||||
}
|
||||
|
||||
void VulkanWindow::SwapBuffers() {
|
||||
|
||||
}
|
||||
|
||||
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) {
|
||||
vulkan_lib = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!vulkan_lib)
|
||||
vulkan_lib = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL);
|
||||
if (!vulkan_lib)
|
||||
Logger::Debug("libvulkan.so couldn't be found in your LD_LIBRARY_PATH."),
|
||||
Vulkan::constructor_success = false;
|
||||
|
||||
Vulkan::vkGetInstanceProcAddr = (PFN_vkGetInstanceProcAddr) dlsym(vulkan_lib,"vkGetInstanceProcAddr");
|
||||
Vulkan::vkCreateInstance = (PFN_vkCreateInstance) Vulkan::vkGetInstanceProcAddr(NULL, "vkCreateInstance");
|
||||
Vulkan::constructor_success = true;
|
||||
}
|
532
src/platform/linux/Window.cpp
Normal file
532
src/platform/linux/Window.cpp
Normal file
@@ -0,0 +1,532 @@
|
||||
#include <cstring>
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/types/Cursors.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include <X11/Xatom.h>
|
||||
|
||||
class ReWindow::RWindow::Platform {
|
||||
public:
|
||||
Window window;
|
||||
XEvent xev;
|
||||
Display* display;
|
||||
int defaultScreen;
|
||||
XVisualInfo* visual;
|
||||
XSetWindowAttributes xSetWindowAttributes;
|
||||
XWindowAttributes windowAttributes;
|
||||
Atom wmDeleteWindow;
|
||||
Atom windowTypeAtom;
|
||||
Atom windowTypeUtilityAtom;
|
||||
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;
|
||||
|
||||
if (platform->wm_hints == nullptr)
|
||||
platform->wm_hints = XAllocWMHints();
|
||||
|
||||
platform->wm_hints->flags = XUrgencyHint;
|
||||
XSetWMHints(platform->display, platform->window, platform->wm_hints);
|
||||
}
|
||||
|
||||
RWindow::RWindow() {
|
||||
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);
|
||||
XRaiseWindow(platform->display, platform->window);
|
||||
}
|
||||
|
||||
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);
|
||||
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.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 | StructureNotifyMask);
|
||||
|
||||
// No resizing.
|
||||
XSizeHints hints;
|
||||
hints.flags = PMinSize | PMaxSize;
|
||||
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));
|
||||
|
||||
XEvent event;
|
||||
while (true) {
|
||||
XNextEvent(platform->display, &event);
|
||||
|
||||
if (event.type == Expose) {
|
||||
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 == 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);
|
||||
XFreeGC(platform->display, gc);
|
||||
XDestroyWindow(platform->display, window);
|
||||
}
|
||||
void RWindow::Lower()
|
||||
{
|
||||
Logger::Debug(std::format("Lowering window '{}'", this->title));
|
||||
XLowerWindow(platform->display, platform->window);
|
||||
}
|
||||
|
||||
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);
|
||||
|
||||
Logger::Debug(std::format("Destroyed window '{}'", this->title));
|
||||
XDestroyWindow(platform->display, platform->window);
|
||||
|
||||
XCloseDisplay(platform->display);
|
||||
delete platform;
|
||||
}
|
||||
|
||||
void RWindow::SetCursorVisible(bool cursor_enable) {
|
||||
cursor_visible = cursor_enable;
|
||||
if (platform->invisible_cursor == 0) {
|
||||
Pixmap blank_pixmap = XCreatePixmap(platform->display, platform->window, 1, 1, 1);
|
||||
XColor dummy; dummy.pixel = 0; dummy.red = 0; dummy.flags = 0;
|
||||
platform->invisible_cursor = XCreatePixmapCursor(platform->display, blank_pixmap, blank_pixmap, &dummy, &dummy, 0, 0);
|
||||
XFreePixmap(platform->display, blank_pixmap);
|
||||
}
|
||||
|
||||
if (!cursor_enable)
|
||||
XDefineCursor(platform->display, platform->window, platform->invisible_cursor);
|
||||
|
||||
if (cursor_enable)
|
||||
XUndefineCursor(platform->display, platform->window);
|
||||
}
|
||||
|
||||
void RWindow::DisableResizing() {
|
||||
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
|
||||
|
||||
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() {
|
||||
while(XPending(platform->display)) {
|
||||
XNextEvent(platform->display, &platform->xev);
|
||||
|
||||
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) {
|
||||
Close();
|
||||
}
|
||||
|
||||
if (platform->xev.type == FocusIn) {
|
||||
Logger::Debug(std::format("Event'{}'", "FocusIn"));
|
||||
|
||||
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;
|
||||
XSetWMHints(platform->display, platform->window, platform->wm_hints);
|
||||
XFree(platform->wm_hints);
|
||||
}
|
||||
if (!cursor_visible)
|
||||
XDefineCursor(platform->display, platform->window, platform->invisible_cursor);
|
||||
|
||||
// Get the position of the renderable area relative to the rest of the window.
|
||||
XGetWindowAttributes(platform->display, platform->window, &platform->windowAttributes);
|
||||
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);
|
||||
|
||||
processFocusOut();
|
||||
focused = false;
|
||||
}
|
||||
|
||||
if (platform->xev.type == KeyRelease) {
|
||||
Logger::Debug(std::format("Event '{}'", "KeyRelease"));
|
||||
auto scancode = (X11Scancode) platform->xev.xkey.keycode;
|
||||
auto key = GetKeyFromX11Scancode(scancode);
|
||||
processKeyRelease(key);
|
||||
}
|
||||
|
||||
if (platform->xev.type == KeyPress) {
|
||||
Logger::Debug(std::format("Event '{}'", "KeyPress"));
|
||||
auto scancode = (X11Scancode) platform->xev.xkey.keycode;
|
||||
auto key = GetKeyFromX11Scancode(scancode);
|
||||
processKeyPress(key);
|
||||
}
|
||||
|
||||
if (platform->xev.type == ButtonRelease) {
|
||||
|
||||
// Mouse Wheel fires both the ButtonPress and ButtonRelease instantaneously.
|
||||
// Therefore, we handle it as a specific MouseWheel event rather than a MouseButton event,
|
||||
// and only call on ButtonPress, otherwise it will appear to duplicate the mouse wheel scroll.
|
||||
if (platform->xev.xbutton.button != 4 && platform->xev.xbutton.button != 5) {
|
||||
MouseButton button = GetMouseButtonFromXButton(platform->xev.xbutton.button);
|
||||
Logger::Debug(std::format("Event '{}'", "ButtonRelease"));
|
||||
processMouseRelease(button);
|
||||
}
|
||||
}
|
||||
|
||||
if (platform->xev.type == ButtonPress) {
|
||||
|
||||
// Mouse Wheel fires both the ButtonPress and ButtonRelease instantaneously.
|
||||
// Therefore, we handle it as a specific MouseWheel event rather than a MouseButton event,
|
||||
// and only call on ButtonPress, otherwise it will appear to duplicate the mouse wheel scroll.
|
||||
if (platform->xev.xbutton.button == 4) {
|
||||
processMouseWheel(-1);
|
||||
} else if (platform->xev.xbutton.button == 5) {
|
||||
processMouseWheel(1);
|
||||
} else {
|
||||
MouseButton button = GetMouseButtonFromXButton(platform->xev.xbutton.button);
|
||||
|
||||
Logger::Debug(std::format("Event: MouseButtonPress {}", button.Mnemonic));
|
||||
|
||||
processMousePress(button);
|
||||
}
|
||||
}
|
||||
|
||||
if (platform->xev.type == Expose) {
|
||||
Logger::Debug(std::format("Event '{}'", "Expose"));
|
||||
}
|
||||
|
||||
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) {
|
||||
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};
|
||||
|
||||
OnResizeRequest(eventData);
|
||||
OnResizeRequestEvent(eventData);
|
||||
}
|
||||
//Window Moved.
|
||||
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;
|
||||
}
|
||||
|
||||
|
||||
// Might make the window go off the screen on some window managers.
|
||||
void RWindow::SetSize(int newWidth, int newHeight) {
|
||||
if (!resizable)
|
||||
return;
|
||||
|
||||
this->width = newWidth;
|
||||
this->height = newHeight;
|
||||
XResizeWindow(platform->display, platform->window, newWidth, newHeight);
|
||||
XFlush(platform->display);
|
||||
Logger::Info(std::format("Set size for '{}' to {} x {}", this->title, newWidth, newHeight));
|
||||
}
|
||||
|
||||
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;
|
||||
uint32_t mask_return;
|
||||
|
||||
// This seems to be relative to the top left corner of the renderable area.
|
||||
bool mouseAvailable = XQueryPointer(platform->display, platform->window, &root_return, &child_return, &root_x_ret, &root_y_ret, &win_x_ret, &win_y_ret, &mask_return);
|
||||
|
||||
if (mouseAvailable) {
|
||||
// TODO: normalize coordinates from platform->displaySpace to windowSpace
|
||||
// TODO: fire mouse movement event
|
||||
std::pair<int, int> m_coords = { win_x_ret, win_y_ret };
|
||||
return m_coords;
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
bool RWindow::IsVisible() const {
|
||||
return platform->window_visible;
|
||||
}
|
||||
|
||||
// TODO: implement integer std::pair<int, int>/3 types
|
||||
std::pair<int, int> RWindow::GetPosition() const {
|
||||
return platform->position;
|
||||
}
|
||||
|
||||
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::SetPosition(const std::pair<int, int>& pos) {
|
||||
SetPosition(pos.first, pos.second);
|
||||
}
|
||||
|
||||
void RWindow::Fullscreen() {
|
||||
platform->size_before_fullscreen = GetSize();
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
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;
|
||||
xev.xclient.data.l[1] = wm_fullscreen;
|
||||
xev.xclient.data.l[2] = 0;
|
||||
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() {
|
||||
Atom wm_state = XInternAtom(platform->display, "_NET_WM_STATE", False);
|
||||
Atom fullscreen = XInternAtom(platform->display, "_NET_WM_STATE_FULLSCREEN", False);
|
||||
|
||||
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;
|
||||
xev.xclient.data.l[1] = fullscreen;
|
||||
xev.xclient.data.l[2] = 0;
|
||||
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));
|
||||
}
|
||||
|
||||
void RWindow::SetCursorStyle(CursorStyle style) const {
|
||||
auto x11_cursor_resolved_enum = (unsigned int) style.X11Cursor;
|
||||
Cursor c = XCreateFontCursor(platform->display, x11_cursor_resolved_enum);
|
||||
XDefineCursor(platform->display, platform->window, c);
|
||||
}
|
||||
|
||||
void RWindow::SetTitle(const std::string& title) {
|
||||
this->title = title;
|
||||
XStoreName(platform->display, platform->window, title.c_str());
|
||||
}
|
||||
|
252
src/platform/shared/Window.cpp
Normal file
252
src/platform/shared/Window.cpp
Normal file
@@ -0,0 +1,252 @@
|
||||
#include <ReWindow/types/Window.h>
|
||||
#include <ReWindow/InputService.h>
|
||||
#include <ReWindow/Logger.h>
|
||||
|
||||
using namespace ReWindow;
|
||||
|
||||
RWindow::~RWindow() {
|
||||
if (open)
|
||||
DestroyOSWindowHandle();
|
||||
}
|
||||
|
||||
std::pair<int, int> RWindow::GetCursorPosition() const {
|
||||
return currentMouse.Position;
|
||||
}
|
||||
|
||||
bool RWindow::IsAlive() const {
|
||||
return (!closing) && open;
|
||||
}
|
||||
|
||||
void RWindow::SetFullscreen(bool fs) {
|
||||
if (fs)
|
||||
Fullscreen();
|
||||
else
|
||||
RestoreFromFullscreen();
|
||||
}
|
||||
|
||||
#pragma region Event Processors Implementation
|
||||
void RWindow::processFocusIn() {
|
||||
RWindowEvent event {};
|
||||
OnFocusGain(event);
|
||||
OnFocusGainEvent(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processFocusOut() {
|
||||
RWindowEvent event {};
|
||||
OnFocusLost(event);
|
||||
OnFocusLostEvent(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processMousePress(const MouseButton& btn) {
|
||||
currentMouse.Set(btn, true);
|
||||
auto event = MouseButtonDownEvent(btn);
|
||||
OnMouseButtonDown(event);
|
||||
OnMouseButtonDownEvent(event);
|
||||
InputService::OnMouseButtonEvent(MouseButtonEvent(btn, true));
|
||||
InputService::OnMouseDown(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
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);
|
||||
OnMouseMoveEvent(event);
|
||||
InputService::OnMouseMove(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processMouseRelease(const MouseButton& btn) {
|
||||
currentMouse.Set(btn, false);
|
||||
auto event = MouseButtonUpEvent(btn);
|
||||
OnMouseButtonUp(event);
|
||||
OnMouseButtonUpEvent(event);
|
||||
InputService::OnMouseButtonEvent(MouseButtonEvent(btn, false));
|
||||
InputService::OnMouseUp(event);
|
||||
LogEvent(event);
|
||||
|
||||
}
|
||||
|
||||
void RWindow::processKeyRelease(Key key) {
|
||||
currentKeyboard.PressedKeys[key] = false;
|
||||
auto event = KeyUpEvent(key);
|
||||
OnKeyUp(event);
|
||||
OnKeyUpEvent(event);
|
||||
InputService::OnKeyboardEvent(KeyboardEvent(key, KeyState::Released));
|
||||
InputService::OnKeyEvent(KeyboardEvent(key, KeyState::Released));
|
||||
InputService::OnKeyUp(event);
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processKeyPress(Key key) {
|
||||
currentKeyboard.PressedKeys[key] = true;
|
||||
auto event = KeyDownEvent(key);
|
||||
OnKeyDown(event);
|
||||
OnKeyDownEvent(event);
|
||||
InputService::OnKeyDown(event);
|
||||
InputService::OnKeyboardEvent(KeyboardEvent(key, KeyState::Pressed));
|
||||
InputService::OnKeyEvent(KeyboardEvent(key, KeyState::Pressed));
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processOnClose() {
|
||||
auto event = RWindowEvent();
|
||||
OnClosing();
|
||||
OnClosingEvent();
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
void RWindow::processOnOpen() {
|
||||
auto event = RWindowEvent();
|
||||
OnOpen();
|
||||
OnOpenEvent();
|
||||
LogEvent(event);
|
||||
}
|
||||
|
||||
#pragma endregion
|
||||
|
||||
std::string RWindow::GetTitle() const { return this->title; }
|
||||
|
||||
int RWindow::GetWidth() const { return this->width; }
|
||||
|
||||
int RWindow::GetHeight() const { return this->height; }
|
||||
|
||||
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; }
|
||||
|
||||
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 {
|
||||
if (currentKeyboard.PressedKeys.contains(key))
|
||||
return currentKeyboard.PressedKeys.at(key);
|
||||
|
||||
return false; // NOTE: Key may not be mapped!!
|
||||
}
|
||||
|
||||
bool RWindow::IsMouseButtonDown(const MouseButton& button) const {
|
||||
// TODO: Implement MouseButton map
|
||||
return currentMouse.IsDown(button);
|
||||
}
|
||||
|
||||
|
||||
void RWindow::ManagedRefresh() {
|
||||
auto begin = GetTimestamp();
|
||||
Refresh();
|
||||
auto end = GetTimestamp();
|
||||
|
||||
float dt = ComputeElapsedFrameTimeSeconds(begin, end);
|
||||
|
||||
UpdateFrameTiming(dt);
|
||||
}
|
||||
|
||||
void RWindow::Refresh() {
|
||||
PollEvents();
|
||||
OnRefresh(delta_time);
|
||||
|
||||
// Only call once and cache the result.
|
||||
currentMouse.Position = GetAccurateCursorCoordinates();
|
||||
|
||||
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();
|
||||
float frame_time_s = frame_time_us / (1000.f * 1000.f);
|
||||
return frame_time_s;
|
||||
}
|
||||
|
||||
std::chrono::steady_clock::time_point RWindow::GetTimestamp() {
|
||||
return std::chrono::steady_clock::now();
|
||||
}
|
||||
|
||||
void RWindow::UpdateFrameTiming(float frame_time) {
|
||||
delta_time = frame_time;
|
||||
refresh_rate = 1.f / delta_time;
|
||||
refresh_rate_prev_5 = refresh_rate_prev_4;
|
||||
refresh_rate_prev_4 = refresh_rate_prev_3;
|
||||
refresh_rate_prev_3 = refresh_rate_prev_2;
|
||||
refresh_rate_prev_2 = refresh_rate_prev_1;
|
||||
refresh_rate_prev_1 = refresh_rate;
|
||||
avg_refresh_rate = (refresh_rate_prev_1 + refresh_rate_prev_2 + refresh_rate_prev_3 + refresh_rate_prev_4 + refresh_rate_prev_5) / 5.f;
|
||||
refresh_count++;
|
||||
}
|
||||
|
||||
|
||||
void RWindow::processMouseWheel(int scrolls) {
|
||||
currentMouse.Wheel += scrolls;
|
||||
auto ev = MouseWheelEvent(scrolls);
|
||||
OnMouseWheel(ev);
|
||||
OnMouseWheelEvent(ev);
|
||||
|
||||
previousMouse.Wheel = currentMouse.Wheel;
|
||||
}
|
||||
|
||||
void RWindow::Close() {
|
||||
closing = true;
|
||||
processOnClose();
|
||||
}
|
||||
|
||||
void RWindow::ForceClose() {
|
||||
Close();
|
||||
DestroyOSWindowHandle();
|
||||
}
|
||||
|
||||
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?
|
||||
}
|
||||
|
||||
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;
|
||||
|
||||
throw std::invalid_argument("Attempted to handle unmapped mouse button.");
|
||||
}
|
511
src/platform/windows/Window.cpp
Normal file
511
src/platform/windows/Window.cpp
Normal file
@@ -0,0 +1,511 @@
|
||||
#include <Windows.h>
|
||||
#include <gl/GL.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, ¢er);
|
||||
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 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: {
|
||||
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 (!focused) {
|
||||
FLASHWINFO fi;
|
||||
fi.cbSize = sizeof(FLASHWINFO);
|
||||
fi.hwnd = platform->hwnd;
|
||||
fi.dwFlags = FLASHW_ALL;
|
||||
fi.uCount = 0;
|
||||
fi.dwTimeout = 0;
|
||||
FlashWindowEx(&fi);
|
||||
}
|
||||
}
|
||||
|
||||
void RWindow::DestroyOSWindowHandle() {
|
||||
DestroyWindow(platform->hwnd);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
std::pair<int, int> RWindow::GetAccurateCursorCoordinates() const {
|
||||
POINT point;
|
||||
GetCursorPos(&point);
|
||||
ScreenToClient(platform->hwnd, &point);
|
||||
return { point.x, point.y };
|
||||
}
|
||||
|
||||
void RWindow::SetCursorVisible(bool cursor_enable) {
|
||||
cursor_visible = cursor_enable;
|
||||
}
|
||||
|
||||
bool RWindow::GetCursorVisible() {
|
||||
return cursor_visible;
|
||||
}
|
||||
|
||||
void RWindow::SetKeyRepeatEnabled(bool state) {
|
||||
key_repeat = state;
|
||||
}
|
||||
|
||||
std::pair<int, int> RWindow::GetSize() const {
|
||||
RECT rect;
|
||||
GetClientRect(platform->hwnd, &rect);
|
||||
return { (rect.right - rect.left), (rect.bottom - rect.top) };
|
||||
}
|
||||
|
||||
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::SetPosition(const std::pair<int, int>& pos) {
|
||||
SetPosition(pos.first, pos.second);
|
||||
}
|
||||
|
||||
void RWindow::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() {
|
||||
SetWindowLong(platform->hwnd, GWL_STYLE, GetWindowLong(platform->hwnd, GWL_STYLE) | WS_OVERLAPPEDWINDOW);
|
||||
|
||||
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 {}
|
||||
|
||||
RWindow::RWindow() {
|
||||
extant = this;
|
||||
platform = new Platform();
|
||||
}
|
||||
|
||||
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) {
|
||||
extant = this;
|
||||
platform = new Platform();
|
||||
}
|
||||
|
||||
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 = RWindow::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");
|
||||
}
|
@@ -1,24 +0,0 @@
|
||||
#include <rewindow/types/key.h>
|
||||
|
||||
std::vector<Key> Key::keyboard = {};
|
||||
|
||||
std::vector<Key> Key::GetKeyboard() { return keyboard; }
|
||||
|
||||
Key::Key() {
|
||||
|
||||
keyboard.push_back(*this);
|
||||
}
|
||||
|
||||
Key::Key(char charcode, X11Scancode scancode, WindowsScancode sc)
|
||||
: CharCode(charcode), x11ScanCode(scancode), winScanCode(sc)
|
||||
{
|
||||
keyboard.push_back(*this);
|
||||
}
|
||||
|
||||
bool Key::operator==(const Key &rhs) const {
|
||||
return (this->CharCode == rhs.CharCode);
|
||||
}
|
||||
|
||||
bool Key::operator<(const Key &rhs) const {
|
||||
return (this->CharCode < rhs.CharCode);
|
||||
}
|
7
src/types/WindowEvents.cpp
Normal file
7
src/types/WindowEvents.cpp
Normal file
@@ -0,0 +1,7 @@
|
||||
#include <ReWindow/types/WindowEvents.h>
|
||||
|
||||
|
||||
namespace ReWindow
|
||||
{
|
||||
|
||||
}
|
41
src/types/key.cpp
Normal file
41
src/types/key.cpp
Normal file
@@ -0,0 +1,41 @@
|
||||
#include <ReWindow/types/Key.h>
|
||||
//std::vector<Key> Key::keyboard = {};
|
||||
|
||||
std::vector<Key> Key::GetKeyboard() { return keyboard; }
|
||||
|
||||
|
||||
|
||||
Key::Key(const char* charcode, X11Scancode scancode, WindowsScancode sc)
|
||||
: Mnemonic(charcode), x11ScanCode(scancode), winScanCode(sc)
|
||||
{
|
||||
//TODO doing this is what crashes the program.
|
||||
keyboard.push_back(*this);
|
||||
}
|
||||
|
||||
bool Key::operator==(const Key &rhs) const {
|
||||
//This is not a good workaround.
|
||||
return (this->x11ScanCode == rhs.x11ScanCode);
|
||||
}
|
||||
|
||||
bool Key::operator<(const Key &rhs) const {
|
||||
return (this->Mnemonic < rhs.Mnemonic);
|
||||
}
|
||||
|
||||
|
||||
|
||||
Key GetKeyFromX11Scancode(X11Scancode code) {
|
||||
for (const auto& key : Key::GetKeyboard())
|
||||
if (key.x11ScanCode == code)
|
||||
return key;
|
||||
std::cout << "Unavaliable Scancode: " + std::to_string((int)code) << std::endl;
|
||||
return Keys::Space;
|
||||
}
|
||||
|
||||
Key GetKeyFromWindowsScancode(WindowsScancode code) {
|
||||
for (const auto& key : Key::GetKeyboard())
|
||||
if (key.winScanCode == code)
|
||||
return key;
|
||||
|
||||
std::cout << "Unavaliable Scancode: " + std::to_string((int) code) << std::endl;
|
||||
return Keys::Space;
|
||||
}
|
35
src/types/mousebutton.cpp
Normal file
35
src/types/mousebutton.cpp
Normal file
@@ -0,0 +1,35 @@
|
||||
#include <ReWindow/types/MouseButton.h>
|
||||
#include <string>
|
||||
#include <ReWindow/Logger.h>
|
||||
|
||||
|
||||
MouseButton::MouseButton(const std::string& charcode, unsigned int index) {
|
||||
this->Mnemonic = charcode;
|
||||
this->ButtonIndex = index;
|
||||
}
|
||||
|
||||
bool MouseButton::operator==(const MouseButton &mb) const {
|
||||
return (mb.ButtonIndex == this->ButtonIndex);
|
||||
}
|
||||
|
||||
bool MouseButton::operator<(const MouseButton &rhs) const {
|
||||
return (this->ButtonIndex < rhs.ButtonIndex);
|
||||
}
|
||||
|
||||
|
||||
MouseButton GetMouseButtonFromXButton(unsigned int button) {
|
||||
switch(button) {
|
||||
case 1: return MouseButtons::Left;
|
||||
case 2: return MouseButtons::Middle;
|
||||
case 3: return MouseButtons::Right;
|
||||
//case 4: return MouseButtons::MWheelUp;
|
||||
//case 5: return MouseButtons::MWheelDown;
|
||||
//For *whatever* reason. These aren't in X.h
|
||||
case 8: return MouseButtons::Mouse4;
|
||||
case 9: return MouseButtons::Mouse5;
|
||||
default: {
|
||||
ReWindow::Logger::Fatal("Undefined XButtonCode: " + std::to_string((int) button));
|
||||
return MouseButtons::Unimplemented;
|
||||
}
|
||||
}
|
||||
}
|
@@ -1,31 +0,0 @@
|
||||
#include <rewindow/types/window.h>
|
||||
|
||||
|
||||
LRESULT CALLBACK WindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
|
||||
|
||||
|
||||
LPTSTR szClassName = TEXT("GenericProgramWindowClass");
|
||||
|
||||
WNDCLASS wc = { };
|
||||
wc.lpfnWndProc = WindowProc;
|
||||
|
||||
HWND hwnd;
|
||||
|
||||
RWindow::RWindow()
|
||||
{
|
||||
hwnd = CreateWindow();
|
||||
}
|
||||
|
||||
|
||||
void RWindow::raise() const {
|
||||
SendMessage(hwnd, WM_SYSCOMMAND, SC_RESTORE, 0); // Restore
|
||||
SetForegroundWindow(hwnd);
|
||||
SetActiveWindow(hwnd);
|
||||
SetWindowPos(hwnd, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOMOVE | SWP_NOSIZE);
|
||||
// Redraw to prevent the window blank
|
||||
RedrawWindow(hwnd, NULL, 0, RDW_FRAME | RDW_INVALIDATE | RDW_ALLCHILDREN);
|
||||
}
|
||||
|
||||
void RWindow::lower() const {
|
||||
|
||||
}
|
Reference in New Issue
Block a user