1
0
Fork 0

Compare commits

...

365 commits

Author SHA1 Message Date
e73d1f7f90 source/Platform/Win32/Win32GLContext.cpp: skip goto in createGLContext() 2024-07-05 01:02:59 +02:00
f71fdea463 source/Platform/Unix: Rename XRandR to Xrandr 2024-06-22 19:56:33 +02:00
ca46bd0ef7 adding .clang-format 2024-06-22 19:50:05 +02:00
0596e1ba3b .gitignore: adding LSP files 2024-06-22 19:49:55 +02:00
f6c44a223b source/Platform/Win32/Win32Mouse.cpp: in update() call GetActiveWindow() instead of GetCapture()
We want the currently focused window whether it is captured or not.
2023-08-23 20:05:54 +02:00
ea763a9f38 Spectre/Window/GLContext: remove static create() method. 2023-08-23 19:45:01 +02:00
f35658a971 source/Window/GLWindow.cpp: use PlatformApplication::createGLContext() instead of GLContext::create() 2023-08-23 19:43:59 +02:00
b300310239 Platform/PlatformApplication: add createGLContext() 2023-08-23 19:43:22 +02:00
b1ccea1397 Spectre/Window/Window: refactor out GLContext specific code to its own class (GLWindow) 2023-08-23 19:32:23 +02:00
2de3bd93f7 Platform/PlatformWindow: remove make() 2023-08-23 15:08:21 +02:00
f5db354aec source/Window/Window.cpp: call PlatformApplication::createWindow() instead of PlatformWindow::make() 2023-08-23 15:07:51 +02:00
a8f65e54ac Platform/PlatformApplication: Adding createWindow() 2023-08-23 15:06:54 +02:00
2ac3b5b8cc Platform/PlatformApplication: define getMessageQueue() here as it is not platform specific. 2023-08-22 20:24:59 +02:00
4380f1ed01 include/Spectre/System/Event.h: Change "None" to "Unkown" as None is a macro in X11 2023-08-22 20:02:12 +02:00
cadbbf9d8b Platform/PlatformWindow: adding getOwner() 2023-08-22 17:51:24 +02:00
1288ef88b8 Platform/PlatformWindow: pass owner in constructor instead of setting the variable directly on the object. it is cleaner. 2023-08-22 17:18:39 +02:00
5a7a5e3f7c source/Platform/Win32/Win32Window.h: fix header guard. 2023-08-22 17:12:36 +02:00
a3c63e6e96 remove examples/display/main.cpp 2023-08-22 17:10:44 +02:00
afc0845006 source/Platform/PlatformWindow.h: rename parent to owner as the generic window is not really a parent to the platform one. 2023-08-22 17:10:08 +02:00
45d3bff620 Unix: Rename X11Display to X11Window and make it work again with Spectre/Window/Window 2023-08-22 10:06:19 +02:00
96f6725428 include/Spectre/Math/Matrix3.inl: make Identity work for all template specializations. not just float. 2023-08-22 10:02:07 +02:00
8901257bb6 Rename DisplayExample to WindowExample 2023-08-22 07:17:51 +02:00
24da7f45e0 Rename Display to Window.
It makes more sense to be consistent and always call it window.
2023-08-22 07:12:47 +02:00
416a71f744 Spectre/Math: Adding Vector2UnProject() 2023-08-21 07:05:34 +02:00
813c0dab17 source/System/Log.cpp: make sure the writer is flushed after we write a line. 2023-08-20 21:07:13 +02:00
7b0cf72ac4 Spectre/System/Log/FileWriter: Implement flush() 2023-08-20 21:06:39 +02:00
8dbb0e0211 include/Spectre/System/Log/Writer.h: Adding flush() 2023-08-20 21:05:51 +02:00
0f7a4bbabc include/Spectre/Math/Transform.h: Adding inverse() 2023-08-18 17:54:37 +02:00
d8db86e40c include/Spectre/Math/Matrix3.h: Add inverse() 2023-08-18 17:54:37 +02:00
910bad0fb7 source/Math/Transform.cpp: Style fixes. 2023-08-18 17:54:37 +02:00
6e8f060882 include/Spectre/Math/Matrix3.h: Adding multiplication and division scalar operations. 2023-08-04 03:48:03 +02:00
c313c5134f source/Platform/Win32/Win32Keyboard.cpp: Minor style fixes. 2023-08-04 03:43:46 +02:00
7b46a85cec source/Platform/Win32/Win32Keyboard.cpp: Fixing some keycodes that where wrong. 2023-08-04 03:43:26 +02:00
fcc292a40f source/Platform/Win32/Win32Display.cpp: in create() fix a bug where window size was initially not setup correctly causing two resize events. 2023-08-03 15:43:18 +02:00
ea4267ef2d source/Platform/Win32/Win32Display.cpp: Use calculateSize() in setSize() 2023-08-03 15:24:11 +02:00
80591ff6ee source/Platform/Win32/Win32Display: Adding calculateSize() 2023-08-03 15:23:19 +02:00
76aa838e8e source/Platform/Win32/Win32GLContext.cpp: in isActive() make sure this function returns false if m_renderContext is null. 2023-08-02 22:48:40 +02:00
c1f1dd75bd GLContext: remove setSize() and set glViewport() in Display::onReshape() 2023-08-02 22:30:45 +02:00
60333f6d02 include/Spectre/Display/Display.h: Adding getSize() 2023-08-02 22:18:33 +02:00
f240d14052 examples/input/InputExample.cpp: Also test mouse grab. 2023-08-02 20:34:38 +02:00
962c18fcac examples/input/InputExample: Adding support for Event based mouse movement. 2023-08-02 20:32:46 +02:00
085d593b66 source/Platform/Unix/X11Display.cpp: implement grabCursor() 2023-08-02 20:30:37 +02:00
d601d95d40 source/Platform/Unix/X11Display.cpp: Tell window to generate pointer events. 2023-08-02 20:30:37 +02:00
2cf035089b source/Platform/Unix/X11Display.cpp: implement fullscreen somewhat correctly :) 2023-08-02 20:30:37 +02:00
186a6e0f14 Unix: Adding FindMode() XRandR helper function. 2023-08-02 20:30:37 +02:00
624871486f source/Platform/Unix/X11Display.cpp: Improve logging. 2023-08-02 20:30:37 +02:00
57d4e44bbe source/Platform/Unix/X11Display.cpp: make getSize() query X11 and dont just return cached value. 2023-08-02 20:30:37 +02:00
8ff2a3d37f engine.cmake: sort unix files abit. 2023-08-02 20:30:37 +02:00
ea0edcf07f source/Platform/Unix/GLXContext.h: Whitespace fix. 2023-08-02 20:30:37 +02:00
1854c4cb51 source/Platform/Unix/GLXContext.cpp: Whitespace fix. 2023-08-02 20:30:37 +02:00
35a6b38d16 source/Platform/Unix/X11Mouse.cpp: minor whitespace fix. 2023-08-02 20:30:37 +02:00
53d8248b8c source/Platform/Unix/X11Display.cpp: typofix. 2023-08-02 20:30:37 +02:00
ff5d719fcf source/Platform/Unix/X11Display.cpp: Do not capture Pointer motions. 2023-08-02 20:30:37 +02:00
75a53f635d source/Platform/Unix/X11EventQueue.cpp: Remove ResizeRequest. 2023-08-02 20:30:37 +02:00
043afc4e3d source/GfxDriver/OpenGL/OpenGLDrv.h: Adding createShaderProgram() 2023-07-25 18:56:38 +02:00
c87bed2a59 include/Spectre/GfxDriver/GfxDriver.h: add createShaderProgram() 2023-07-25 18:55:47 +02:00
5144c197d5 Style fixes. 2023-05-01 17:48:02 +02:00
5c5d9fe09a GfxDriver: add getName() getVersion() and getCardName() 2023-05-01 17:46:37 +02:00
43354fc9b4 Spectre/Math: rename all vector length() and normalize() functions to len() and normal() 2023-04-30 23:07:25 +02:00
4a6a20342d Spectre/Math/Time: minor fixes and documentation 2023-04-30 23:02:16 +02:00
b9936e5867 source/Math/Logarithm.cpp: include cmath directly instead of cstdlib 2023-04-30 15:58:29 +02:00
ff44ec7b7a source/Math/Logarithm.cpp: c++11/C99 has log2 in cmath. not sure why i didnt use it. 2023-04-30 15:55:20 +02:00
c1cc476094 source/Platform/Win32/Win32Display.cpp: Tab indentation fix. 2023-02-18 14:03:14 +01:00
ba504c7efc Spectre/Game: Set default log writer. 2023-02-18 13:59:42 +01:00
faed79c653 Spectre/System/Log: Support Writer interface. 2023-02-18 13:59:42 +01:00
8db01a0957 Adding Spectre/System/Log/FileWriter class. 2023-02-18 13:59:42 +01:00
173aea31c9 Adding include/Spectre/System/Log/Writer.h interface. 2023-02-18 13:59:42 +01:00
9928a3599e include/Spectre/System/Log.h: Change message variable name to format. 2023-02-18 13:59:42 +01:00
2bb0cbaf6b source/Graphics/Graphics.cpp: implement getDriver() 2023-02-18 13:10:43 +01:00
869b41c38a source/Platform/Unix/UnixMisc.cpp: tab indentation fix. 2023-02-18 13:08:03 +01:00
8a0946eb3a .gitattributes: add more filetypes. 2023-02-18 13:07:01 +01:00
dcbce9a153 .gitignore: Ignore VS debug files. 2023-02-18 13:06:43 +01:00
a024e7015d Whitespace fixes. 2023-02-18 13:06:02 +01:00
07f32ee129 include/Spectre/Graphics.h: Adding getDisplay() 2023-02-18 13:05:07 +01:00
d57d01c4b4 README.md: Add "sh" to code blocks. 2023-02-18 13:04:05 +01:00
9c4c6152c9 source/Platform/Win32/Win32Display.cpp: Whitespace fix. 2022-10-08 17:29:27 +02:00
9b683e9a5c source/Graphics/Graphics.cpp: should delete m_gfxdrv in destructor. 2022-10-08 16:49:04 +02:00
d70ca4a6c1 include/Spectre/System/Log.h: Whitespace fix. 2022-10-08 14:54:40 +02:00
3c7a5d148d include/Spectre/Graphics/PixelFormat.h: Whitespace fix. 2022-10-03 22:11:39 +02:00
82343f0835 source/Graphics/Image.cpp: minor style fix. 2022-10-03 22:11:26 +02:00
0a5eb397c7 Platform/Unix/X11Display: Adding stub for enterFullscreen and exitFullscreen 2022-10-02 23:31:46 +02:00
84f0a83bee source/Platform/Unix/X11Display.cpp: Whitespace fix. 2022-10-02 17:11:27 +02:00
605e0df902 source/Platform/Unix/X11Display.cpp: call setDecoration() in create() 2022-10-02 17:07:14 +02:00
36c6024649 Platform/Unix/X11Display: remove setIcon(const std::string&) as this exists in Generic Display class. 2022-10-02 17:06:02 +02:00
a8fa3981f4 source/Platform/Unix/Xlib.cpp: assert _priv::display in shutdown() 2022-10-02 17:02:10 +02:00
b78ddba11e Platform/Unix/X11Display: implement setDecoration() 2022-10-02 17:01:40 +02:00
c20c79cfd3 Adding source/Platform/Unix/wm_hints.h 2022-10-02 17:00:45 +02:00
1c7cc31b52 source/Platform/Unix/X11Display.cpp: Fix getPosition() as it did not take border width into account. 2022-10-01 16:09:43 +02:00
46bc8eb5d8 Platform/Unix/Xlib: Adding getParentWindow() 2022-10-01 16:09:43 +02:00
05b59a4677 engine.cmake: Small comment fix. 2022-10-01 16:09:43 +02:00
7f141a8930 engine.cmake: OpenGL on unix needs to link with GLX. 2022-10-01 16:09:43 +02:00
a4f7c90f63 engine.cmake: Unix systems needs to link with X11 and Xrandr 2022-10-01 16:09:42 +02:00
54aefa4bdd engine.cmake: fix ENGINE_PLATFORM_UNIX_SRC. they are in Unix directory not X11 2022-10-01 16:09:42 +02:00
f2fc9d46b8 Revert "include/Spectre/Display/DisplayDescription.h: change Empty to None"
This reverts commit 7c23f5dfd9.

`None` is defined in X11.
2022-10-01 16:09:42 +02:00
6007f52194 README.md: Update with cmake info. 2022-09-28 15:54:20 +02:00
36af790293 Remove bam 2022-09-26 22:31:50 +02:00
0406a38895 vendor/stb/include/stb_image_write.h: Remove _CTR_SECURE_NO_WARNINGS as we define it in cmake. 2022-09-26 22:23:43 +02:00
2dc8050ce3 Adding CMake again :) 2022-09-26 22:22:25 +02:00
cb4274bb1c source/GfxDriver/OpenGL/OpenGLShaderProgram.cpp: Indent fix. 2022-09-26 14:12:47 +02:00
b6446e129b source/GfxDriver/OpenGL/OpenGLShaderProgram.cpp: Whitespace fix. 2022-09-26 14:11:38 +02:00
736f30c33a source/GfxDriver/OpenGL/OpenGLShaderProgram.cpp: remove unused variable 2022-09-26 14:11:17 +02:00
50e9300667 Game/FPSCounter: change m_fps variable and getFPS() return value from float to double.
MSVC complains about loss of information because sp::Time::seconds() returns double.
2022-09-26 12:06:40 +02:00
c11d71aaaa Spectre/System/File: adding readString() 2022-09-25 16:31:52 +02:00
99ae7f2236 .gitignore: Add VS Code stuffs. 2022-09-18 13:59:57 +02:00
d7889ebac0 engine.build.lua: include OpenGLShaderProgam in gfxdriver_opengl_module 2022-09-18 13:58:10 +02:00
bb205c6ad1 engine.build.lua: compile GfxDriver/ShaderProgram 2022-09-18 13:57:20 +02:00
81f3e1e399 Graphics: Remove Shader and ShaderProgram classes. they are combined into GfxDriver/ShaderProgram. 2022-09-18 13:56:37 +02:00
82e08d0785 Graphics/DefaultRenderer2D: use GfxDriver/ShaderProgram instead of Graphics/ShaderProgram 2022-09-18 13:55:43 +02:00
9bea188686 Graphics/BatchRenderer2D: use GfxDriver/ShaderProgram instead of Graphics/ShaderProgram 2022-09-18 13:54:32 +02:00
cc1f287a3a source/Graphics/RenderState.cpp: Use GfxDriver/ShaderProgram instead of Graphics/ShaderProgram. 2022-09-18 13:53:48 +02:00
b85b4ab601 include/Spectre/Graphics/Renderer2D.h: Dont have to include ShaderProgram here. 2022-09-18 13:51:18 +02:00
69e5ae22d2 Adding GfxDriver/OpenGL/OpenGLShaderProgram class 2022-09-18 12:26:31 +02:00
cd9114bfd0 Adding Spectre/GfxDriver/ShaderProgram base class. 2022-09-18 12:26:01 +02:00
b91bc22db1 engine.build.lua: Graphics module: OpenGL.cpp is now called Graphics.cpp 2022-09-18 12:24:44 +02:00
038d997421 engine.build.lua: build OpenGL gfx driver. 2022-09-18 12:22:19 +02:00
4dad1a5d75 Graphics class: use GfxDriver API. 2022-09-17 12:07:28 +02:00
d3debea41a Adding OpenGL Driver. 2022-09-17 12:06:47 +02:00
ab11f7b9db Adding include/Spectre/GfxDriver/GfxDriver.h 2022-09-17 12:06:00 +02:00
3a7f91cb07 Merge branch 'fullscreen-api-nonrecreate' into dev 2022-09-13 20:39:02 +02:00
deb9918b9b source/Display/Display.cpp: Need to set position to 0,0 in window fullscreen, otherwise it wont stick to the top-left of the monitor. 2022-09-13 19:52:34 +02:00
7c23f5dfd9 include/Spectre/Display/DisplayDescription.h: change Empty to None 2022-09-13 19:43:26 +02:00
1c27fce58c examples/display/DisplayExample.cpp: make "W" key switch to windowed fullscreen. 2022-09-13 19:35:46 +02:00
4761473e86 include/Spectre/Display/DisplayDescription.h: remove fullscreen here as it is not a decorator flag. 2022-09-12 22:45:54 +02:00
3c6a842c9d Platform/Win32/Win32Display.cpp: remove fullscreen stuff in create() 2022-09-12 22:44:51 +02:00
fc38bb59a9 source/Display/Display.cpp: restore size when entering window mode. 2022-09-12 22:25:15 +02:00
d12d60b1ba Display/Display: Cache position when entering fullscreen and restore when entering window mode again. 2022-09-12 22:24:42 +02:00
83f4d05df8 source/Game.cpp: call PlatformApplication::get() and dont delete the pointer. 2022-09-12 21:13:04 +02:00
c7d380c4b0 source/Platform/PlatformApplication: rename create() to get() and just return a statically allocated implementation.
As we just this throughout the whole program. and platform can be determined at compile time. we might as well allocate it statically.
2022-09-12 21:12:32 +02:00
859e95eea8 bam.lua: Set custom compiler functions. 2022-09-12 19:57:10 +02:00
d678f3c7a0 Adding .bam/compilers.lua 2022-09-12 19:56:54 +02:00
c83337b6a6 .bam/path.lua: Adding ModuleRelative() 2022-09-12 19:55:34 +02:00
c2c201c9e4 vendor/FreeType2/build.lua: build a static lib. 2022-09-12 19:43:49 +02:00
2f39299fc6 vendor/FreeType2/build.lua: use SetSettingsPrefix() 2022-09-12 19:41:07 +02:00
397120a973 examples/build.lua: use PathFilename(name) as name contains a directory. 2022-09-12 19:37:04 +02:00
4222d89eb2 examples/build.lua: Use libspectre_settings. 2022-09-12 19:35:24 +02:00
9dc3a49207 .bam/utils.lua: Adding TableMerge() 2022-09-12 19:34:10 +02:00
8082309896 .bam/functions.lua: Adding SetSettingsPrefix() 2022-09-12 19:32:44 +02:00
0170e8181b engine.build.lua: export settings. 2022-09-11 15:09:15 +02:00
82cfe55a91 vendor/FreeType2/build.lua: use RelPath() "everywhere" 2022-09-11 00:29:41 +02:00
7967eaea2a bam.lua: import .bam/path.lua 2022-09-11 00:29:41 +02:00
fc64fedb0e engine.build.lua: use RelPath() "everywhere" 2022-09-11 00:29:41 +02:00
fd108cc391 engine.build.lua: remove linkage with freetype2 as we build it ourself on windows. 2022-09-10 21:43:01 +02:00
d35ba0730e .bam/functions.lua: use RelPath() in module to get the correct paths. 2022-09-10 21:39:05 +02:00
0ce1d25594 examples/build.lua: rename example_settings to just settings as it's a locale variable anyway. 2022-09-10 21:37:22 +02:00
b913c2024d .bam/functions.lua: delete BuildExample() and BuildExamples() 2022-09-10 21:35:39 +02:00
315f2e9c41 examples/build.lua: skip using BuildExamples(). just run the code directly here as we wont need it anywhere else. 2022-09-10 21:34:52 +02:00
de789ad77e .bam/functions.lua: Imports() should be relative to the current script. 2022-09-10 21:14:21 +02:00
788e3f697e bam.lua: Adding descriptive comment to global_settings.lib.prefix 2022-09-10 20:05:55 +02:00
01b626d44e Adding .bam/path.lua 2022-09-10 20:02:34 +02:00
e9ebb38090 vendor/FreeType2/src/base/module.lua: basepath to Module() should be relative to the script's directory. 2022-09-10 19:59:38 +02:00
54805c07f4 .bam/functions.lua: use paths.examples in BuildExample() to get the correct path. 2022-09-10 19:57:40 +02:00
6a84af227c bam.lua: append "_<TARGET_OS>" to examples output directory. 2022-09-10 19:56:07 +02:00
1902b92210 bam.lua: Add "intermediate" directory to paths and use it when building object files. 2022-09-10 19:46:36 +02:00
03cbba9a6c include/Spectre/Core/NonCopyable.h: Destructor needs to be virtual. Otherwise deleting a NonCopyable pointer wont call the child class destructor 2022-09-10 14:10:11 +02:00
9621ea19bb source/Platform/Win32/Win32Display.cpp: on x64, windows headers undefine GWL_USERDATA, So we define it again. 2022-09-10 14:02:58 +02:00
8d57b3a72c source/Platform/Win32/Win32Display.cpp: Use SetWindowLongPtr/GetWindowLongPtr as LONG_PTR supports 64bit addresses. 2022-09-10 13:59:40 +02:00
e97844a6e6 Spectre/Core/NonCopyable.h: Updated make use of C++11 default and delete keywords. 2020-12-29 20:07:12 +01:00
46af40bbb7 source/Platform/PlatformApplication.h: extend NonCopyable 2020-12-29 19:54:49 +01:00
b984f30968 Platform/Win32/Win32Display.cpp: for WM_SIZE event we can use lParam variable to get the size. 2020-12-29 17:45:32 +01:00
0a75f0c2ed .bam/functions.lua: adding documentation to host_system() 2020-12-28 19:28:27 +01:00
cbd26a211d .bam/functions.lua: in host_system() switch from 'family' to 'platform' variable.
family == "unix" contains FreeBSD and MacOS. that we dont have support for.
2020-12-28 19:27:39 +01:00
543542625d .bam/functions.lua: rename system() to host_system() 2020-12-28 19:13:28 +01:00
d9697e2eae bam.lua: allow TARGET_OS to be set from CLI, fallback on host. 2020-12-28 19:13:05 +01:00
707cd7732c .bam/functions.lua: adding valid_system() 2020-12-28 19:13:05 +01:00
bb28f5658f Adding .bam/utils.lua 2020-12-28 19:13:05 +01:00
36e4894dc7 bam.lua: allow paths.build variable to be set from CLI 2020-12-28 18:47:28 +01:00
0e2a3525e4 Merge branch '4-linux-support' into dev 2020-12-28 18:43:22 +01:00
a172fbb323 engine.build.lua: Fix local variable inside if statement. 2020-12-28 18:41:51 +01:00
d48cc650a8 source/Platform/PlatformApplication.cpp: ApplicationType is defined by some Win32 headers. 2020-12-28 18:41:51 +01:00
845b93fb48 source/Platform/Win32/Win32Display.cpp: DisplayDecorate::None has changed to DisplayDecorate::Empty 2020-12-28 18:38:27 +01:00
f6aa0246d3 source/Platform/Unix/X11Mouse.cpp: implement hack for XButton1 and 2. 2020-12-28 18:20:55 +01:00
c082700891 include/Spectre/Input/Mouse.h rename Button1,Button2 to XButton1 and XButton2
Button1 and Button2 are defined by Xlib. So lets change our ones to avoid headache.
2020-12-28 18:20:55 +01:00
7e79663dce include/Spectre/Input/Mouse.h rename Button1,Button2 to XButton1 and XButton2
Button1 and Button2 are defined by Xlib. So lets change our ones to avoid headache.
2020-12-26 18:08:39 +01:00
81c7e34c58 Use SPECTRE_PLATFORM_* defines instead of raw compiler ones. 2020-12-26 17:25:25 +01:00
2eec1c9f75 source/Game.cpp: use PlatformApplication::create() 2020-12-26 17:20:30 +01:00
b91b9f3768 Platform/PlatformApplication: adding create() method. 2020-12-26 17:20:05 +01:00
0540f5d201 engine.build.lua: add platform defines. 2020-12-26 15:53:52 +01:00
090646b61a Platform/Unix: Rename X11SharedDisplay to Xlib, and remove Display member variable from all classes.
We now initialize/destroy the display in Xlib::init/shutdown that is called in UnixApplication::init/shutdown and
therefore is valid through the whole lifetime. So no need for classes to keep references.
2020-12-26 15:37:56 +01:00
60dd9bacb0 source/Game.cpp: make sure we call init() and shutdown() for platform 2020-12-26 15:37:57 +01:00
197b4df87f Unix: Remove unnecessary includes of Spectre/Display/DisplayDescription.h 2020-12-23 14:36:52 +01:00
12b2413e23 include/Spectre/Display/DisplayDescription.h: Rename DisplayDecorate::None to Empty (None clashes with X11) 2020-12-23 14:34:12 +01:00
080c4f77c3 Platform/Unix/X11Keyboard: only update state and signal key down if we have a focused window. 2020-12-20 16:29:12 +01:00
6c96a3d9a1 Platform/Unix/X11Mouse.cpp: in isButtonDown() check if we have a focused window. 2020-12-20 16:28:25 +01:00
f71cfa86f2 Platform/Unix/X11Mouse: use X11Display::getFocused() to get the coordinates relative to the focused window. 2020-12-20 16:09:16 +01:00
227d58725d Platform/Unix/X11Display.cpp: Set and unset focused_display variable when the display receives FocusIn/Out events. 2020-12-20 16:03:05 +01:00
d9f54b08ca Platform/Unix/X11Display: Adding getFocused() 2020-12-20 16:01:37 +01:00
d971cd6cb2 Platform/Unix/X11Display.cpp: Capture input focus events (just log for now). 2020-12-20 13:55:56 +01:00
56c24f7118 Platform/Unix/X11Display: Implement missing interface functions.
* getPosition
* setVisible
* minimize
* maximize
* grabCursor (only stub. to get the code to compile)
2020-12-20 13:43:35 +01:00
40e4f95452 Platform/Unix/X11Display.cpp: minor stuff. 2020-12-19 18:55:12 +01:00
0c76864b40 Platform/Unix/X11Display: in setSize() check if width or height is zero before calling XResizeWindow() 2020-12-19 18:55:12 +01:00
50439a58bd source/Platform/Unix/X11Display.cpp: in destroy() make sure m_disp is valid before calling functions that needs it. 2020-12-19 18:55:12 +01:00
0d029817fe source/Platform/Unix/X11Display.cpp: in destroy() call XDestroyWindow() 2020-12-19 18:55:12 +01:00
61b233f708 Platform/Unix/X11Display.cpp: Minor cleanup. 2020-12-19 18:55:12 +01:00
f5d80aa46f Platform/Unix/X11Display: Implement setIcon() 2020-12-19 18:55:12 +01:00
3d9dda64ca Platform/Unix/X11Display: Implement showCursor() 2020-12-19 18:55:12 +01:00
d73c787f40 Platform/Unix/X11SharedDisplay: pass a pointer to the display to XReleaseDisplay() just to be sure client code has a valid pointer 2020-12-19 18:55:11 +01:00
421bf819d5 examples/build.lua: Unix systems needs to link with xrandr. 2020-12-19 18:55:11 +01:00
dfe29acc1e Platform/Unix/UnixMisc.cpp: implement display mode lookups using xrandr extension. 2020-12-19 18:55:11 +01:00
03186ebea0 Platform/Unix/X11EventQueue.cpp: pass ButtonPress/ButtonRelease/MotionNotify events to X11Mouse 2020-12-19 18:55:11 +01:00
816cf3a072 Platform/Unix/X11Mouse: adding a basic implementation to get things going. 2020-12-19 18:55:11 +01:00
cfe064f02c Platform/Unix/X11Keyboard: implement isKeyDown() 2020-12-19 18:55:11 +01:00
7356bdebdd Platform/Unix/X11EventQueue: Fix bug where messeges where not flushed to the event queue.
XEventsQueued(disp, QueuedAlready) only returns the number of events currently in the queue and
does not flush new events. So this must happen elsewhere and if it does not we
will never see any events. i noticed this bug when removing the call to glXSwapBuffers().

Fix this by using XPending() instead as this flushes new events
if the queue is empty before returning the length.

see https://tronche.com/gui/x/xlib/event-handling/XEventsQueued.html
and https://tronche.com/gui/x/xlib/event-handling/XPending.html
2020-12-19 18:55:11 +01:00
4193b3b719 Platform/Unix/X11EventQueue: send KeyPress and KeyRelease events to X11Keyboard::handleMessage() 2020-12-19 18:55:11 +01:00
9954c45fe9 Platform/Unix/X11Keyboard: Implement handleMessage() 2020-12-19 18:55:11 +01:00
30dc11f0d5 Platform/Unix/X11Display.h: Some documentation. 2020-12-19 18:55:11 +01:00
23cf17f9af Platform/Unix/X11EventQueue.cpp: Only process one event per call to poll(). Confirming to Platform API. 2020-12-19 18:55:11 +01:00
7648c23e43 Platform/Unix/X11EventQueue: get and release display handle in constructor/destructor instead of every call to poll()
Should be fine as the display should never change during runtime.
2020-12-19 18:55:11 +01:00
c5648a5105 Platform/Unix/X11EventQueue: redirect unkown events to X11WindowEventHandler. 2020-12-19 18:55:11 +01:00
2b14977eed source/Platform/Unix/X11Display.cpp: register with X11WindowEventHandler 2020-12-19 18:55:11 +01:00
7402896ce6 Adding Platform/Unix/X11WindowEventHandler 2020-12-19 18:55:11 +01:00
7a694e8fd0 Platform/Unix/X11Display: Adding processEvent() to handle resize. 2020-12-19 18:55:11 +01:00
f07be50bd3 source/Platform/Unix/X11Display.cpp: Replace ResizeRedirectMask with StructureNotifyMask
ResizeRedirectMask is broken (will not update the window size). We use StrucutreNotifyMask instead and capture the window size from CaptureNotify event instead.
2020-12-19 18:55:10 +01:00
96b61f0ee3 source/Platform/Unix/X11Display.cpp: in create() call setSize() 2020-12-19 18:55:10 +01:00
9b5bd9dcd0 source/Platform/Unix/X11EventQueue.cpp: post quit event on "WM_DELETE_WINDOW". 2020-12-19 18:55:10 +01:00
035dd333da source/Platform/Unix/X11EventQueue.cpp: log "WM_DESTROY_WINDOW" message. 2020-12-19 18:55:10 +01:00
46bf27f4a4 source/Platform/Unix/X11Display.cpp: call XSetWMProtocols with "WM_DELETE_WINDOW" flag. 2020-12-19 18:55:10 +01:00
d94c7fcf9a Platform/Unix/X11SharedDisplay: adding getAtom() 2020-12-19 18:55:10 +01:00
f8188c4358 source/Platform/Unix/UnixEventQueue.cpp: implement a poll method (only log events for now) 2020-12-19 18:55:10 +01:00
5e27f820de source/Platform/Unix/X11Display.cpp: in create() set the attr.event_mask to include some interesting events. 2020-12-19 18:55:10 +01:00
7dedabba57 source/Platform/Unix/GLXContext: Initial implementation 2020-12-19 18:55:10 +01:00
b65cb9c2d2 source/Platform/Unix/X11Display.cpp: Initial implementation 2020-12-19 18:55:10 +01:00
bd38e9e98f Adding source/Platform/Unix/X11SharedDisplay.cpp 2020-12-19 18:55:10 +01:00
c41fb6c013 Adding glad GLX 2020-12-19 18:55:10 +01:00
7fd1ee5445 assets: bam does not like whitespace in file names. 2020-12-19 18:55:10 +01:00
1cfd4adca4 bam: adding unix support. 2020-12-19 18:55:10 +01:00
6464838159 source/Platform/Unix: stub implementation 2020-12-19 18:55:10 +01:00
db695f11f6 Spectre/Game/GameTime: Store max accumulated time in a member variable and calculate it once in setTimeStep() 2020-12-18 18:27:07 +01:00
2a608805b5 Spectre/Game/GameTime: add shouldTick() 2020-12-18 18:27:07 +01:00
ed876ca64d Spectre/Game/GameTime: remove useless m_inLoop variable. 2020-12-18 18:27:07 +01:00
d49d91a294 Spectre/Game/GameTime: Use sp::Time and sp::Stopwatch 2020-12-18 18:27:07 +01:00
6ee1752735 include/Spectre/Game.h: Remove unused variable. 2020-12-18 18:27:07 +01:00
3855cdd541 Game/FPSCounter: Use sp::Stopwatch 2020-12-18 18:27:07 +01:00
f62373dcbc Adding Spectre/System/Stopwatch 2020-12-18 18:27:07 +01:00
919aa7740a Spectre/Game/FPSCounter: Use sp::Time 2020-12-16 16:33:32 +01:00
6de6028ba4 Adding Spectre/Math/Time 2020-12-16 16:33:32 +01:00
d34d20361d include/Spectre/Display/DisplayDescription.h: adding Fullscreen flag. 2020-12-09 02:46:55 +01:00
74a2ff028c source/Display/Display.cpp: Use the new display api that does not require recreating the display. 2020-12-09 02:46:55 +01:00
ea91d50a84 source/Graphics/OpenGL.cpp: minor fix. no need to set window decoration (default is fine) 2020-12-09 02:46:55 +01:00
304e345a79 Platform/Win32/Win32Display: Implementing true fullscreen with enterFullscreen() and exitFullscreen() 2020-12-09 02:46:55 +01:00
ca5e2a399c Platform/PlatformDisplay: adding enterFullscreen() and exitFullscreen() 2020-12-09 02:46:54 +01:00
ebe3a648c5 Platform/Win32/Win32Display: Implement setDecoration() 2020-12-09 02:46:54 +01:00
02567eb225 source/Platform/PlatformDisplay.h: Adding setDecoration() 2020-12-09 02:46:54 +01:00
4d69ff3a18 Adding Display Example 2020-12-09 02:45:40 +01:00
b43f2fcca8 Display/DisplayMode: adding empty() 2020-12-05 18:23:16 +01:00
c2b0d73888 source/Display/DisplayMode.cpp: initialize bpp to zero. 2020-12-05 18:23:16 +01:00
3f38286049 source/Platform/Win32/Win32EventQueue.cpp: change OutputDebugString() to Log::debug() 2020-12-05 15:31:48 +01:00
fc1fc7001a Spectre/Display/Display: Adding setVisible() 2020-12-05 15:31:48 +01:00
5d433a7b80 source/Platform/Win32/Win32Display.cpp: don't call destroy() on WM_DESTROY as the window is already destroyed if we get this event. 2020-12-05 15:31:48 +01:00
2da0f7e712 Platform/Win32/Win32Display.cpp: change OutputDebugString() to Log::debug() 2020-12-05 15:31:47 +01:00
f0d769c923 Platform/Win32/Win32Display: minor fix. 2020-12-05 15:31:47 +01:00
04db63aa49 Platform/Win32/Win32Display: implement setVisible() 2020-12-05 15:31:47 +01:00
48b501e355 source/Platform/PlatformDisplay.h: add setVisible() to the interface 2020-12-05 15:31:47 +01:00
17759992c8 Platform/Win32/Win32Display: implement maximize() and minimize() 2020-12-05 15:31:47 +01:00
d7d8a23dc2 Platform/Win32/Win32Display: implement getPosition() 2020-12-05 15:31:47 +01:00
70f73c1d52 source/Platform/PlatformDisplay.h: add getPosition() to the intreface 2020-12-05 15:31:47 +01:00
33270d9f7b source/Platform/PlatformDisplay.h: add minimize() and maximize() to the interface 2020-12-05 15:31:47 +01:00
0a5681c871 Spectre/Display/Display: implement grabCursor() 2020-12-05 15:31:47 +01:00
e64d9cdce0 Platform/Win32/Win32Display: implement grabCursor() 2020-12-05 15:31:47 +01:00
0a1c18548d source/Platform/PlatformDisplay.h: add grabCursor() to the interface. 2020-12-05 15:31:47 +01:00
363afe111b source/Platform/Win32/Win32EventQueue.cpp: should not return status from DispatchMessage()
this can falsely signal that we have translated a win32 event to engine event when in fact we have not.
2020-12-05 15:30:45 +01:00
92f42a08fb Spectre/System/Event: Adding toString() 2020-12-05 15:23:06 +01:00
66a4011f4b Spectre/Core/String: Adding to_string() for signed int. 2020-12-05 15:23:06 +01:00
c731cda1a2 Spectre/Graphics/PixelFormat: Rework
source/Graphics/Image/IcoFormat.cpp: use new PixelFormat.
source/Graphics/Image.cpp: update to confirm with new PixelFormat
Spectre/Graphics/PixelFormat: add PF_getNumChannels()
Spectre/Graphics/PixelFormat: Rework the enum with proper naming convention and documentation.
2020-11-03 14:23:38 +01:00
82add50157 Spectre/Display/Display: implement setIcon() with pixel array parameter. 2020-11-03 11:29:14 +01:00
2be3c66a2d Platform/Win32/Win32Display: implement the new setIcon() with pixel array. 2020-11-03 11:29:14 +01:00
60653509fa source/Platform/PlatformDisplay.h: change setIcon() parameters to take a pixel array instead of filename 2020-11-03 11:29:14 +01:00
a72ebf3d15 include/Spectre/Graphics/Texture.h: indentation fix. 2020-10-23 11:11:41 +02:00
5d391ef70c source/Graphics/Texture.cpp: minor fix. 2020-10-23 11:11:41 +02:00
fadd24fa51 include/Spectre/Graphics/PixelFormat.h: Some documentation 2020-10-23 11:11:41 +02:00
391d617117 Adding assets/debug_icon.ico 2020-10-23 11:11:41 +02:00
acf96a0971 source/Graphics/ImageLoader.cpp: load .ico files. 2020-10-23 11:11:41 +02:00
37d495fca3 Adding source/Graphics/Image/IcoFormat 2020-10-23 11:11:41 +02:00
b78531a570 Adding source/Graphics/Image/Format/ico.h 2020-10-23 11:09:30 +02:00
02912b857b source/Graphics/Image.cpp: in setPixels() do proper conversion. 2020-10-22 16:53:20 +02:00
4f04a8e7c9 include/Spectre/Graphics/PixelFormat.h: Define 32BRG and 32BRGA formats. 2020-10-22 16:10:15 +02:00
f7fcc2633c Graphics/Image: dont store PixelFormat, instead define a new enum for number of channels.
The image class has a strict internal representation so we dont need "format".
PixelFormat enum can be passed to functions that modify the pixel data (like setPixels()) so that a proper convertion can be done.
2020-10-22 13:06:19 +02:00
6f9b33be8f Adding Spectre/System/ByteOrder 2020-10-21 13:02:03 +02:00
b0d14b91e0 Adding Input Example. 2020-10-16 19:38:05 +02:00
1332921174 examples/events/EventsExample.cpp: handle mouse button events also. 2020-10-16 19:37:56 +02:00
c09febc4d8 examples/events/EventsExample.cpp: store std::string instead of char pointer.
Some compilers (ehm, microsoft) returns a temporary variable for event.key.getKeyName() that is only valid during the statement and not scope.

Fix this by storing std::string instead. So the object's lifetime is the entire if statement.
2020-10-14 13:50:52 +02:00
49f42e98f4 Adding Event example 2020-10-14 13:21:16 +02:00
ec8eb971a5 engine.build.lua: define "SPECTRE_DEBUG" when building in debug mode. 2020-10-13 18:07:29 +02:00
1a6cee0b25 Spectre/System/Log: adding debug method. 2020-10-13 18:07:29 +02:00
eb1f6303f1 include/Spectre/Input/InputDevice.h: typo fix. 2020-09-24 18:30:53 +02:00
32fddcd99d include/Spectre/Input/Mouse.h: don't use relative path in include. 2020-09-24 17:39:48 +02:00
f86a1ae90c Merge branch 'maint-platform' into dev 2020-09-24 17:17:12 +02:00
18880ef17e source/Game.cpp: minor fixes. 2020-09-24 16:33:30 +02:00
976ddecd10 source/Game.cpp: in run() exit if graphics could not be initialized. 2020-09-23 16:56:28 +02:00
2a1851efb5 Game: remove setup() method. do setup in run() instead. 2020-09-23 16:55:42 +02:00
d58c49421e source/Graphics/OpenGL.cpp: in init() return false if display fails to be created. 2020-09-23 12:41:22 +02:00
0f08f10a0d source/Game.cpp: don't need to call setClearColor() here. it is done as part of the graphics module setup. 2020-09-23 00:00:31 +02:00
2c76d3bc87 source/Platform/Win32/Win32GLContext.cpp: no need to have our own wgl extension loader (fixed in latest glad2) 2020-09-21 18:00:08 +02:00
d8af100691 GLAD WGL: Update to new version. 2020-09-21 17:59:14 +02:00
a96e78bca5 source/Platform/Win32/Win32GLContext.cpp: in createGLContext() check return value from ensureExtensionsLoaded() 2020-09-20 16:46:51 +02:00
e3c01d4897 source/Platform/Win32/Win32GLContext.cpp: make ensureExtensionsLoaded() return bool. 2020-09-20 16:45:58 +02:00
6805e392a7 source/Platform/Win32/Win32GLContext.cpp: in createGLContext() delete temporary context as the last step. 2020-09-20 16:42:44 +02:00
afc1491718 Merge branch '6-abstract-filesystem' into dev 2020-09-17 09:50:06 +02:00
92a561648e
Platform/Win32/Win32Input.cpp: remove Win32InputMsgBuffer 2020-02-15 15:41:53 +01:00
a4a691fd48
Math/Transform.cpp: use transform/scale/ratation functions from Math.h 2020-02-14 23:31:15 +01:00
a6e6b915e6
Math/Math: Remove getTranslate(), getUpVector() and getForwardVector() as they are not used. 2020-02-12 19:54:52 +01:00
532c6dafaf
Math/Math: translate/scale functions should not accept vectors, but rather individual parameters.
This is "low level" functions. Used by other math classes/functions.
2020-02-12 19:42:50 +01:00
18ea713445
Math/Transform.cpp: minor fixes. 2020-02-12 19:29:02 +01:00
76d175ffd9
Math/Transform: rename multiply() to combine() 2020-02-12 19:27:41 +01:00
1194128627
Math/Transform.cpp: indent fixes. 2020-02-12 19:20:20 +01:00
72e1bfdade
Math: indent fixes. 2020-02-12 08:54:03 +01:00
c0f44016c6
Math/Vector2: inline toString() 2020-02-12 08:52:08 +01:00
eef2690ada
source/Platform/Win32/Win32Mouse.cpp: in isButtonDown() use SM_SWAPBUTTON to determine if buttons are swapped or not. 2020-02-02 18:58:06 +01:00
e888626b03
Update icon. 2020-02-02 09:56:03 +01:00
24fa1e140e
source/Platform/Win32/Win32Keyboard.cpp: define LAlt and RAlt keys. 2020-02-02 00:42:00 +01:00
3364b921de
include/Spectre/Input/Keyboard.h: remove NumpadEnter (this is usually the same as regular enter). 2020-02-02 00:38:38 +01:00
7c6cf45d3c
include/Spectre/Input/Keyboard.h: Fix CamelCase for some enum values. 2020-02-02 00:34:13 +01:00
e0d95a1135
include/Spectre/Input/Mouse.h: add getPositionAbs() to the interface. 2020-02-01 22:40:14 +01:00
fa0fc72eb0
Platform/Win32/Win32Mouse: add getAbsPosition() and update the position variables in update() 2020-02-01 22:31:44 +01:00
290c6643f5
Platform/Win32/Win32Mouse: implement isButtonDown() using GetAsyncKeyState() and remove m_state and m_tracked. 2020-02-01 22:28:37 +01:00
c7c1ff68fd
Platform/Win32: remove Win32MsgBuffer 2020-02-01 16:43:10 +01:00
cdaed77bf7
Input: remove InputEvent and InputListener and related code. Those are handled in System/Event 2020-02-01 15:50:10 +01:00
3c209ba01b
Platform/Win32/Win32Mouse: skip Win32MsgBuffer and handle event directly in handleMessage() 2020-02-01 15:50:09 +01:00
2e9701a15b
Platform/Win32/Win32Keyboard: implement isKeyDown() using GetAsyncKeyState() and remove m_bufState and m_focus. 2020-02-01 15:50:08 +01:00
390be8f740
Platform/Win32/Win32Keyboard: skip Win32MsgBuffer and handle event directly in handleMessage() 2020-02-01 15:50:06 +01:00
e75d373933
Game: call MessageHandler::onEvent() 2020-02-01 15:50:05 +01:00
81b64e18d4
Game: add getMessageHandler() method. 2020-02-01 15:50:03 +01:00
a30fd37032
System/MessageHandler: Make this class useful by implementing EventListener and also add a vector of listeners with register/unregister methods. 2020-02-01 15:50:02 +01:00
cd32d0b7c2
Adding System/EventListener 2020-02-01 15:50:01 +01:00
10198484e7
System/SystemEvent: Merge with Input/InputEvent into just Event. 2020-02-01 15:49:59 +01:00
858e721451
source/Platform/PlatformEventQueue.h: need to forward declare sp::SysEvent 2020-02-01 15:49:57 +01:00
ffb97d2b3a
source/Platform/Win32/Win32Display.cpp: No need to include Spectre/System/SystemEvent.h 2020-02-01 15:49:56 +01:00
4d54968f83
Display/Display: No need to include System/SystemEvent. 2020-02-01 15:49:55 +01:00
24c3f14c8c
include/Spectre/Input/InputEvent.h: Move Key::Type to Keyboard class 2020-02-01 15:49:53 +01:00
762d26f368
include/Spectre/Input/InputEvent.h: Move MouseButton::Type to Mouse class. 2020-02-01 15:49:52 +01:00
b2ca926a00
include/Spectre/Input/InputDevice.h: do not include "InputModule.h" 2020-02-01 15:49:50 +01:00
f526b598e2
source/Platform/PlatformApplication.h: remove update(). platform event queue is handled in MessageQueue class. 2020-02-01 15:49:49 +01:00
801ab1033f
source/Game.cpp: in processEvents() no need to call platform->update() anymore. (messages are pumped in MessageQueue) 2020-02-01 15:49:48 +01:00
fb58490bfe
System/MessageQueue: Use PlatformEventQueue 2020-02-01 15:49:46 +01:00
e6718e7ef1
Adding source/Platform/PlatformEventQueue.h 2020-02-01 15:49:45 +01:00
da76c4b4d1
Adding Win32EventQueue 2020-02-01 15:49:42 +01:00
3477b72371
source/Input/InputModule.cpp: should not call m_platform->update() in update(). 2020-02-01 15:49:39 +01:00
52fe72f31f
examples/text/Game.h: no need to include Vector2 2020-02-01 15:48:33 +01:00
a1e4f9347a
examples/text/Game.h: no need to extend sp::InputListener 2020-02-01 15:48:24 +01:00
9e581ef859
source/Graphics/ImageLoader.h: remove unimplemented methods. 2020-01-19 22:01:26 +01:00
8a3b5a17d8
Graphics/ImageLoader: move decode() to loadFromMemory() 2020-01-19 22:00:56 +01:00
29749e945a
Remove FT2 lib files (we compile our own). 2020-01-19 21:57:50 +01:00
1a43bcd77a
source/Graphics/ImageLoader.cpp: use the new File API 2020-01-19 21:43:07 +01:00
dc04a12922
Spectre/System/File: add getErrorMessage() 2020-01-19 21:43:07 +01:00
59a4f1347a
source/Graphics/Shader.cpp: use the new File API 2020-01-19 21:43:07 +01:00
624a979356
Spectre/System/File: implement File class. 2020-01-19 21:43:10 +01:00
1a218532c0
source/System/File.cpp: move path stuff to Path.cpp 2020-01-10 00:45:11 +01:00
66f3bb30d9
bam: Move library build to engine.build.lua file. 2020-01-07 07:11:02 +01:00
a19944437b
bam: Define engine library as default target and add "examples" pseudo target. 2020-01-07 06:57:56 +01:00
e4c086a1eb
bam: move examples stuff to it's own file. 2020-01-07 06:55:24 +01:00
f3cada7ac8
bam.lua: use CopySettings() function. 2020-01-07 06:35:00 +01:00
ddd41971e1
.bam/functions.lua: adding CopySettings functions 2020-01-07 06:34:40 +01:00
ce575cc122
.bam/functions.lua: whitespace fixes. 2020-01-07 06:33:50 +01:00
b564758ff6
bam.lua: call TableDeepCopy() when copying global_settings as just assigning it to a variable only creates a reference. 2020-01-07 06:28:36 +01:00
b53ddfb3fa
vendor/FreeType2/build.lua: Pass full path to include directory (as it's relative to root dir). 2020-01-07 06:26:51 +01:00
cb2ea423dc
FreeType2: move out our own config to ftspectre directory (makes it esier to upgrade FT). 2020-01-07 06:18:31 +01:00
f5b7fa8178
FreeType2: skip static lib, build custom source into libspectre. 2020-01-07 05:51:23 +01:00
093149e72c
FontEngine/FreeType: move libWrapper to its own compile unit. 2020-01-06 00:38:06 +01:00
f72178ffd0
FontEngine: remove hinting (exists in FontDescripion class) and let child classes handle it. 2020-01-06 00:25:01 +01:00
6e14209aae
Font: add FontDescription class. 2020-01-06 00:18:07 +01:00
2dd1187ff2
Font: move Glyph to it's own header. 2020-01-05 23:40:25 +01:00
5c4eea4ae1
Font: rename Driver stuff to Engine and move subdirectory 2020-01-05 23:31:45 +01:00
8b96338e24
include/Spectre/Graphics/Font.h: Minor typo fix. 2020-01-05 23:20:00 +01:00
2a111a237d
Move OpenGL headers from API to implementation.
We don't want to expose any OpenGL functions to client code. Because if we do, there is a chance we break client code if we switch implementation (Direct3D).
2020-01-03 20:30:08 +01:00
1dc0ecf563
Update Readme 2020-01-02 05:06:17 +01:00
8c9c1e0997
remove libpng and libjpeg (we use stb instead) 2020-01-02 05:05:29 +01:00
471 changed files with 132355 additions and 9320 deletions

View file

@ -1,77 +0,0 @@
local _systems = {
"Win32",
-- "Linux"
}
-- Returns a string of all supported systems
function supported_systems()
return table.concat(_systems, ', ')
end
-- Detect what system we currently are on.
function system()
local win = os.getenv('OS')
if win:lower():match('windows') then
return _systems[1]
end
return nil
end
-- Defines a module
-- path: base path to source files.
-- src: table of source files.
function Module(path, src)
local r = {}
for k, v in pairs(src) do
r[k] = path .. "/" .. v
end
return r
end
-- Copy a directory src to dst
-- src = "path/to/a", dest = "path/to/b" -> the whole content
-- of "a" will be copied to "path/to/b"
function CopyDir(dst, src)
local r = {}
local base = PathDir(src)
local files = CollectRecursive(Path(src) .. "/*")
for k, v in pairs(files) do
local rdir = PathDir(v:sub(base:len() + 1))
r[k] = CopyToDirectory(PathJoin(dst, rdir), v)
end
return r
end
-- Build example binary.
-- This function Imports "examples/<name>/bam.lua"
-- that file must define a table "src" that contains the source files.
function BuildExample(settings, name, dependencies)
Import("examples/" .. name .. "/bam.lua")
exe = Link(settings, "examples/" .. name, Compile(settings, src))
if dependencies ~= nil and #dependencies > 0 then
AddDependency(exe, dependencies)
end
return exe
end
-- Build examples binaries.
-- Just a wrapper for BuildExample. taking a table of names instead.
function BuildExamples(settings, names, dependencies)
local r = {}
for i = 1, #names do
r[i] = BuildExample(settings, names[i], dependencies)
end
return r
end

6
.clang-format Normal file
View file

@ -0,0 +1,6 @@
BasedOnStyle: LLVM
UseTab: Always
TabWidth: 8
IndentWidth: 8
BreakBeforeBraces: Linux

4
.gitattributes vendored
View file

@ -5,8 +5,12 @@
*.sh text eol=lf *.sh text eol=lf
*.ini text eol=lf *.ini text eol=lf
*.xml text eol=lf *.xml text eol=lf
*.h eol=lf
*.hpp eol=lf
*.hxx eol=lf
*.c text eol=lf *.c text eol=lf
*.cpp text eol=lf *.cpp text eol=lf
*.cxx text eol=lf
*.htext eol=lf *.htext eol=lf
*.txt text eol=lf *.txt text eol=lf
*.glsl text eol=lf *.glsl text eol=lf

13
.gitignore vendored
View file

@ -1,7 +1,10 @@
# Build system related files
build/ build/
.bam/*
!.bam/*.lua # LSP related files
.ccls-cache/
compile_commands.json
# Thumbnail databases (Windows) # Thumbnail databases (Windows)
Thumbs.db Thumbs.db
@ -25,6 +28,12 @@ Thumbs.db
!vsproj/* !vsproj/*
# Visual Studio Code
.vscode/
# Debug files
*.pdb
# Compiled Object files # Compiled Object files
*.slo *.slo
*.lo *.lo

42
CMakeLists.txt Normal file
View file

@ -0,0 +1,42 @@
# ------------------------------------------------------------
#
# Spectre main Cmake config
#
# ------------------------------------------------------------
cmake_minimum_required(VERSION 3.15)
cmake_policy(SET CMP0091 NEW)
# set the project name
project(Spectre
VERSION 0.0.1
DESCRIPTION ""
HOMEPAGE_URL "")
set( CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_CURRENT_LIST_DIR}/cmake" )
include(GNUInstallDirs)
# Compiler
# -------------------------------
set(CMAKE_CXX_STANDARD 11)
set(CMAKE_CXX_STANDARD_REQUIRED True)
set(CMAKE_CXX_EXTENSIONS OFF)
if (MSVC)
add_definitions("/EHsc -D_CRT_SECURE_NO_WARNINGS")
# Staticly link with MSVCR
set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$<CONFIG:Debug>:Debug>")
endif (MSVC)
# Variables
# -------------------------------
# Include engine
include(engine.cmake)
# Include examples
add_subdirectory(examples)

View file

@ -1,3 +1,41 @@
# Spectre 2D Engine # Spectre 2D Engine
A simple 2D Game engine from scratch! A simple 2D Game engine from scratch!
## Compiling
This project uses [cmake](https://cmake.org) build system
(Version 3.15 or greater) to compile the engine.
### Linux with make.
```sh
$ mkdir build
$ cd build
$ cmake .. -G "Unix Makefiles"
$ make
```
### Windows using NMake
```sh
$ mkdir build
$ cd build
$ cmake .. -G "NMake Makefiles"
$ nmake
```
### Or the best way (in my opinion)
install [Ninja](https://ninja-build.org) and run
```sh
$ mkdir build
$ cd build
$ cmake .. -G Ninja
$ ninja
```
The build will produce `spectre.lib` in the `build` directory that
should be used when linking.
## Author
Henrik Hautakoski - [henrik.hautakoski@gmail.com](mailto:henrik.hautakoski@gmail.com)

Binary file not shown.

Before

Width:  |  Height:  |  Size: 31 KiB

After

Width:  |  Height:  |  Size: 101 KiB

Before After
Before After

BIN
assets/debug_icon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

248
bam.lua
View file

@ -1,248 +0,0 @@
--------------------------------
-- --
-- Spectre build config --
-- --
--------------------------------
Import(".bam/functions.lua")
CheckVersion("0.5")
--------------------------------
-- --
-- Environment Setup --
-- --
--------------------------------
-- OS Detection
TARGET_OS = system()
if TARGET_OS == nil then
print ("System not supported" )
print ("Supported systems are: " .. supported_systems() )
return 1
end
-- paths used when building.
paths = {
build = "build",
object = "obj",
examples = "examples"
}
--------------------------------
-- --
-- Global Build Settings --
-- --
--------------------------------
global_settings = NewSettings();
-- Build type
--------------------------------
global_settings.debug = 1
global_settings.optimize = 0
if ScriptArgs.type ~= nil and ScriptArgs.type:match("^release") then
global_settings.debug = 0
if ScriptArgs.type == "release-fast" then
global_settings.optimize = 1
end
end
-- Output configuration
--------------------------------
global_settings.lib.prefix = Path(paths.build) .. "/"
global_settings.link.Output = function(settings, input)
return Path(PathJoin(paths.build, input))
end
global_settings.cc.Output = function(settings, input)
return Path(PathJoin(PathJoin(paths.build, paths.object), PathBase(input)))
end
-- Compiler configuration
--------------------------------
-- MSVC complains about exception handler without this flag.
if global_settings.cc.exe_cxx == "cl" then
global_settings.cc.flags:Add('/EHsc')
end
--------------------------------
-- --
-- Engine configuration --
-- --
--------------------------------
local settings = global_settings
settings.cc.includes:Add("include/")
settings.cc.includes:Add("source/")
-- FreeType2
if TARGET_OS == "Win32" then
settings.cc.includes:Add("vendor/FreeType2/include")
else
settings.cc.includes:Add("/usr/include/freetype2")
end
-- STB
settings.cc.includes:Add("vendor/stb/include")
-- Source files
--------------------------------
local system_module = Module("source/System", {
"File.cpp",
"MessageHandler.cpp",
"MessageQueue.cpp",
"SystemEvent.cpp",
"Log.cpp"
})
local platform_common_module = Module("source/Platform", {
"PlatformDisplay.cpp"
})
-- if TARGET_OS == "Win32" then -- Needed later for unix.
platform_spec_module = Module("source/Platform/Win32", {
"Win32Application.cpp",
"Win32Display.cpp",
"Win32GLContext.cpp",
"Win32Input.cpp",
"Win32Internal.cpp",
"Win32Keyboard.cpp",
"Win32Misc.cpp",
"Win32Mouse.cpp",
"Win32MsgBuffer.cpp",
"Win32System.cpp",
"glad_wgl.c"
})
--end
local input_module = Module("source/Input", {
"InputDevice.cpp",
"InputEvent.cpp",
"InputListener.cpp",
"InputModule.cpp",
"Keyboard.cpp",
"Mouse.cpp"
})
local display_module = Module("source/Display", {
"Display.cpp",
"DisplayDescription.cpp",
"DisplayMode.cpp",
"GLContext.cpp"
})
local graphics_module = Module("source/Graphics", {
-- Primitives
"Vertex2D.cpp",
"Transformable.cpp",
"Sprite.cpp",
-- Rendering
"BatchRenderer2D.cpp",
"DefaultRenderer2D.cpp",
"Renderable2D.cpp",
"Renderer2D.cpp",
"RenderState.cpp",
"Shader.cpp",
"ShaderProgram.cpp",
"Texture.cpp",
-- Text
"Font/FontDriver.cpp",
"Font/FreeTypeDriver.cpp",
"Font/FreeTypeError.cpp",
"Font.cpp",
"Text.cpp",
-- Image
"Image.cpp",
"ImageLoader.cpp",
"OpenGL.cpp",
"GL/glad.c",
"GL/CheckError.cpp",
})
local core_module = Module("source/Core", {
"String.cpp"
})
local math_module = Module("source/Math", {
"Color.cpp",
"Logarithm.cpp",
"Math.cpp",
"Transform.cpp"
})
local game_module = Module("source", {
"Game/FPSCounter.cpp",
"Game/GameTime.cpp",
"Game.cpp",
})
local scene_module = Module("source/Scene", {
"Camera2D.cpp"
})
-- Build target
--------------------------------
local obj = Compile(settings, {
system_module,
platform_common_module,
platform_spec_module,
input_module,
display_module,
graphics_module,
core_module,
math_module,
game_module,
scene_module
})
local libspectre = StaticLibrary(settings,
"spectre",
obj
)
--------------------------------
-- --
-- Examples --
-- --
--------------------------------
local example_settings = global_settings
-- Include spectre headers.
example_settings.cc.includes:Add("include/")
-- Link with spectre.
example_settings.link.extrafiles:Add(libspectre)
if TARGET_OS == "Win32" then
-- Windows needs to link against these.
example_settings.link.libs:Add("opengl32", "gdi32", "user32")
-- Staticly link freetype on windows.
example_settings.link.libpath:Add("vendor/FreeType2/lib/x86")
if example_settings.debug > 0 then
example_settings.link.libs:Add("freetype-d-s")
else
example_settings.link.libs:Add("freetype-s")
end
end
-- For now, to get examples working
-- we copy the whole assets directory.
assets = CopyDir(PathJoin(paths.build, paths.examples), "assets")
BuildExamples(example_settings, {
"text"
}, assets)

7
cmake/Macros.cmake Normal file
View file

@ -0,0 +1,7 @@
function(spectre_example NAME)
add_executable(example_${NAME} ${ARGN})
target_link_libraries(example_${NAME} PRIVATE Spectre)
set_target_properties(example_${NAME} PROPERTIES VS_GLOBAL_IgnoreImportLibrary "true")
#set_target_properties(${NAME} PROPERTIES RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
endfunction()

View file

@ -0,0 +1,31 @@
# This script provides the spectre as an import target
# ----------------------------------------------------------
#
# Use find_package() so cmake will find spectre:
#
# find_package(spectre) # No specific version
# find_package(spectre REQUIRED) # No specific version, but the library must be found.
# find_package(spectre 0.1) # any 0.1.x, but the library is optional.
# find_package(spectre 0.1.0) # 0.1.0 or greater, but the library is optional.
#
# Then you just link your target with spectre:
#
# target_link_libraries( ${PROGRAM_EXE} PUBLIC spectre )
#
# if you do not specify REQUIRED. you must check the variable spectre_FOUND
# and and only link to it if it's defined:
#
# if (spectre_FOUND)
# ...
# target_link_libraries( ${PROGRAM_EXE} PUBLIC spectre )
# ..
# endif()
@PACKAGE_INIT@
find_package(OpenGL)
set_and_check( SPECTRE_ASSETS "@PACKAGE_ASSETS_DIR@" )
include("${CMAKE_CURRENT_LIST_DIR}/SpectreTargets.cmake")
check_required_components(Spectre)

240
engine.cmake Normal file
View file

@ -0,0 +1,240 @@
# ------------------------------------------------------------
#
# Engine library build config
#
# ------------------------------------------------------------
# Source
# ------------------------------------------------------------
set( ENGINE_SRC
# Core
source/Core/String.cpp
# System
source/System/ByteOrder.cpp
source/System/Event.cpp
source/System/EventListener.cpp
source/System/File.cpp
source/System/Log.cpp
source/System/MessageHandler.cpp
source/System/MessageQueue.cpp
source/System/Path.cpp
source/System/Stopwatch.cpp
source/System/Log/FileWriter.cpp
# Platform
source/Platform/PlatformApplication.cpp
source/Platform/PlatformWindow.cpp
# Math
source/Math/Color.cpp
source/Math/Logarithm.cpp
source/Math/Time.cpp
source/Math/Transform.cpp
source/Math/Math.cpp
# Input
source/Input/InputDevice.cpp
source/Input/InputModule.cpp
source/Input/Keyboard.cpp
source/Input/Mouse.cpp
# Window
source/Window/Window.cpp
source/Window/WindowDescription.cpp
source/Window/DisplayMode.cpp
source/Window/GLWindow.cpp
source/Window/GLContext.cpp
# GfxDriver
source/GfxDriver/ShaderProgram.cpp
# Graphics
source/Graphics/BatchRenderer2D.cpp
source/Graphics/DefaultRenderer2D.cpp
source/Graphics/Renderable2D.cpp
source/Graphics/Renderer2D.cpp
source/Graphics/RenderState.cpp
source/Graphics/Sprite.cpp
source/Graphics/Text.cpp
source/Graphics/Texture.cpp
source/Graphics/Transformable.cpp
source/Graphics/Vertex2D.cpp
source/Graphics/Graphics.cpp
# Graphics - Font
source/Graphics/Font/Engine/FreeTypeEngine.cpp
source/Graphics/Font/Engine/FreeTypeError.cpp
source/Graphics/Font/Engine/FreeTypeLib.cpp
source/Graphics/Font/FontDescription.cpp
source/Graphics/Font.cpp
# Graphics - Image
source/Graphics/Image/IcoFormat.cpp
source/Graphics/ImageLoader.cpp
source/Graphics/PixelFormat.cpp
source/Graphics/Image.cpp
# Graphics - GL
source/Graphics/GL/glad.c
source/Graphics/GL/CheckError.cpp
# Scene
source/Scene/Camera2D.cpp
# Game
source/Game/FPSCounter.cpp
source/Game/GameTime.cpp
source/Game.cpp
)
set(ENGINE_GFXDRIVER_OPENGL_SRC
source/GfxDriver/OpenGL/OpenGLDrv.cpp
source/GfxDriver/OpenGL/OpenGLShaderProgram.cpp
)
set(ENGINE_PLATFORM_WIN32_SRC
source/Platform/Win32/Win32Application.cpp
source/Platform/Win32/Win32Window.cpp
source/Platform/Win32/Win32GLContext.cpp
source/Platform/Win32/Win32Input.cpp
source/Platform/Win32/Win32Internal.cpp
source/Platform/Win32/Win32Keyboard.cpp
source/Platform/Win32/Win32Misc.cpp
source/Platform/Win32/Win32Mouse.cpp
source/Platform/Win32/Win32EventQueue.cpp
source/Platform/Win32/Win32System.cpp
source/Platform/Win32/glad_wgl.c
)
set(ENGINE_PLATFORM_UNIX_SRC
source/Platform/Unix/UnixApplication.cpp
source/Platform/Unix/UnixSystem.cpp
source/Platform/Unix/UnixMisc.cpp
# GLContext
source/Platform/Unix/GLXContext.cpp
source/Platform/Unix/glad_glx.c
# X11
source/Platform/Unix/Xlib.cpp
source/Platform/Unix/Xrandr.cpp
source/Platform/Unix/X11Window.cpp
source/Platform/Unix/X11Input.cpp
source/Platform/Unix/X11Keyboard.cpp
source/Platform/Unix/X11Mouse.cpp
source/Platform/Unix/X11EventQueue.cpp
source/Platform/Unix/X11WindowEventHandler.cpp
)
# Library
# ------------------------------------------------------------
add_library( Spectre STATIC ${ENGINE_SRC} )
target_include_directories(Spectre
PUBLIC
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>
PRIVATE
${CMAKE_CURRENT_LIST_DIR}/source
)
if (WIN32)
target_compile_options(Spectre PRIVATE "-DSPECTRE_PLATFORM_WIN=1")
else()
target_compile_options(Spectre PRIVATE "-DSPECTRE_PLATFORM_UNIX=1")
endif()
# Dependancies
# ------------------------------------------------------------
# Platform specific
if (WIN32)
target_sources(Spectre PRIVATE ${ENGINE_PLATFORM_WIN32_SRC})
else()
target_sources(Spectre PRIVATE ${ENGINE_PLATFORM_UNIX_SRC})
# Unix needs to link against X11
find_package(X11 REQUIRED COMPONENTS Xrandr)
target_link_libraries(Spectre PRIVATE X11::X11 X11::Xrandr)
endif (WIN32)
# Select graphics API
# Only OpenGL Driver for now
target_sources(Spectre PRIVATE ${ENGINE_GFXDRIVER_OPENGL_SRC})
if (WIN32)
find_package(OpenGL REQUIRED COMPONENTS OpenGL)
target_link_libraries(Spectre PRIVATE OpenGL::GL)
else()
find_package(OpenGL REQUIRED COMPONENTS OpenGL GLX)
target_link_libraries(Spectre PRIVATE OpenGL::OpenGL OpenGL::GLX)
endif()
# FreeType
add_subdirectory(vendor/FreeType2)
target_sources(Spectre PRIVATE $<TARGET_OBJECTS:freetype>)
target_include_directories(Spectre PRIVATE $<TARGET_PROPERTY:freetype,INTERFACE_INCLUDE_DIRECTORIES>)
# STB
target_include_directories(Spectre PRIVATE ${CMAKE_CURRENT_LIST_DIR}/vendor/stb/include)
# Install
# ------------------------------------------------------------
# Includes
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/include/Spectre TYPE INCLUDE)
# Assets
install(DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/assets DESTINATION ${CMAKE_INSTALL_DATADIR})
# Install - CMake targets
# ------------------------------------------------------------
install(TARGETS Spectre
EXPORT SpectreTargets
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
INCLUDES DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(EXPORT SpectreTargets
FILE SpectreTargets.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Spectre
)
# Build directory target
export(EXPORT SpectreTargets
FILE "${CMAKE_CURRENT_BINARY_DIR}/SpectreTargets.cmake"
)
# CMake config
# ------------------------------------------------------------
# Version
include(CMakePackageConfigHelpers)
write_basic_package_version_file(SpectreConfigVersion.cmake COMPATIBILITY SameMajorVersion)
set (ASSETS_DIR ${CMAKE_INSTALL_DATADIR}/assets)
configure_package_config_file(cmake/SpectreConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/cmake/SpectreConfig.cmake
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Spectre
PATH_VARS ASSETS_DIR)
install(FILES ${CMAKE_CURRENT_BINARY_DIR}/cmake/SpectreConfig.cmake
${CMAKE_CURRENT_BINARY_DIR}/SpectreConfigVersion.cmake
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/Spectre)
# CMake config - build directory
# ------------------------------------------------------------
set (ASSETS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/assets)
configure_package_config_file(cmake/SpectreConfig.cmake.in
${CMAKE_CURRENT_BINARY_DIR}/SpectreConfig.cmake
INSTALL_DESTINATION ${CMAKE_CURRENT_BINARY_DIR}
INSTALL_PREFIX ${CMAKE_CURRENT_SOURCE_DIR}
PATH_VARS ASSETS_DIR)

7
examples/CMakeLists.txt Normal file
View file

@ -0,0 +1,7 @@
include("Macros")
add_subdirectory(window)
add_subdirectory(events)
add_subdirectory(input)
add_subdirectory(text)

View file

@ -0,0 +1,7 @@
#find_package(Spectre REQUIRED)
spectre_example(events
main.cpp
EventsExample.cpp
)

View file

@ -0,0 +1,34 @@
#include <Spectre/System/MessageHandler.h>
#include <Spectre/System/Log.h>
#include "EventsExample.h"
void EventsExample::init()
{
getMessageHandler()->registerListener(this);
}
void EventsExample::onEvent(const sp::Event& event)
{
if (event.type == sp::Event::Key) {
std::string name = event.key.getKeyName();
const char* pressed = event.key.pressed ? "pressed" : "released";
sp::Log::info("Key: %s %s", name.c_str(), pressed);
}
if (event.type == sp::Event::MouseButton) {
std::string name = event.mouseButton.getName();
const char* pressed = event.mouseButton.pressed ? "pressed" : "released";
sp::Log::info("MouseButton: %s %s", name.c_str(), pressed);
}
}
void EventsExample::update(double dt)
{
// Nothing to do
}
void EventsExample::render()
{
// Nothing to do
}

View file

@ -0,0 +1,22 @@
#ifndef EVENTS_EXAMPLE_H
#define EVENTS_EXAMPLE_H
#include <Spectre/Game.h>
#include <Spectre/System/EventListener.h>
class EventsExample : public sp::Game, sp::EventListener
{
public :
void onEvent(const sp::Event& event);
protected :
void init();
void update(double dt);
void render();
};
#endif /* EVENTS_EXAMPLE_H */

11
examples/events/main.cpp Normal file
View file

@ -0,0 +1,11 @@
#include "EventsExample.h"
int main(int argc, char **argv) {
EventsExample game;
game.run();
return 0;
}

View file

@ -0,0 +1,7 @@
#find_package(Spectre REQUIRED)
spectre_example(input
main.cpp
InputExample.cpp
)

View file

@ -0,0 +1,99 @@
#include <Spectre/Input/InputModule.h>
#include <Spectre/Input/Keyboard.h>
#include <Spectre/Input/Mouse.h>
#include <Spectre/System/MessageHandler.h>
#include <Spectre/System/Log.h>
#include <Spectre/Graphics/BatchRenderer2D.h>
#include <Spectre/System/Log.h>
#include "InputExample.h"
void InputExample::init()
{
m_renderer = new sp::BatchRenderer2D();
getMessageHandler()->registerListener(this);
m_tux_texture.create("assets/textures/tux.png");
m_kb_sprite.setTexture(m_tux_texture);
m_kb_sprite.setColor(sp::Color::Green);
m_kb_sprite.setSize(sp::vec2f(100, 100));
m_mouse_sprite.setTexture(m_tux_texture);
m_mouse_sprite.setColor(sp::Color::Red);
m_mouse_sprite.setSize(sp::vec2f(100, 100));
m_mouse_sprite.setPosition(sp::vec2f(50, 50));
m_mouse_event_sprite.setTexture(m_tux_texture);
m_mouse_event_sprite.setColor(sp::Color::Blue);
m_mouse_event_sprite.setSize(sp::vec2f(100, 100));
m_mouse_event_sprite.setPosition(sp::vec2f(50, 50));
m_right_mouse_down = false;
m_renderer->setCamera(m_camera);
}
void InputExample::update(double dt)
{
sp::Keyboard* keyboard = getInput()->getKeyboard();
sp::Mouse* mouse = getInput()->getMouse();
double delta = 0.3 * dt;
// Handle keyboard input.
if (keyboard->isKeyDown(sp::Keyboard::Left)) {
m_kb_sprite.move(sp::vec2f(-delta, 0));
} else if (keyboard->isKeyDown(sp::Keyboard::Right)) {
m_kb_sprite.move(sp::vec2f( delta, 0));
}
if (keyboard->isKeyDown(sp::Keyboard::Up)) {
m_kb_sprite.move(sp::vec2f(0, -delta));
} else if (keyboard->isKeyDown(sp::Keyboard::Down)) {
m_kb_sprite.move(sp::vec2f(0, delta));
}
// Handle mouse input.
if (mouse->isButtonDown(sp::Mouse::Left)) {
m_mouse_sprite.setPosition(mouse->getPosition());
}
}
void InputExample::onSizeChanged(sp::Window* Window, int width, int height)
{
}
void InputExample::onEvent(const sp::Event& event)
{
if (event.type == event.Key && !event.key.pressed) {
if (event.key.code == sp::Keyboard::G) {
getGraphics()->getWindow()->grabCursor(true);
sp::Log::info("Mouse Grabbed");
} else if (event.key.code == sp::Keyboard::U) {
getGraphics()->getWindow()->grabCursor(false);
sp::Log::info("Mouse Released");
}
} else if (event.type == event.MouseButton && event.mouseButton.button == sp::Mouse::Right) {
m_right_mouse_down = event.mouseButton.pressed;
} else if (event.type == event.MouseMove && m_right_mouse_down) {
m_mouse_event_sprite.setPosition(event.mouseMove.x, event.mouseMove.y);
}
}
void InputExample::render()
{
sp::Graphics* g = getGraphics();
g->clearBuffer();
m_renderer->begin();
m_renderer->submit(m_mouse_sprite);
m_renderer->submit(m_mouse_event_sprite);
m_renderer->submit(m_kb_sprite);
m_renderer->render();
g->swapBuffers();
}

View file

@ -0,0 +1,42 @@
#ifndef INPUT_EXAMPLE_H
#define INPUT_EXAMPLE_H
#include <Spectre/Scene/Camera2D.h>
#include <Spectre/Graphics/Texture.h>
#include <Spectre/Graphics/Sprite.h>
#include <Spectre/System/EventListener.h>
#include <Spectre/Game.h>
namespace sp {
class Renderer2D;
}
class InputExample : public sp::Game, sp::EventListener
{
protected :
void init();
void update(double dt);
void render();
void onSizeChanged(sp::Window* display, int width, int height);
void onEvent(const sp::Event& event);
private :
sp::Camera2D m_camera;
sp::Renderer2D *m_renderer;
sp::Sprite m_kb_sprite;
sp::Sprite m_mouse_sprite;
sp::Sprite m_mouse_event_sprite;
bool m_right_mouse_down;
sp::Texture m_tux_texture;
};
#endif /* INPUT_EXAMPLE_H*/

11
examples/input/main.cpp Normal file
View file

@ -0,0 +1,11 @@
#include "InputExample.h"
int main(int argc, char **argv) {
InputExample game;
game.run();
return 0;
}

View file

@ -0,0 +1,7 @@
#find_package(Spectre REQUIRED)
spectre_example(text
main.cpp
Game.cpp
)

View file

@ -2,11 +2,9 @@
#ifndef TEXT_GAME_H #ifndef TEXT_GAME_H
#define TEXT_GAME_H #define TEXT_GAME_H
#include <Spectre/Math/Vector2.h>
#include <Spectre/Input/InputListener.h>
#include <Spectre/Game.h> #include <Spectre/Game.h>
class TextExample : public sp::Game, public sp::InputListener class TextExample : public sp::Game
{ {
protected : protected :
@ -17,4 +15,4 @@ protected :
void render(); void render();
}; };
#endif /* TEXT_GAME_H*/ #endif /* TEXT_GAME_H*/

View file

@ -1,7 +0,0 @@
local base = PathDir(ModuleFilename())
src ={
base .. "/main.cpp",
base .. "/Game.cpp"
}

View file

@ -0,0 +1,7 @@
#find_package(Spectre REQUIRED)
spectre_example(window
main.cpp
WindowExample.cpp
)

View file

@ -0,0 +1,70 @@
#include <Spectre/Window/Window.h>
#include <Spectre/Graphics/BatchRenderer2D.h>
#include <Spectre/System/MessageHandler.h>
#include <Spectre/System/Log.h>
#include "WindowExample.h"
void WindowExample::init()
{
m_renderer = new sp::BatchRenderer2D();
m_mode = sp::Window::WINDOWED;
getMessageHandler()->registerListener(this);
m_texture.create("assets/textures/tux.png");
m_sprite.setTexture(m_texture);
m_sprite.setPosition(sp::vec2f(50, 50));
m_sprite.setSize(sp::vec2f(100, 100));
m_renderer->setCamera(m_camera);
}
void WindowExample::onEvent(const sp::Event& event)
{
if (event.type == sp::Event::Key && event.key.pressed == false) {
if (event.key.code == sp::Keyboard::W) {
if (m_mode == sp::Window::WINDOWED) {
m_mode = sp::Window::WINDOWEDFULLSCREEN;
sp::Log::info("Windowed Fullscreen");
} else {
m_mode = sp::Window::WINDOWED;
sp::Log::info("Windowed");
}
getGraphics()->setWindowMode(m_mode);
} else if (event.key.code == sp::Keyboard::Space) {
if (m_mode == sp::Window::WINDOWED) {
m_mode = sp::Window::FULLSCREEN;
sp::Log::info("Fullscreen");
} else {
m_mode = sp::Window::WINDOWED;
sp::Log::info("Windowed");
}
getGraphics()->setWindowMode(m_mode);
}
}
}
void WindowExample::update(double dt)
{
// Nothing to do
}
void WindowExample::render()
{
sp::Graphics* g = getGraphics();
g->clearBuffer();
m_renderer->begin();
m_renderer->submit(m_sprite);
m_renderer->render();
g->swapBuffers();
}

View file

@ -0,0 +1,34 @@
#ifndef DISPLAY_EXAMPLE_H
#define DISPLAY_EXAMPLE_H
#include <Spectre/Scene/Camera2D.h>
#include <Spectre/Graphics/Texture.h>
#include <Spectre/Graphics/Sprite.h>
#include <Spectre/System/EventListener.h>
#include <Spectre/Game.h>
class WindowExample : public sp::Game, sp::EventListener
{
public :
void onEvent(const sp::Event& event);
protected :
void init();
void update(double dt);
void render();
protected :
sp::Window::Mode m_mode;
sp::Camera2D m_camera;
sp::Renderer2D *m_renderer;
sp::Texture m_texture;
sp::Sprite m_sprite;
};
#endif /* DISPLAY_EXAMPLE_H */

11
examples/window/main.cpp Normal file
View file

@ -0,0 +1,11 @@
#include "WindowExample.h"
int main(int argc, char **argv) {
WindowExample game;
game.run();
return 0;
}

View file

@ -8,13 +8,12 @@ class NonCopyable
{ {
protected : protected :
NonCopyable() {} NonCopyable() = default;
virtual ~NonCopyable() = default;
private : // Delete Copy constructor and assignment.
NonCopyable(const NonCopyable&) = delete;
// Skip implementation to trigger compiler error. NonCopyable& operator =(const NonCopyable&) = delete;
NonCopyable(const NonCopyable&);
NonCopyable& operator =(const NonCopyable&);
}; };
} // namespace sp } // namespace sp

View file

@ -10,6 +10,8 @@ namespace sp { namespace core
{ {
// Convertion functions from standard c/c++ types. // Convertion functions from standard c/c++ types.
std::string to_string(int value);
std::string to_string(unsigned int value); std::string to_string(unsigned int value);
std::string to_string(float value); std::string to_string(float value);

View file

@ -1,80 +0,0 @@
#ifndef SPECTRE_DISPLAY_DISPLAY_H
#define SPECTRE_DISPLAY_DISPLAY_H
#include "DisplayMode.h"
#include "DisplayDescription.h"
#include <Spectre/Display/GLContext.h>
#include <Spectre/System/SystemEvent.h>
#include <string>
namespace sp {
class PlatformDisplay;
class GLContext;
class Display
{
friend class PlatformDisplay;
public :
enum Mode {
WINDOWED = 0,
FULLSCREEN = 1,
WINDOWEDFULLSCREEN = 2,
};
public :
Display();
virtual ~Display();
bool create(DisplayDescription decription);
void destroy();
void setSize(unsigned int width, unsigned int height);
void setCaption(const std::string& title);
const std::string& getCaption() const;
void setIcon(const std::string& filename);
void setDisplayMode(const DisplayMode& mode);
const DisplayMode& getDisplayMode() const;
void setVideoMode(Mode mode);
enum Mode getVideoMode() const;
void showCursor(bool value);
bool activate(bool value);
// Enable/Disable Vertical Sync.
bool enableVSync(bool value);
void swapBuffers();
protected :
void init();
void onReshape(int width, int height);
protected :
enum Mode m_fmode;
DisplayDescription m_description;
DisplayDescription m_cacheDesc;
std::string m_caption;
PlatformDisplay* m_impl;
GLContext* m_context;
};
} // namepsace sp
#endif /* SPECTRE_DISPLAY_DISPLAY_H */

View file

@ -1,34 +0,0 @@
#ifndef SPECTRE_DISPLAY_DISPLAYDESCRIPTION_H
#define SPECTRE_DISPLAY_DISPLAYDESCRIPTION_H
#include "DisplayMode.h"
namespace sp {
namespace DisplayDecorate {
enum Type {
None = 0,
Menu = 1 << 0,
Resize = 1 << 1,
Close = 1 << 2,
Default = Menu | Resize | Close,
};
};
struct DisplayDescription
{
public :
DisplayDescription();
DisplayDescription(DisplayMode mode, unsigned decoration = DisplayDecorate::Default);
public :
DisplayMode mode;
unsigned int decoration;
};
} // namespace sp
#endif /* SPECTRE_DISPLAY_DISPLAYDESCRIPTION_H */

View file

@ -3,7 +3,6 @@
#define SPECTRE_GAME_H #define SPECTRE_GAME_H
#include <Spectre/Graphics.h> #include <Spectre/Graphics.h>
#include <Spectre/Input/InputEvent.h>
#include <Spectre/Game/FPSCounter.h> #include <Spectre/Game/FPSCounter.h>
class InputModule; class InputModule;
@ -13,6 +12,8 @@ class PlatformApplication;
namespace sp { namespace sp {
namespace log { class Writer; }
class Game class Game
{ {
public : public :
@ -37,9 +38,9 @@ protected :
FPSCounter& getFpsCounter(); FPSCounter& getFpsCounter();
private : MessageHandler* getMessageHandler() const;
void setup(); private :
void gameLoop(); void gameLoop();
@ -55,9 +56,10 @@ private :
MessageHandler* m_messageHandler; MessageHandler* m_messageHandler;
log::Writer* m_log_writer;
FPSCounter m_fpsCounter; FPSCounter m_fpsCounter;
double m_timestep;
bool m_running; bool m_running;
}; };

View file

@ -2,6 +2,8 @@
#ifndef SPECTRE_FPS_COUNTER_H #ifndef SPECTRE_FPS_COUNTER_H
#define SPECTRE_FPS_COUNTER_H #define SPECTRE_FPS_COUNTER_H
#include <Spectre/System/Stopwatch.h>
// Simple FPS counter. // Simple FPS counter.
namespace sp { namespace sp {
@ -15,11 +17,11 @@ public :
// Should be called whenever a frame has been rendered. // Should be called whenever a frame has been rendered.
void addFrame(); void addFrame();
float getFPS() const; double getFPS() const;
// Set the update rate (in seconds). // Set the update rate (in seconds).
// How often the FPS should be sampled and calculated. // How often the FPS should be sampled and calculated.
void setUpdateRate(unsigned int seconds); void setUpdateRate(unsigned int rate);
// Update the internal time measurment. // Update the internal time measurment.
bool update(); bool update();
@ -29,17 +31,18 @@ public :
private : private :
// Frame counter. // Number of frames since last update.
unsigned int m_count; unsigned int m_count;
// time (in ms) // Last time we updated the counter.
unsigned int m_time; //Time m_time;
Stopwatch m_watch;
// Update rate (in ms) // Update rate (at what interval should we update)
unsigned int m_updateRate; Time m_updateRate;
// Calculated fps. // Calculated Frames per second.
float m_fps; double m_fps;
}; };
} // namespace sp } // namespace sp

View file

@ -2,6 +2,9 @@
#ifndef SPECTRE_GAME_TIME_H #ifndef SPECTRE_GAME_TIME_H
#define SPECTRE_GAME_TIME_H #define SPECTRE_GAME_TIME_H
#include <Spectre/Math/Time.h>
#include <Spectre/System/Stopwatch.h>
namespace sp { namespace sp {
class GameTime class GameTime
@ -13,12 +16,12 @@ public :
double getTimeStep() const; double getTimeStep() const;
unsigned long getElapsed() const; Time getElapsed() const;
//bool shouldTick();
bool beginFrame(); bool beginFrame();
bool shouldTick() const;
bool tick(); bool tick();
void reset(); void reset();
@ -33,15 +36,13 @@ protected :
// TODO: min,max framerates // TODO: min,max framerates
// Time(in ms) when the last update occured. Stopwatch m_watch;
unsigned long m_current;
unsigned long m_lastUpdate;
double m_acc;
// timeslice in ms. Time m_acc;
double m_slice; Time m_max_acc;
bool m_inLoop; // Timeslice.
Time m_slice;
}; };
} // namespace sp } // namespace sp

View file

@ -0,0 +1,49 @@
#ifndef SPECTRE_GFXDRIVER_GFXDRIVER_H
#define SPECTRE_GFXDRIVER_GFXDRIVER_H
#include <string>
namespace sp {
class ShaderProgram;
class GfxDriver
{
public:
enum BufferFlags {
CLEAR_BUFFER_BIT,
};
public:
// Get the name of the driver.
virtual std::string getName() const = 0;
// Get the version of the driver
virtual std::string getVersion() const = 0;
virtual std::string getVendor() const = 0;
virtual std::string getCardName() const = 0;
virtual void setViewport(int x, int y, int width, int height) = 0;
virtual void setClearColor(float r, float g, float b, float a) = 0;
virtual void clearBuffer(BufferFlags flags) = 0;
virtual void clearColorBuffer() = 0;
// Resources.
virtual ShaderProgram* createShaderProgram() = 0;
// CreateIndexBuffer()
// CreateVertexBuffer()
// Draw calls
};
} // namespace sp
#endif /* SPECTRE_GFXDRIVER_GFXDRIVER_H */

View file

@ -0,0 +1,77 @@
#ifndef SPECTRE_GFXDRIVER_SHADERPROGRAM_H
#define SPECTRE_GFXDRIVER_SHADERPROGRAM_H
#include <Spectre/Math/Matrix4.h>
#include <Spectre/Math/Color.h>
namespace sp {
enum ShaderType {
Vertex,
Fragment
};
class ShaderProgram
{
public:
virtual ~ShaderProgram();
// Load a shader program from file.
virtual bool loadFromFile(const std::string& filename);
// Load a shader from file.
virtual bool loadFromFile(const std::string& filename, ShaderType type);
// Load a shader from memory.
virtual bool loadFromMemory(const std::string& source, ShaderType type) = 0;
// Link the program.
virtual bool link() = 0;
// Returns true if the program was linked successfully
virtual bool isLinked() const;
// Enable this shader
// All shader operations after this call will affect this shader.
virtual void enable() const = 0;
// Disable this shader
// Operations will no longer affect this shader after this call.
virtual void disable() const = 0;
// Get the last shader error.
virtual std::string getLastError() const;
// ---------------------
// Variables.
// ---------------------
// TODO: Move this to a ShaderParameter class
virtual bool setMVPMatrix(const Matrix4f& matrix) = 0;
// ---------------------
// General Variables.
// ---------------------
virtual bool setAttribute(const std::string& name, float value) const = 0;
virtual bool setAttribute(const std::string& name, const Matrix4f& matrix) const = 0;
virtual bool setUniform(const std::string& name, const Matrix4f& matrix) const = 0;
virtual bool setUniform(const std::string& name, const Color& color) const = 0;
protected:
std::string m_extension;
mutable std::string m_error;
bool m_linked;
};
} // namespace sp
#endif /* SECTRE_GRAPHICS_SHADERPROGRAM_H */

View file

@ -2,7 +2,8 @@
#ifndef GRAPHICS_H #ifndef GRAPHICS_H
#define GRAPHICS_H #define GRAPHICS_H
#include <Spectre/Display/Display.h> #include <Spectre/GfxDriver/GfxDriver.h>
#include <Spectre/Window/GLWindow.h>
namespace sp { namespace sp {
@ -30,7 +31,7 @@ public :
std::string getVersion() const; std::string getVersion() const;
void setDisplayMode(Display::Mode mode); void setWindowMode(Window::Mode mode);
void setSize(int width, int height); void setSize(int width, int height);
@ -42,12 +43,19 @@ public :
void swapBuffers(); void swapBuffers();
GfxDriver* getDriver();
GLWindow* getWindow();
protected : protected :
int m_width; int m_width;
int m_height; int m_height;
Display *m_display; GLWindow *m_window;
// Graphics Driver. OpenGL/Vulcan/DirectX etc.
GfxDriver *m_gfxdrv;
}; };
} // namespace sp } // namespace sp

View file

@ -39,10 +39,10 @@ protected :
struct Batch struct Batch
{ {
RenderType type; RenderType type;
const Texture* texture; const Texture* texture;
unsigned int count; unsigned int count;
unsigned int offset; unsigned int offset;
}; };
typedef std::vector<Batch> BatchQueue; typedef std::vector<Batch> BatchQueue;
@ -67,8 +67,8 @@ protected :
unsigned short m_size; unsigned short m_size;
ShaderProgram m_textShader; ShaderProgram* m_textShader;
ShaderProgram m_spriteShader; ShaderProgram* m_spriteShader;
}; };
} // namespace } // namespace

View file

@ -7,6 +7,8 @@
namespace sp { namespace sp {
class ShaderProgram;
class DefaultRenderer2D : public Renderer2D class DefaultRenderer2D : public Renderer2D
{ {
public : public :
@ -21,7 +23,7 @@ protected :
std::vector<const Renderable2D*> m_queue; std::vector<const Renderable2D*> m_queue;
ShaderProgram m_shader; ShaderProgram* m_shader;
}; };
} // namespace } // namespace

View file

@ -1,18 +1,18 @@
#ifndef SPECTRE_GRAPHCIS_FONT_H #ifndef SPECTRE_GRAPHICS_FONT_H
#define SPECTRE_GRAPHCIS_FONT_H #define SPECTRE_GRAPHICS_FONT_H
#include <map> #include <map>
#include <vector> #include <vector>
#include <string> #include <string>
#include <Spectre/Math/Vector4.h>
#include <Spectre/Math/Vector2.h> #include <Spectre/Math/Vector2.h>
#include <Spectre/Graphics/Texture.h> #include <Spectre/Graphics/Texture.h>
#include <Spectre/Graphics/Font/Glyph.h>
namespace sp { namespace sp {
class FontDriver; class FontEngine;
// TODO: Fixup this api :) // TODO: Fixup this api :)
@ -24,16 +24,6 @@ public :
std::string name; std::string name;
}; };
struct Glyph {
vec2b size; // Width, Height of bounding box.
vec2b offset; // Offset from cursor where the box begins.
unsigned char advance;
//vec4u tex_coords;
vec2u texture_origin;
const Texture* texture; // Texture atlas.
};
Font(); Font();
~Font(); ~Font();
@ -65,7 +55,7 @@ protected :
Texture texture; Texture texture;
}; };
FontDriver *m_driver; FontEngine *m_engine;
mutable std::map<unsigned char, Glyph> m_charset; mutable std::map<unsigned char, Glyph> m_charset;
@ -77,4 +67,4 @@ protected :
} }
#endif /* SPECTRE_GRAPHCIS_FONT_H */ #endif /* SPECTRE_GRAPHICS_FONT_H */

View file

@ -0,0 +1,22 @@
#ifndef SPECTRE_GRAPHICS_FONT_FONTDESCRIPTION_H
#define SPECTRE_GRAPHICS_FONT_FONTDESCRIPTION_H
namespace sp {
class FontDescription
{
public :
void hinting(bool value = true);
bool isHintingEnabled() const;
protected :
// True if hinting is enabled. false otherwise.
bool m_hinting = true;
};
} // namespace sp
#endif /* SPECTRE_GRAPHICS_FONT_FONTDESCRIPTION_H */

View file

@ -0,0 +1,21 @@
#ifndef SPECTRE_GRAPHICS_FONT_GLYPH_H
#define SPECTRE_GRAPHICS_FONT_GLYPH_H
#include <Spectre/Math/Vector2.h>
#include <Spectre/Graphics/Texture.h>
namespace sp {
struct Glyph {
vec2b size; // Width, Height of bounding box.
vec2b offset; // Offset from cursor where the box begins.
unsigned char advance;
vec2u texture_origin;
const Texture* texture; // Texture atlas.
};
} // namespace sp
#endif // SPECTRE_GRAPHICS_FONT_GLYPH_H

View file

@ -13,13 +13,16 @@ namespace sp {
class Image class Image
{ {
public : public :
enum Channels {
Alpha,
RGB,
RGBA
};
Image(); Image();
void create(unsigned width, unsigned height, const Color& color = Color::Black); void create(unsigned width, unsigned height, const Color& color = Color::Black, enum Channels comp = Channels::RGBA);
void create(unsigned width, unsigned height, const void* pixels, PixelFormat format = PixelFormat::PF_RGBA);
void create(unsigned width, unsigned height, const void* pixels);
void create(PixelFormat format, unsigned width, unsigned height, const Color& color = Color::Black);
void create(PixelFormat format, unsigned width, unsigned height, const void* pixels);
const Vector2u& getSize() const; const Vector2u& getSize() const;
@ -27,7 +30,7 @@ public :
unsigned int getHeight() const; unsigned int getHeight() const;
unsigned int getBpp() const; unsigned int getNumChannels() const;
unsigned int getStride() const; unsigned int getStride() const;
@ -46,7 +49,7 @@ public :
Color getPixel(unsigned x, unsigned y) const; Color getPixel(unsigned x, unsigned y) const;
void setPixels(const void* pixels); void setPixels(const void* pixels, PixelFormat format = PixelFormat::PF_RGBA);
const unsigned char* getPixels() const; const unsigned char* getPixels() const;
@ -56,7 +59,7 @@ private :
Vector2u m_size; Vector2u m_size;
PixelFormat m_format; enum Channels m_channels;
std::vector<unsigned char> m_pixels; std::vector<unsigned char> m_pixels;
}; };

View file

@ -1,7 +0,0 @@
#ifndef SPECTRE_OPENGL_H
#define SPECTRE_OPENGL_H
#include <Spectre/Graphics/GL/glad.h>
#endif /* SPECTRE_OPENGL_H */

View file

@ -1,16 +1,49 @@
#ifndef SPECTRE_GRAPHICS_PIXELFORMAT_H #ifndef SPECTRE_GRAPHICS_PIXELFORMAT_H
#define SPECTRE_GRAPHICS_PIXELFORMAT_H #define SPECTRE_GRAPHICS_PIXELFORMAT_H
#include <cstdint>
namespace sp { namespace sp {
enum PixelFormat enum PixelFormat
{ {
PF_Unknown = 0, PF_Unknown = 0,
PF_RGB = 1, PF_Alpha = 1, // 8 bit alpha channel.
PF_RGBA = 2,
PF_Alpha = 3, // 1 byte alpha channel. // Byte-order formats.
// Pixels are always ordered with the first channel at the first byte, second channel at the second byte.
// ---------------------------
PF_RGB = 2, // Standard RGB: 24 bits per pixel, 8 bits are used for red, green, blue.
PF_RGBX = 3, // 32 bits per pixel, 8 bits are used for red, green, Last 8 bits are unused.
PF_RGBA = 4, // Standard RGBA: 32 bits per pixel, 8 bits are used for red, green, blue, alpha.
PF_BGR = 5, // 24 bits per pixel, 8 bits are used for blue, green, red.
PF_BGRX = 6, // 32 bits per pixel, 8 bits are used for blue, green, red. Last 8 bits are unused.
PF_BGRA = 7, // 32 bits per pixel, 8 bits are used for blue, green, red, alpha.
// Packed formats.
// ---------------------------
// 32-bit: Pixels are in ordered in 32-bit words. where the first channel is stored at the most significant byte (MSB).
// these formats are architecture dependant (litte/big-endian).
// (MSB) | byte 0 | byte 1 | byte 2 | byte 3 | (LSB)
PF_RGBX32 = 8, // | rrrr rrrr | gggg gggg | bbbb bbbb | xxxx xxxx |
PF_RGBA32 = 9, // | rrrr rrrr | gggg gggg | bbbb bbbb | aaaa aaaa |
PF_BGRX32 = 10, // | bbbb bbbb | gggg gggg | rrrr rrrr | xxxx xxxx |
PF_BGRA32 = 11, // | bbbb bbbb | gggg gggg | rrrr rrrr | aaaa aaaa |
// 24-bit (unsuppored for now)
//PF_RGB24 = 12, // | rrrr rrrr | gggg gggg | bbbb bbbb |
//PF_BGR24 = 13, // | bbbb bbbb | gggg gggg | rrrr rrrr |
// 16-bit (unsuppored for now)
//PF_RGB565 = 14, // | rrrr rggg | gggb bbbb |
//PF_RGBA5551 = 15 // | rrrr rggg | ggb bbbba |
//PF_RGBX5551 = 16 // | rrrr rggg | ggb bbbbx |
}; };
uint8_t PF_getNumChannels(enum PixelFormat format);
} // namespace } // namespace
#endif /* SPECTRE_GRAPHICS_PIXELFORMAT_H */ #endif /* SPECTRE_GRAPHICS_PIXELFORMAT_H */

View file

@ -3,7 +3,6 @@
#define SPECTRE_GRAPHICS_RENDERER2D_H #define SPECTRE_GRAPHICS_RENDERER2D_H
#include <Spectre/Graphics/Renderable.h> #include <Spectre/Graphics/Renderable.h>
#include <Spectre/Graphics/ShaderProgram.h>
#include <Spectre/Scene/Camera2D.h> #include <Spectre/Scene/Camera2D.h>
namespace sp { namespace sp {

View file

@ -1,58 +0,0 @@
#ifndef SPECTRE_GRAPHICS_SHADER_H
#define SPECTRE_GRAPHICS_SHADER_H
#include <string>
namespace sp {
class Shader
{
public :
enum Type {
Vertex,
Fragment
};
Shader(Type type, const std::string& name = "");
~Shader();
unsigned int getHandle() const;
const std::string& getName() const;
// Load shader from file.
bool loadFromFile(const std::string& file);
// Load shader from memory
bool loadFromMemory(const std::string& source);
const std::string& getError() const;
// Is this shader compiled?
bool isCompiled() const;
protected :
// Compile the shader.
// Returns true if the shader compiled without errors. false otherwise.
bool compile();
std::string fetchErrorLog();
protected :
// Type of shader. Vertex, fragment, geometry etc.
Type m_type;
unsigned int m_handle; // Shader id.
// A name for the shader (usually the filename if loaded from file).
std::string m_name;
std::string m_error;
};
} // namespace sp
#endif /* SPECTRE_GRAPHICS_SHADER_H */

View file

@ -1,90 +0,0 @@
#ifndef SPECTRE_GRAPHICS_SHADER_PROGRAM_H
#define SPECTRE_GRAPHICS_SHADER_PROGRAM_H
#include <string>
#include <Spectre/Math/Matrix4.h>
#include "Shader.h"
namespace sp {
struct Color;
class ShaderProgram
{
public :
ShaderProgram();
~ShaderProgram();
void create();
void destroy();
void addShader(const Shader& shader);
// Load a shader program from file.
//
// The following naming conventions are supported:
// <name>.glsl - Virtual file, will load all real shader files with the same name.
// <name>.vert.glsl - Vertex shader.
// <name>.frag.glsl - Fragment shader.
bool loadFromFile(const std::string& filename);
// Load a shader from file.
bool loadFromFile(const std::string& filename, Shader::Type type);
// Load a shader from memory.
bool loadFromMemory(const std::string& source, Shader::Type type);
// Link the program.
bool link();
// Returns true if the program was linked successfully
bool isLinked() const;
// Enable this shader
// All shader operations after this call will affect this shader.
void enable() const;
// Disable this shader
// Operations will no longer affect this shader after this call.
void disable() const;
// Get the last shader error.
std::string getLastError() const;
// ---------------------
// Variables.
// ---------------------
bool setMVPMatrix(const Matrix4f& matrix);
// ---------------------
// General Variables.
// ---------------------
bool setAttribute(const std::string& name, float value) const;
bool setAttribute(const std::string& name, const Matrix4f& matrix) const;
bool setUniform(const std::string& name, const Matrix4f& matrix) const;
bool setUniform(const std::string& name, const Color& color) const;
protected :
bool getAttribLoc(const std::string& name, int& loc) const;
bool getUniformLoc(const std::string& name, int& loc) const;
std::string fetchErrorLog();
protected :
unsigned int m_id; // program id
mutable std::string m_error;
};
} // namespace sp
#endif /* SPECTRE_GRAPHICS_SHADER_PROGRAM_H */

View file

@ -16,19 +16,19 @@ class Texture : public NonCopyable
{ {
public: public:
enum Filter { enum Filter {
Nearest = 0x2600, Nearest = 0x2600,
Linear = 0x2601, Linear = 0x2601,
NearestMipmapNearest = 0x2700, NearestMipmapNearest = 0x2700,
NearestMipmapLinear = 0x2702, NearestMipmapLinear = 0x2702,
LinearMipmapNearest = 0x2701, LinearMipmapNearest = 0x2701,
LinearMipmapLinear = 0x2703, LinearMipmapLinear = 0x2703,
}; };
enum WrapMode { enum WrapMode {
Repeat = 0x2901, Repeat = 0x2901,
RepeatMirror = 0x8370, RepeatMirror = 0x8370,
ClampToEdge = 0x812F, ClampToEdge = 0x812F,
ClampToBorder = 0x812D, ClampToBorder = 0x812D,
}; };
Texture(); Texture();
@ -85,9 +85,9 @@ protected :
unsigned int m_id; unsigned int m_id;
Vector2u m_size; Vector2u m_size;
PixelFormat m_format; PixelFormat m_format;
}; };
} // namespace sp } // namespace sp

View file

@ -2,10 +2,10 @@
#ifndef SPECTRE_INTPUT_DEVICE_H #ifndef SPECTRE_INTPUT_DEVICE_H
#define SPECTRE_INTPUT_DEVICE_H #define SPECTRE_INTPUT_DEVICE_H
#include "InputModule.h"
namespace sp { namespace sp {
class InputModule;
class InputDevice class InputDevice
{ {
friend class InputModule; friend class InputModule;

View file

@ -1,157 +0,0 @@
#ifndef SPECTRE_INPUT_EVENT_H
#define SPECTRE_INPUT_EVENT_H
#include <string>
#include <vector>
namespace sp {
namespace MouseButton {
enum Type {
Unknown,
Left,
Right,
Middle,
Button1,
Button2,
NUM_MBUTTONS,
};
};
namespace Key {
enum Type {
Unknown,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Zero,
Period,
Comma,
Enter,
Backspace,
Escape,
Space,
Capslock,
Up,
Down,
Left,
Right,
NUMPAD_1,
NUMPAD_2,
NUMPAD_3,
NUMPAD_4,
NUMPAD_5,
NUMPAD_6,
NUMPAD_7,
NUMPAD_8,
NUMPAD_9,
NUMPAD_0,
NUMPAD_Enter,
Home,
End,
Insert,
Delete,
PageUp,
PageDown,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
Tab,
LShift,
RShift,
LCtrl,
RCtrl,
LAlt,
RAlt,
NUM_KEYS,
};
}
typedef struct InputEvent
{
enum Type
{
None,
Key,
MouseButton,
MousePosition
};
struct KeyEvent {
Key::Type code;
bool pressed; /* true if pressed, false if released. */
std::string getKeyName() const; /* Get the key name */
};
struct MouseButtonEvent {
MouseButton::Type button;
bool pressed; /* true if pressed, false if released. */
std::string getName() const;
};
struct MouseEvent {
unsigned int x;
unsigned int y;
};
Type type;
union {
struct KeyEvent key;
struct MouseEvent mouse;
struct MouseButtonEvent mouseButton;
};
InputEvent(Type type = None);
} InputEvent;
} // namespace sp
#endif /* SPECTRE_INPUT_EVENT_H */

View file

@ -1,17 +0,0 @@
#ifndef SPECTRE_INPUT_LISTENER_H
#define SPECTRE_INPUT_LISTENER_H
#include "InputEvent.h"
namespace sp {
class InputListener
{
public :
virtual void onInputEvent(const InputEvent& event);
};
} // namespace sp
#endif /* SPECTRE_INPUT_LISTENER_H */

View file

@ -5,9 +5,6 @@
#include <deque> #include <deque>
#include <vector> #include <vector>
#include "InputListener.h"
#include "InputEvent.h"
namespace sp { namespace sp {
class Mouse; class Mouse;
@ -28,12 +25,6 @@ public :
void addInputDevice(InputDevice *device); void addInputDevice(InputDevice *device);
void registerListener(InputListener* listener);
void removeListener(InputListener* listener);
void postInputEvent(const InputEvent& event);
// NOTE: Update devices here! (for winapi, process keyboard/mouse messages) // NOTE: Update devices here! (for winapi, process keyboard/mouse messages)
void update(); void update();
@ -48,11 +39,6 @@ protected :
Keyboard *m_keyboard; Keyboard *m_keyboard;
// Buffered input queue.
std::deque<InputEvent> m_buffer;
std::vector<InputListener*> m_listeners;
PlatformInput *m_platform; PlatformInput *m_platform;
}; };

View file

@ -3,19 +3,107 @@
#define SPECTRE_INPUT_KEYBOARD_H #define SPECTRE_INPUT_KEYBOARD_H
#include <string> #include <string>
#include "InputEvent.h"
#include "InputDevice.h" #include "InputDevice.h"
namespace sp { namespace sp {
class Keyboard : public InputDevice class Keyboard : public InputDevice
{ {
public :
enum Key {
Unknown,
A,
B,
C,
D,
E,
F,
G,
H,
I,
J,
K,
L,
M,
N,
O,
P,
Q,
R,
S,
T,
U,
V,
W,
X,
Y,
Z,
One,
Two,
Three,
Four,
Five,
Six,
Seven,
Eight,
Nine,
Zero,
Period,
Comma,
Enter,
Backspace,
Escape,
Space,
Capslock,
Up,
Down,
Left,
Right,
Numpad1,
Numpad2,
Numpad3,
Numpad4,
Numpad5,
Numpad6,
Numpad7,
Numpad8,
Numpad9,
Numpad0,
Home,
End,
Insert,
Delete,
PageUp,
PageDown,
Pause,
F1,
F2,
F3,
F4,
F5,
F6,
F7,
F8,
F9,
F10,
F11,
F12,
Tab,
LShift,
RShift,
LCtrl,
RCtrl,
LAlt,
RAlt,
NUM_KEYS,
};
public : public :
virtual ~Keyboard() {}; virtual ~Keyboard() {};
virtual bool isKeyDown(Key::Type key) = 0; virtual bool isKeyDown(Key key) = 0;
static std::string getKeyName(Key::Type key); static std::string getKeyName(Key key);
}; };
} // namespace sp } // namespace sp

View file

@ -4,26 +4,39 @@
#include <string> #include <string>
#include <Spectre/Math/Vector2.h> #include <Spectre/Math/Vector2.h>
#include "InputEvent.h" #include <Spectre/Input/InputDevice.h>
#include "InputDevice.h"
namespace sp { namespace sp {
class Mouse : public InputDevice class Mouse : public InputDevice
{ {
public :
enum Button {
Unknown,
Left,
Right,
Middle,
XButton1,
XButton2,
NUM_MBUTTONS
};
public : public :
virtual ~Mouse(); virtual ~Mouse();
// Get mouse position // Get the position in relative (focused window) coordinates.
// coordinates are relative to the window's top-left corner.
virtual Vector2f getPosition() const = 0; virtual Vector2f getPosition() const = 0;
//virtual Vector2i getPositionAbs() const = 0; // Get the position in absolute (screen) coordinates.
// 0,0 is located at the screen's top-left corner.
virtual Vector2f getAbsPosition() const = 0;
virtual bool isButtonDown(MouseButton::Type button) const = 0; virtual bool isButtonDown(Button button) const = 0;
static std::string getButtonName(MouseButton::Type button); static std::string getButtonName(Button button);
}; };
} // namespace sp }; // namespace sp
#endif /* SPECTRE_INPUT_MOUSE_H */ #endif /* SPECTRE_INPUT_MOUSE_H */

View file

@ -2,6 +2,8 @@
#ifndef SPECTRE_MATH_MATH_H #ifndef SPECTRE_MATH_MATH_H
#define SPECTRE_MATH_MATH_H #define SPECTRE_MATH_MATH_H
#include "Transform.h"
#include "Vector4.h"
#include "Vector3.h" #include "Vector3.h"
#include "Vector2.h" #include "Vector2.h"
#include "Matrix4.h" #include "Matrix4.h"
@ -32,21 +34,17 @@ namespace sp { namespace math
float bottom, float top, float bottom, float top,
float zNear = -1.0f, float zFar = 1.0f); float zNear = -1.0f, float zFar = 1.0f);
//
Vector2f Vector2UnProject(Vector2f point, Transform InverseMVP, Vector4u screen);
// Create a 2D rotation matrix. (rotation around Z-axis) // Create a 2D rotation matrix. (rotation around Z-axis)
Matrix4f rotation(float theta); Matrix4f rotation(float theta);
// Create a 2D translation matrix. // Create a 2D translation matrix.
Matrix4f translate(const Vector2f& v); Matrix4f translate(float x, float y);
// Create a 2D scale matrix. // Create a 2D scale matrix.
Matrix4f scale(const Vector2f& f); Matrix4f scale(float x, float y);
// Get translation part of a matrix.
Vector3f getTranslate(const Matrix4f matrix);
Vector3f getUpVector(const Matrix4f matrix);
Vector3f getForwardVector(const Matrix4f matrix);
} } // namespace sp } } // namespace sp

View file

@ -58,7 +58,16 @@ struct Matrix3
inline Matrix3<T> operator*(const Matrix3<T>& mat) const; inline Matrix3<T> operator*(const Matrix3<T>& mat) const;
inline Matrix3<T> operator*=(const Matrix3<T>& mat); inline Matrix3<T> operator*=(const Matrix3<T>& mat);
// Need scalar, vector arithmetic?
// -----------------
// Arithmetic: Scalar
// -----------------
inline Matrix3<T> operator/(T value) const;
inline Matrix3<T> operator/=(T value);
inline Matrix3<T> operator*(T value) const;
inline Matrix3<T> operator*=(T value);
// ----------------- // -----------------
// Named operations. // Named operations.
@ -69,6 +78,9 @@ struct Matrix3
// Transpose matrix. // Transpose matrix.
Matrix3<T> transpose() const; Matrix3<T> transpose() const;
// Inverse
Matrix3<T> inverse() const;
}; };
template <typename T> template <typename T>

View file

@ -4,8 +4,8 @@
namespace sp { namespace sp {
template <> template<typename T>
Matrix3f Matrix3f::Identity( sp::Matrix3<T> sp::Matrix3<T>::Identity(
1, 0, 0, 1, 0, 0,
0, 1, 0, 0, 1, 0,
0, 0, 1 0, 0, 1
@ -87,6 +87,39 @@ inline Matrix3<T> Matrix3<T>::operator*=(const Matrix3<T>& mat)
return *this; return *this;
} }
template<typename T>
inline Matrix3<T> Matrix3<T>::operator/(T value) const
{
return Matrix3<T>(
v[0] / value, v[1] / value, v[2] / value,
v[3] / value, v[4] / value, v[5] / value,
v[6] / value, v[7] / value, v[8] / value);
}
template<typename T>
inline Matrix3<T> Matrix3<T>::operator/=(T value)
{
*this = *this / value;
return *this;
}
template<typename T>
inline Matrix3<T> Matrix3<T>::operator*(T value) const
{
return Matrix3<T>(
v[0] * value, v[1] * value, v[2] * value,
v[3] * value, v[4] * value, v[5] * value,
v[6] * value, v[7] * value, v[8] * value);
}
template<typename T>
inline Matrix3<T> Matrix3<T>::operator*=(T value)
{
*this = *this * value;
return *this;
}
template<typename T> template<typename T>
float Matrix3<T>::det() const float Matrix3<T>::det() const
{ {
@ -103,6 +136,30 @@ float Matrix3<T>::det() const
return det; return det;
} }
template<typename T>
Matrix3<T> Matrix3<T>::inverse() const
{
float d = det();
if (d != 0.0f) {
float a00 = (v[4] * v[8]) - (v[7] * v[5]);
float a01 = -((v[1] * v[8]) - (v[7] * v[2]));
float a02 = (v[1] * v[5]) - (v[4] * v[2]);
float a10 = -((v[3] * v[8]) - (v[6] * v[5]));
float a11 = (v[0] * v[8]) - (v[6] * v[2]);
float a12 = -((v[0] * v[5]) - (v[3] * v[2]));
float a20 = (v[3] * v[7]) - (v[6] * v[4]);
float a21 = -((v[0] * v[7]) - (v[6] * v[1]));
float a22 = (v[0] * v[4]) - (v[3] * v[1]);
return Matrix3<T>(a00, a01, a02, a10, a11, a12, a20, a21, a22) / d;
}
return Matrix3<T>::Identity;
}
template<typename T> template<typename T>
Matrix3<T> Matrix3<T>::transpose() const Matrix3<T> Matrix3<T>::transpose() const
{ {

View file

@ -0,0 +1,50 @@
#ifndef SPECTRE_MATH_TIME_H
#define SPECTRE_MATH_TIME_H
namespace sp {
class Time {
public :
Time(long value = 0);
double seconds() const;
int milliseconds() const;
long microseconds() const;
// ----------------------------
// Helper construct functions
// ----------------------------
static Time seconds(double value);
static Time milliseconds(int value);
static Time microseconds(long value);
private :
// Microseconds (us)
long m_us;
};
// ----------------------------
// Compare
// ----------------------------
bool operator ==(const Time& a, const Time& b);
bool operator !=(const Time& a, const Time& b);
bool operator <(const Time& a, const Time& b);
bool operator <=(const Time& a, const Time& b);
bool operator >(const Time& a, const Time& b);
bool operator >=(const Time& a, const Time& b);
// ----------------------------
// Arithmetic
// ----------------------------
Time operator +(const Time& a, const Time& b);
Time& operator +=(Time& a, const Time& b);
Time operator -(const Time& a, const Time& b);
Time& operator -=(Time& a, const Time& b);
}; // namespace sp
#endif /* SPECTRE_MATH_TIME_H */

View file

@ -53,7 +53,11 @@ public :
Transform& scale(Vector2f offset); Transform& scale(Vector2f offset);
Transform& scale(float s); Transform& scale(float s);
Transform& multiply(const Transform& other); // Inverse
Transform inverse();
Transform& combine(const Transform& other);
Vector2f transformPoint(float x, float y) const; Vector2f transformPoint(float x, float y) const;

View file

@ -30,16 +30,16 @@ struct Vector2
// Named operations. // Named operations.
// ----------------- // -----------------
inline float length() const; inline float len() const;
inline Vector2<T>& normalize(); inline Vector2<T>& normal();
// Dot product // Dot product
inline T dot(const Vector2<T>& vec) const; inline T dot(const Vector2<T>& vec) const;
inline Vector2<T>& reflect(const Vector2<T>& n); inline Vector2<T>& reflect(const Vector2<T>& n);
std::string toString() const; inline std::string toString() const;
}; };
// ------------ // ------------
@ -182,14 +182,14 @@ inline std::ostream& operator<<(std::ostream &s, const Vector2<T>& v);
// Common specialization types // Common specialization types
// ----------------------------- // -----------------------------
typedef Vector2<float> Vector2f; typedef Vector2<float> Vector2f;
typedef Vector2<int> Vector2i; typedef Vector2<int> Vector2i;
typedef Vector2<unsigned> Vector2u; typedef Vector2<unsigned> Vector2u;
typedef Vector2<unsigned char> Vector2b; typedef Vector2<unsigned char> Vector2b;
typedef Vector2<float> vec2f; typedef Vector2<float> vec2f;
typedef Vector2<int> vec2i; typedef Vector2<int> vec2i;
typedef Vector2<unsigned> vec2u; typedef Vector2<unsigned> vec2u;
typedef Vector2<unsigned char> vec2b; typedef Vector2<unsigned char> vec2b;
} // namespace sp } // namespace sp

View file

@ -31,15 +31,15 @@ inline Vector2<T>::Vector2(const Vector2<U>& vec)
} }
template <typename T> template <typename T>
inline float Vector2<T>::length() const inline float Vector2<T>::len() const
{ {
return std::sqrt((x * x) + (y * y)); return std::sqrt((x * x) + (y * y));
} }
template <typename T> template <typename T>
inline Vector2<T>& Vector2<T>::normalize() inline Vector2<T>& Vector2<T>::normal()
{ {
float il = 1.0f / length(); float il = 1.0f / len();
x *= il; y *= il; x *= il; y *= il;
return *this; return *this;
} }
@ -58,7 +58,7 @@ inline Vector2<T>& Vector2<T>::reflect(const Vector2<T>& n)
} }
template <typename T> template <typename T>
std::string Vector2<T>::toString() const inline std::string Vector2<T>::toString() const
{ {
return core::to_string(x) + ", " + core::to_string(y); return core::to_string(x) + ", " + core::to_string(y);
} }

View file

@ -35,9 +35,9 @@ struct Vector3
// Named operations. // Named operations.
// ----------------- // -----------------
inline float length() const; inline float len() const;
inline Vector3<T>& normalize(); inline Vector3<T>& normal();
inline Vector2<T> toVec2(); inline Vector2<T> toVec2();
}; };
@ -159,14 +159,14 @@ inline std::ostream& operator<<(std::ostream &s, const Vector3<T>& v);
// Common specialization types // Common specialization types
// ----------------------------- // -----------------------------
typedef Vector3<float> Vector3f; typedef Vector3<float> Vector3f;
typedef Vector3<int> Vector3i; typedef Vector3<int> Vector3i;
typedef Vector3<unsigned> Vector3u; typedef Vector3<unsigned> Vector3u;
typedef Vector3<unsigned char> Vector3b; typedef Vector3<unsigned char> Vector3b;
typedef Vector3<float> vec3f; typedef Vector3<float> vec3f;
typedef Vector3<int> vec3i; typedef Vector3<int> vec3i;
typedef Vector3<unsigned> vec3u; typedef Vector3<unsigned> vec3u;
typedef Vector3<unsigned char> vec3b; typedef Vector3<unsigned char> vec3b;
} // namespace sp } // namespace sp

View file

@ -43,7 +43,7 @@ inline Vector3<T>::Vector3(const Vector2<U>& vec)
} }
template <typename T> template <typename T>
inline float Vector3<T>::length() const inline float Vector3<T>::len() const
{ {
return std::sqrt((x * x) + (y * y) + (z * z)); return std::sqrt((x * x) + (y * y) + (z * z));
} }
@ -55,9 +55,9 @@ Vector2<T> Vector3<T>::toVec2()
} }
template <typename T> template <typename T>
inline Vector3<T>& Vector3<T>::normalize() inline Vector3<T>& Vector3<T>::normal()
{ {
float il = 1.0f / length(); float il = 1.0f / len();
x *= il; y *= il; z *= il; x *= il; y *= il; z *= il;
return *this; return *this;
} }

View file

@ -29,9 +29,9 @@ struct Vector4
// Named operations // Named operations
inline float length() const; inline float len() const;
inline Vector4<T>& normalize(); inline Vector4<T>& normal();
}; };
// --------- // ---------
@ -145,14 +145,14 @@ inline bool operator>=(T s, const Vector4<T>& v);
template <typename T> template <typename T>
inline std::ostream& operator<<(std::ostream &s, const Vector4<T>& v); inline std::ostream& operator<<(std::ostream &s, const Vector4<T>& v);
typedef Vector4<float> Vector4f; typedef Vector4<float> Vector4f;
typedef Vector4<int> Vector4i; typedef Vector4<int> Vector4i;
typedef Vector4<unsigned> Vector4u; typedef Vector4<unsigned> Vector4u;
typedef Vector4<unsigned char> Vector4b; typedef Vector4<unsigned char> Vector4b;
typedef Vector4<float> vec4f; typedef Vector4<float> vec4f;
typedef Vector4<int> vec4i; typedef Vector4<int> vec4i;
typedef Vector4<unsigned> vec4u; typedef Vector4<unsigned> vec4u;
typedef Vector4<unsigned char> vec4b; typedef Vector4<unsigned char> vec4b;
} // namespace sp } // namespace sp

View file

@ -36,15 +36,15 @@ Vector4<T>::Vector4(const Vector4<U>& vec)
} }
template <typename T> template <typename T>
float Vector4<T>::length() const float Vector4<T>::len() const
{ {
return std::sqrt((x * x) + (y * y) + (z * z) + (w * w)); return std::sqrt((x * x) + (y * y) + (z * z) + (w * w));
} }
template <typename T> template <typename T>
Vector4<T>& Vector4<T>::normalize() Vector4<T>& Vector4<T>::normal()
{ {
float il = 1.0f / length(); float il = 1.0f / len();
x *= il; y *= il; z *= il; w *= il; x *= il; y *= il; z *= il; w *= il;
return *this; return *this;
} }

View file

@ -0,0 +1,15 @@
#ifndef SPECTRE_SYSTEM_BYTEORDER_H
#define SPECTRE_SYSTEM_BYTEORDER_H
#include <cstdint>
namespace sp { namespace system
{
uint16_t ltoh16(const uint8_t* bytes);
uint32_t ltoh32(const uint8_t* bytes);
} } // namespace sp::system
#endif /* SPECTRE_SYSTEM_BYTEORDER_H */

View file

@ -0,0 +1,76 @@
#ifndef SPECTRE_SYSTEM_EVENT_H
#define SPECTRE_SYSTEM_EVENT_H
#include <Spectre/Input/Mouse.h>
#include <Spectre/Input/Keyboard.h>
namespace sp {
class Window;
struct Event
{
public :
enum Type {
Unknown,
Quit,
Size,
Key,
MouseButton,
MouseMove
};
struct KeyEvent {
Keyboard::Key code;
bool pressed; /* true if pressed, false if released. */
std::string getKeyName() const; /* Get the key name */
};
struct MouseButtonEvent {
Mouse::Button button;
bool pressed; /* true if pressed, false if released. */
std::string getName() const;
};
struct MouseMoveEvent {
unsigned int x;
unsigned int y;
};
struct SizeEvent
{
Window *window;
int width;
int height;
};
Type type;
union {
struct SizeEvent size;
struct KeyEvent key;
struct MouseMoveEvent mouseMove;
struct MouseButtonEvent mouseButton;
};
Event(Type type = Unknown);
std::string toString() const;
// Helper methods
static Event createSize(Window *window, int width, int height);
static Event createKey(Keyboard::Key code, bool pressed);
static Event createMouseButton(Mouse::Button button, bool pressed);
static Event createMouseMove(unsigned int x, unsigned int y);
};
} // namespace sp
#endif /* SPECTRE_SYSTEM_EVENT_H */

View file

@ -0,0 +1,23 @@
#ifndef SYSTEM_EVENT_LISTENER_H
#define SYSTEM_EVENT_LISTENER_H
#include <Spectre/System/Event.h>
#include <Spectre/Input/Mouse.h>
#include <Spectre/Input/Keyboard.h>
namespace sp {
class Window;
class EventListener
{
public :
virtual void onSizeChanged(Window* window, int width, int height);
virtual void onEvent(const Event& event);
};
} // namespace sp
#endif /* SYSTEM_EVENT_LISTENER_H */

View file

@ -2,18 +2,118 @@
#ifndef SPECTRE_SYSTEM_FILE_H #ifndef SPECTRE_SYSTEM_FILE_H
#define SPECTRE_SYSTEM_FILE_H #define SPECTRE_SYSTEM_FILE_H
#include <vector> #include <stdio.h>
#include <string> #include <string>
#include <system_error>
namespace sp { namespace file namespace sp {
class File
{ {
std::string getBasename(const std::string& path); public :
std::string getExtension(const std::string& path); enum struct Access {
READ = 1 << 0,
WRITE = 1 << 1,
READ_WRITE = READ | WRITE,
};
std::string getPathname(const std::string& path); // NOTE: These are ignored atm. as implementation uses stdio.h
enum OpenMode {
// Only open if file exists and
// in overwrite mode if write is enabled.
DEFAULT = 0,
// Create file if it does not exist (ignored in read-only mode)
CREATE = 1 << 0,
// If file exists any write calls will
// append to the file. (ignored in read-only mode)
APPEND = 1 << 1,
// If file exists it's content are discarded
// resulting in an empty file. (ignored in read-only mode)
TRUNCATE = 1 << 2
};
std::vector<unsigned char> read(const std::string& path); // Methods.
} } public :
File();
// see `open()`
File(const std::string& filename,
Access access = Access::READ,
unsigned int mode = DEFAULT);
~File();
// Opens a file (default in read-only)
bool open(const std::string& filename,
Access access = Access::READ,
unsigned int mode = DEFAULT);
// Returns true if the file is open, false otherwise.
bool isOpen() const;
// Close the file.
void close();
std::string getErrorMessage() const;
// Get the current position in the file.
size_t pos();
// Set the file stream position.
// if `from_end` is true. `offset` will be applied from the end of file, otherwise from beginning.
// Returns true if the position was updated, false otherwise.
bool set(long int pos = 0, bool from_end = false);
// Move the current file stream position with `offset` bytes.
// This is equivalent to calling set(pos() + offset)
// Returns true if the position was updated, false otherwise.
bool seek(long int offset);
// Get the size of the file (in bytes)
size_t size() const;
// Read `size` data from file at the current position.
// Content is stored in `ptr` and must be alteast `size` bytes.
// Returns -1 if an error occured. Otherwice the number of bytes read is returned.
size_t read(void *ptr, size_t size);
// Read all remaining data from file at the current position. Content is stored in `buffer`.
// Returns true if exactly all data could be read from file. false otherwise.
template <typename buffer_t>
inline bool read(buffer_t& buffer)
{
size_t s = size();
buffer.resize(s);
return read((void*) &buffer[0], s) == s;
}
// Read contents into str until null (\0)
size_t readString(std::string &str);
// Write data to file at the current position.
// Returns -1 if an error occured. Otherwice the number of bytes written is returned.
size_t write(const void *ptr, size_t size);
// Write data to file at the current position.
// Returns true if exactly all data could be written from `buffer`. false otherwise.
template <typename buffer_t>
inline bool write(const buffer_t& buffer)
{
return write((const void*) &buffer[0], buffer.size()) == buffer.size();
}
// Flush any buffered data to the file.
bool flush();
private :
FILE *m_handle;
// Error
mutable std::error_condition m_error;
};
} //namespace sp
#endif /* SPECTRE_SYSTEM_FILE_H */ #endif /* SPECTRE_SYSTEM_FILE_H */

View file

@ -7,6 +7,8 @@
namespace sp { namespace sp {
namespace log { class Writer; }
class Log class Log
{ {
public : public :
@ -15,17 +17,24 @@ public :
T_WARNING = 1 << 0, T_WARNING = 1 << 0,
T_CRITICAL = 1 << 1, T_CRITICAL = 1 << 1,
T_ERROR = 1 << 2, T_ERROR = 1 << 2,
T_DEBUG = 1 << 3
}; };
static void info(const char *message, ...); static void setWriter(log::Writer* writer);
static void warn(const char *message, ...); static void info(const char *format, ...);
static int error(const char *message, ...); static void warn(const char *format, ...);
static int error(const char *format, ...);
static void debug(const char *format, ...);
private : private :
static void writeln(Type type, const char *fmt, va_list args); static void writeln(Type type, const char *fmt, va_list args);
static log::Writer* _writer;
}; };
} // namespace sp } // namespace sp

View file

@ -0,0 +1,32 @@
#ifndef SPECTRE_SYSTEM_LOG_FILEWRITER_H
#define SPECTRE_SYSTEM_LOG_FILEWRITER_H
#include <stdio.h>
#include <string>
#include <Spectre/System/Log/Writer.h>
namespace sp { namespace log {
class FileWriter : public Writer
{
public:
FileWriter(const std::string file = "");
~FileWriter();
bool open(const std::string file);
bool close();
size_t write(const void *data, size_t len);
virtual bool flush();
protected:
FILE *m_fd;
};
} } // sp::log
#endif /* SPECTRE_SYSTEM_LOG_FILEWRITER_H */

View file

@ -0,0 +1,19 @@
#ifndef SPECTRE_SYSTEM_LOG_WRITER_H
#define SPECTRE_SYSTEM_LOG_WRITER_H
namespace sp { namespace log {
class Writer
{
public:
virtual ~Writer() {}
virtual size_t write(const void *data, size_t len) = 0;
virtual bool flush() = 0;
};
} } // sp::log
#endif /* SPECTRE_SYSTEM_LOG_WRITER_H */

View file

@ -2,16 +2,25 @@
#ifndef SPECTRE_SYSTEM_MESSAGEHANDLER_H #ifndef SPECTRE_SYSTEM_MESSAGEHANDLER_H
#define SPECTRE_SYSTEM_MESSAGEHANDLER_H #define SPECTRE_SYSTEM_MESSAGEHANDLER_H
#include "SystemEvent.h" #include <vector>
#include "EventListener.h"
namespace sp { namespace sp {
class Display; class MessageHandler : public EventListener
class MessageHandler
{ {
public : public :
virtual void onSizeChanged(Display* display, int width, int height);
void registerListener(EventListener *listener);
void unregisterListener(EventListener *listener);
virtual void onSizeChanged(Window* window, int width, int height);
virtual void onEvent(const Event& event);
protected :
std::vector<EventListener*> m_listeners;
}; };
} // namespace sp } // namespace sp

View file

@ -2,22 +2,29 @@
#ifndef SPECTRE_MESSAGE_QUEUE_H #ifndef SPECTRE_MESSAGE_QUEUE_H
#define SPECTRE_MESSAGE_QUEUE_H #define SPECTRE_MESSAGE_QUEUE_H
#include <Spectre/System/SystemEvent.h> #include <Spectre/System/Event.h>
#include <queue> #include <queue>
namespace sp { namespace sp {
class PlatformEventQueue;
class MessageQueue class MessageQueue
{ {
public : public :
void postEvent(SysEvent event); MessageQueue();
~MessageQueue();
bool pollEvent(SysEvent& event); void postEvent(Event event);
bool pollEvent(Event& event);
bool isEmpty() const; bool isEmpty() const;
protected : protected :
std::deque<SysEvent> m_queue; std::deque<Event> m_queue;
PlatformEventQueue* m_impl;
}; };
} // namespace sp } // namespace sp

View file

@ -0,0 +1,19 @@
#ifndef SYSTEM_PATH_H
#define SYSTEM_PATH_H
#include <string>
namespace sp {
class Path
{
public :
static std::string getBasename(const std::string& path);
static std::string getExtension(const std::string& path);
};
} // namespace sp
#endif /* SYSTEM_PATH_H */

View file

@ -0,0 +1,27 @@
#ifndef SPECTRE_SYSTEM_STOPWATCH_H
#define SPECTRE_SYSTEM_STOPWATCH_H
#include <Spectre/Math/Time.h>
namespace sp {
class Stopwatch {
public :
Stopwatch();
// Restart the watch. also returns the elapsed time before
// the watch was restarted.
Time restart();
// Get the elapsed time since the watch was restarted.
Time elapsed() const;
private :
Time m_start;
};
} // namespace sp
#endif /* SPECTRE_SYSTEM_STOPWATCH_H */

View file

@ -1,41 +0,0 @@
#ifndef SYSTEM_EVENT_H
#define SYSTEM_EVENT_H
namespace sp {
class Display;
struct SysEvent
{
public :
enum Type {
None,
Quit,
Size,
};
Type type;
struct Size
{
Display *display;
int width;
int height;
};
union {
struct Size size;
};
SysEvent(Type type = None);
// Helper methods
static SysEvent sizeEvent(Display *display, int width, int height);
};
} // namespace sp
#endif /* SYSTEM_EVENT_H */

View file

@ -16,6 +16,15 @@ public :
static DisplayMode getDesktopMode(); static DisplayMode getDesktopMode();
// Returns true if width hight and bpp are not set (eg. zero)
// useful to determine if a DisplayMode object is set or not.
// this is equal to:
// DisplayMode a;
// if (a == DisplayMode()) {
// // empty
// }
bool empty() const;
inline bool operator==(const DisplayMode& other) inline bool operator==(const DisplayMode& other)
{ {
return width == other.width return width == other.width

View file

@ -1,24 +1,22 @@
#ifndef DISPLAY_GLCONTEXT_H #ifndef SPECTRE_WINDOW_GLCONTEXT_H
#define DISPLAY_GLCONTEXT_H #define SPECTRE_WINDOW_GLCONTEXT_H
#include <Spectre/Math/Vector2.h> #include <Spectre/Math/Vector2.h>
namespace sp { namespace sp {
class PlatformDisplay; class PlatformWindow;
// Platform independant interface for OpenGL Contexts. // Platform independant interface for OpenGL Contexts.
class GLContext class GLContext
{ {
public : public :
static GLContext* create();
virtual ~GLContext(); virtual ~GLContext();
// Create a GLContext for this perticular display. // Create a GLContext for this perticular window.
virtual bool create(const PlatformDisplay* display) = 0; virtual bool create(const PlatformWindow* window) = 0;
virtual void destroy() = 0; virtual void destroy() = 0;
@ -38,13 +36,10 @@ public :
// This is usually refered to as enabling/disabling vertical synchronization. // This is usually refered to as enabling/disabling vertical synchronization.
virtual bool setSwapInterval(int interval) = 0; virtual bool setSwapInterval(int interval) = 0;
// Set the size of the pixel buffer.
virtual void setSize(unsigned int width, unsigned int height) = 0;
// Swap front with back buffer and vice versa. // Swap front with back buffer and vice versa.
virtual void swapBuffers() = 0; virtual void swapBuffers() = 0;
}; };
} // namespace sp } // namespace sp
#endif /* DISPLAY_GLCONTEXT_H */ #endif /* SPECTRE_WINDOW_GLCONTEXT_H */

View file

@ -0,0 +1,41 @@
#ifndef SPECTRE_WINDOW_GLWINDOW_H
#define SPECTRE_WINDOW_GLWINDOW_H
#include <Spectre/Window/Window.h>
#include <Spectre/Window/GLContext.h>
namespace sp {
class GLContext;
// GLWindow represents a window that has an OpenGL context attached to it.
class GLWindow : public Window
{
public:
GLWindow();
virtual ~GLWindow();
virtual bool create(WindowDescription decription);
virtual void destroy();
bool activate(bool value);
// Enable/Disable Vertical Sync.
bool enableVSync(bool value);
void swapBuffers();
protected:
virtual void onReshape(int width, int height);
private:
GLContext* m_context;
};
} // namepsace sp
#endif /* SPECTRE_WINDOW_GLWINDOW_H */

View file

@ -0,0 +1,83 @@
#ifndef SPECTRE_WINDOW_WINDOW_H
#define SPECTRE_WINDOW_WINDOW_H
#include "DisplayMode.h"
#include "WindowDescription.h"
#include <Spectre/Math/Vector2.h>
#include <cstdint>
#include <string>
namespace sp {
class PlatformWindow;
class GLContext;
class Window
{
friend class PlatformWindow;
public :
enum Mode {
WINDOWED = 0,
FULLSCREEN = 1,
WINDOWEDFULLSCREEN = 2,
};
public :
Window();
virtual ~Window();
virtual bool create(WindowDescription decription);
virtual void destroy();
void setSize(unsigned int width, unsigned int height);
sp::Vector2u getSize() const;
void setCaption(const std::string& title);
const std::string& getCaption() const;
void setIcon(const std::string& filename);
void setIcon(unsigned int width, unsigned int height, const uint8_t *pixels);
void setDisplayMode(const DisplayMode& mode);
const DisplayMode& getDisplayMode() const;
void setVideoMode(Mode mode);
enum Mode getVideoMode() const;
void setVisible(bool visible);
void showCursor(bool value);
void grabCursor(bool value);
protected :
void init();
virtual void onReshape(int width, int height);
protected :
enum Mode m_fmode;
// Cache window position when entering fullscreen
// So it can be restored when returning to window mode.
Vector2u m_cachePos;
WindowDescription m_description;
WindowDescription m_cacheDesc;
std::string m_caption;
PlatformWindow* m_impl;
};
} // namepsace sp
#endif /* SPECTRE_WINDOW_WINDOW_H */

View file

@ -0,0 +1,34 @@
#ifndef SPECTRE_WINDOW_WINDOWDESCRIPTION_H
#define SPECTRE_WINDOW_WINDOWDESCRIPTION_H
#include "DisplayMode.h"
namespace sp {
namespace WindowDecorate {
enum Type {
Empty = 0,
Menu = 1 << 0,
Resize = 1 << 1,
Close = 1 << 2,
Default = Menu | Resize | Close,
};
};
struct WindowDescription
{
public :
WindowDescription();
WindowDescription(DisplayMode mode, unsigned decoration = WindowDecorate::Default);
public :
DisplayMode mode;
unsigned int decoration;
};
} // namespace sp
#endif /* SPECTRE_WINDOW_WINDOWDESCRIPTION_H */

View file

@ -4,6 +4,13 @@
namespace sp { namespace sp {
std::string core::to_string(int value)
{
char buf[32];
sprintf(buf, "%i", value);
return std::string(buf);
}
std::string core::to_string(unsigned int value) std::string core::to_string(unsigned int value)
{ {
char buf[32]; char buf[32];

View file

@ -1,154 +0,0 @@
#include <iostream>
#include <Spectre/Display/Display.h>
#include <Spectre/Display/GLContext.h>
#include <Spectre/System/SystemEvent.h>
#include <Platform/PlatformDisplay.h>
namespace sp {
#define CAPTION_DEFAULT "Spectre"
#define ICON_DEFAULT "./assets/app.ico"
Display::Display()
{
m_caption = CAPTION_DEFAULT;
m_fmode = WINDOWED;
m_context = GLContext::create();
m_impl = PlatformDisplay::make(this);
}
Display::~Display()
{
delete m_context;
delete m_impl;
}
bool Display::create(DisplayDescription description)
{
destroy();
if (!m_impl->create(description)) {
return false;
}
if (!m_context->create(m_impl)) {
return false;
}
init();
m_description = description;
return true;
}
void Display::init()
{
m_impl->setCaption(m_caption);
setIcon(ICON_DEFAULT);
activate(true);
enableVSync(false);
showCursor(true);
}
void Display::destroy()
{
m_context->destroy();
m_impl->destroy();
}
void Display::setCaption(const std::string& caption)
{
m_caption = caption;
m_impl->setCaption(m_caption);
}
const std::string& Display::getCaption() const
{
return m_caption;
}
void Display::setIcon(const std::string& filename)
{
m_impl->setIcon(filename);
}
void Display::setSize(unsigned int width, unsigned int height)
{
m_description.mode.width = width;
m_description.mode.height = height;
m_impl->setSize(width, height);
}
void Display::setVideoMode(Mode mode)
{
DisplayDescription desc;
if (m_fmode == mode) {
return;
}
if (mode == FULLSCREEN || mode == WINDOWEDFULLSCREEN) {
// True fullscreen
if (mode == FULLSCREEN) {
desc.mode = m_description.mode;
} else {
desc.mode = DisplayMode::getDesktopMode();
m_cacheDesc = m_description;
}
desc.decoration = DisplayDecorate::None;
} else {
desc = m_cacheDesc;
}
create(desc);
m_fmode = mode;
}
enum Display::Mode Display::getVideoMode() const
{
return m_fmode;
}
void Display::showCursor(bool value)
{
m_impl->showCursor(value);
}
bool Display::activate(bool value)
{
if (value) {
return m_context->activate();
}
return m_context->deactivate();
}
bool Display::enableVSync(bool value)
{
return m_context->setSwapInterval(value ? 1 : 0);
}
void Display::swapBuffers()
{
if (activate(true)) {
m_context->swapBuffers();
}
}
void Display::onReshape(int width, int height)
{
// Resize context if the windows resizes.
m_context->setSize(width, height);
}
} // namespace sp

View file

@ -1,18 +0,0 @@
#include <Spectre/Display/DisplayDescription.h>
namespace sp {
DisplayDescription::DisplayDescription() :
mode (),
decoration (DisplayDecorate::Default)
{
}
DisplayDescription::DisplayDescription(DisplayMode mode, unsigned decoration) :
mode (mode),
decoration (decoration)
{
}
} // namespace sp

View file

@ -1,23 +0,0 @@
#include <Spectre/Display/GLContext.h>
#ifdef _WIN32
#include <Platform/Win32/Win32GLContext.h>
typedef sp::Win32GLContext ContextType;
#else
#error "No GLContext implementation exists"
#endif
namespace sp {
GLContext* GLContext::create()
{
return new ContextType();
}
GLContext::~GLContext()
{
// Nothing to do.
}
} // namespace sp

View file

@ -3,45 +3,49 @@
#include <Spectre/Game/GameTime.h> #include <Spectre/Game/GameTime.h>
#include <Spectre/Game/FPSCounter.h> #include <Spectre/Game/FPSCounter.h>
#include <Spectre/Input/InputModule.h> #include <Spectre/Input/InputModule.h>
#include <Spectre/System/Log.h>
#include <Spectre/System/Log/FileWriter.h>
#include <Spectre/System/MessageHandler.h> #include <Spectre/System/MessageHandler.h>
#include <Spectre/System/MessageQueue.h>
#include <Platform/PlatformMisc.h>
#include <Platform/Win32/Win32Application.h>
#include <Spectre/Game.h> #include <Spectre/Game.h>
#include <Platform/PlatformApplication.h>
#include <Platform/PlatformMisc.h>
namespace sp { namespace sp {
Game::Game() Game::Game() :
m_running(false)
{ {
m_platform = new Win32Application(); m_platform = PlatformApplication::get();
m_running = false;
m_graphics = new Graphics(m_platform); m_graphics = new Graphics(m_platform);
m_input = new InputModule(&m_platform->getInput()); m_input = new InputModule(&m_platform->getInput());
m_messageHandler = new MessageHandler(); m_messageHandler = new MessageHandler();
// Setup log
m_log_writer = new log::FileWriter("stdout");
Log::setWriter(m_log_writer);
} }
Game::~Game() Game::~Game()
{ {
delete m_input; delete m_input;
delete m_graphics; delete m_graphics;
delete m_platform;
delete m_messageHandler; delete m_messageHandler;
}
void Game::setup() // TODO: This is abit ugly tbh.
{ m_platform->shutdown();
m_graphics->init();
m_graphics->setClearColor(0.0f, 0.0f, 0.0f);
init();
} }
void Game::run() void Game::run()
{ {
setup(); m_platform->init();
if (!m_graphics->init()) {
return;
}
init();
gameLoop(); gameLoop();
} }
@ -56,6 +60,9 @@ void Game::gameLoop()
processEvents(); processEvents();
// Update input.
getInput()->update();
if (time.beginFrame()) { if (time.beginFrame()) {
while(time.tick()) { while(time.tick()) {
@ -71,22 +78,22 @@ void Game::gameLoop()
void Game::processEvents() void Game::processEvents()
{ {
MessageQueue& queue = m_platform->getMessageQueue(); MessageQueue& queue = m_platform->getMessageQueue();
SysEvent event; Event event;
m_platform->update();
while(queue.pollEvent(event)) { while(queue.pollEvent(event)) {
if (event.type == SysEvent::Quit) { if (event.type == Event::Quit) {
exit(); exit();
break; break;
} }
// Call message handler. // Call message handler.
if (event.type == SysEvent::Size) { if (event.type == Event::Size) {
m_messageHandler->onSizeChanged(event.size.display, event.size.width, event.size.height); m_messageHandler->onSizeChanged(event.size.window, event.size.width, event.size.height);
} }
m_messageHandler->onEvent(event);
} }
} }
@ -110,4 +117,9 @@ FPSCounter& Game::getFpsCounter()
return m_fpsCounter; return m_fpsCounter;
} }
MessageHandler* Game::getMessageHandler() const
{
return m_messageHandler;
} }
} // namespace sp

View file

@ -5,9 +5,9 @@
namespace sp { namespace sp {
FPSCounter::FPSCounter() : FPSCounter::FPSCounter() :
m_fps (60.0f), m_fps (60.0f)
m_updateRate (2000)
{ {
m_updateRate = Time::seconds(2);
reset(); reset();
} }
@ -16,19 +16,19 @@ void FPSCounter::addFrame()
m_count++; m_count++;
} }
float FPSCounter::getFPS() const double FPSCounter::getFPS() const
{ {
return m_fps; return m_fps;
} }
void FPSCounter::setUpdateRate(unsigned int ups) void FPSCounter::setUpdateRate(unsigned int rate)
{ {
// Clamp to 1. // Clamp to 1.
if (ups < 1) { if (rate < 1) {
ups = 1; rate = 1;
} }
m_updateRate = ups * 1000; m_updateRate = Time::seconds(rate);
// Must reset the counter. // Must reset the counter.
reset(); reset();
@ -36,15 +36,12 @@ void FPSCounter::setUpdateRate(unsigned int ups)
bool FPSCounter::update() bool FPSCounter::update()
{ {
unsigned int current = system::getMilliseconds(); Time elapsed = m_watch.elapsed();
unsigned int elapsed = current - m_time;
if (elapsed >= m_updateRate) { if (elapsed >= m_updateRate) {
float fraction = m_count / ((float) elapsed); m_fps = m_count / elapsed.seconds();
m_fps = fraction * 1000.f;
m_time = current; reset();
m_count = 0;
return true; return true;
} }
return false; return false;
@ -52,7 +49,7 @@ bool FPSCounter::update()
void FPSCounter::reset() void FPSCounter::reset()
{ {
m_time = system::getMilliseconds(); m_watch.restart();
m_count = 0; m_count = 0;
} }

View file

@ -7,44 +7,44 @@ namespace sp {
GameTime::GameTime(unsigned long updates_per_sec) GameTime::GameTime(unsigned long updates_per_sec)
{ {
m_acc = 0;
m_current = system::getMilliseconds();
m_lastUpdate = m_current;
setTimeStep(updates_per_sec); setTimeStep(updates_per_sec);
} }
double GameTime::getTimeStep() const double GameTime::getTimeStep() const
{ {
return m_slice; return m_slice.milliseconds();
} }
void GameTime::setTimeStep(unsigned long updates_per_sec) void GameTime::setTimeStep(unsigned long updates_per_sec)
{ {
m_slice = (1000.0f / ((double) updates_per_sec)); m_slice = Time::seconds(1.0f / ((double) updates_per_sec));
m_max_acc = Time::seconds(1.0f / m_slice.seconds());
reset(); reset();
} }
unsigned long GameTime::getElapsed() const Time GameTime::getElapsed() const
{ {
return m_current - m_lastUpdate; return m_watch.elapsed();
} }
bool GameTime::beginFrame() bool GameTime::beginFrame()
{ {
reset();
accumulateTime(); accumulateTime();
if (m_acc > m_slice) { // Signal if we should tick
m_inLoop = true; return shouldTick();
} }
return m_inLoop;
bool GameTime::shouldTick() const
{
// if acc is larger than one slice, we have atleast one tick.
return m_acc > m_slice;
} }
bool GameTime::tick() bool GameTime::tick()
{ {
if (m_acc > m_slice) { if (shouldTick()) {
m_acc -= m_slice; m_acc -= m_slice;
return true; return true;
} }
@ -53,27 +53,14 @@ bool GameTime::tick()
void GameTime::reset() void GameTime::reset()
{ {
m_lastUpdate = m_current; m_watch.restart();
m_inLoop = false;
} }
void GameTime::accumulateTime() void GameTime::accumulateTime()
{ {
updateTime(); m_acc += m_watch.restart();
if (m_acc > m_max_acc) {
m_acc += (double) (m_current - m_lastUpdate); m_acc = m_max_acc;
if (m_acc > (1000.f / m_slice)) {
m_acc = 1000.f / m_slice;
}
}
void GameTime::updateTime()
{
m_current = system::getMilliseconds();
// Just to be safe. check so we don't get a negative interval.
if (m_current < m_lastUpdate) {
m_lastUpdate = m_current;
} }
} }

View file

@ -0,0 +1,68 @@
#include "OpenGLDrv.h"
#include <GfxDriver/OpenGL/OpenGLShaderProgram.h>
#include <Graphics/GL/gl.h>
namespace sp {
std::string OpenGLDrv::getName() const {
return "OpenGL";
}
std::string OpenGLDrv::getVersion() const {
char buf[512];
std::string prof = "Compability";
GLint flags;
glGetIntegerv(GL_CONTEXT_PROFILE_MASK, &flags);
if (flags & GL_CONTEXT_CORE_PROFILE_BIT) {
prof = "Core";
}
snprintf(buf, sizeof(buf), "%s %s", prof.c_str(), glGetString(GL_VERSION));
return std::string(buf);
}
std::string OpenGLDrv::getVendor() const
{
return std::string((char*)glGetString(GL_VENDOR));
}
std::string OpenGLDrv::getCardName() const
{
return std::string((char*)glGetString(GL_RENDERER));
}
void OpenGLDrv::setViewport(int x, int y, int width, int height)
{
glViewport(x, y, width, height);
}
void OpenGLDrv::setClearColor(float r, float g, float b, float a)
{
glClearColor(r, g, b, 1.0f);
}
void OpenGLDrv::clearBuffer(GfxDriver::BufferFlags flags)
{
int glFlags = 0;
if (flags == GfxDriver::CLEAR_BUFFER_BIT) {
glFlags |= GL_COLOR_BUFFER_BIT;
}
glClear(glFlags);
}
void OpenGLDrv::clearColorBuffer()
{
glClear(GL_COLOR_BUFFER_BIT);
}
ShaderProgram* OpenGLDrv::createShaderProgram() {
return new OpenGLShaderProgram();
}
} // namespace sp

View file

@ -0,0 +1,35 @@
#ifndef SPECTRE_GFXDRIVER_OPENGL_OPENGLDRV_H
#define SPECTRE_GFXDRIVER_OPENGL_OPENGLDRV_H
#include <Spectre/GfxDriver/GfxDriver.h>
namespace sp {
class ShaderProgram;
class OpenGLDrv : public GfxDriver
{
public:
virtual std::string getName() const;
virtual std::string getVersion() const;
virtual std::string getVendor() const;
virtual std::string getCardName() const;
virtual void setViewport(int x, int y, int width, int height);
virtual void setClearColor(float r, float g, float b, float a);
virtual void clearBuffer(GfxDriver::BufferFlags flags);
virtual void clearColorBuffer();
virtual ShaderProgram* createShaderProgram();
};
} // namespace sp
#endif /* SPECTRE_GFXDRIVER_GFXDRIVER_H */

View file

@ -0,0 +1,185 @@
#include "OpenGLShaderProgram.h"
namespace sp {
OpenGLShaderProgram::OpenGLShaderProgram()
{
m_extension = "glsl";
m_id = glCreateProgram();
}
OpenGLShaderProgram::~OpenGLShaderProgram()
{
if (m_id > 0) {
glDeleteProgram(m_id);
}
}
bool OpenGLShaderProgram::loadFromMemory(const std::string& source, ShaderType type)
{
const char *s = source.c_str();
GLuint shader_id = glCreateShader(type == ShaderType::Vertex
? GL_VERTEX_SHADER : GL_FRAGMENT_SHADER);
glShaderSource(shader_id, 1, &s, NULL);
if (!compileShader(shader_id)) {
return false;
}
return attachShader(shader_id);
}
bool OpenGLShaderProgram::link()
{
GLint status;
glLinkProgram(m_id);
// Query OpenGL for link status.
glGetProgramiv(m_id, GL_LINK_STATUS, &status);
m_linked = status == GL_TRUE;
if (!m_linked) {
m_error = fetchErrorLog();
}
return m_linked;
}
// Enable this shader
// All shader operations after this call will affect this shader.
void OpenGLShaderProgram::enable() const
{
glUseProgram(m_id);
}
// Disable this shader
// Operations will no longer affect this shader after this call.
void OpenGLShaderProgram::disable() const
{
glUseProgram(0);
}
// ---------------------
// Variables.
// ---------------------
bool OpenGLShaderProgram::setMVPMatrix(const Matrix4f& matrix)
{
return setUniform("u_MVP", matrix);
}
// ---------------------
// General Variables.
// ---------------------
bool OpenGLShaderProgram::setAttribute(const std::string& name, float value) const
{
int loc;
if (getAttribLoc(name, loc)) {
glVertexAttrib1f(loc, value);
return true;
}
return false;
}
bool OpenGLShaderProgram::setAttribute(const std::string& name, const Matrix4f& matrix) const
{
int loc;
if (getAttribLoc(name, loc)) {
glVertexAttrib4fv(loc, matrix.e);
return true;
}
return false;
}
bool OpenGLShaderProgram::setUniform(const std::string& name, const Matrix4f& matrix) const
{
int loc;
if (getUniformLoc(name, loc)) {
glUniformMatrix4fv(loc, 1, GL_FALSE, matrix.e);
return true;
}
return false;
}
bool OpenGLShaderProgram::setUniform(const std::string& name, const Color& color) const
{
int loc;
if (getUniformLoc(name, loc)) {
Vector4f c = color.toRGBAf();
glUniform4f(loc, c.x, c.y, c.z, c.w);
return true;
}
return false;
}
bool OpenGLShaderProgram::getAttribLoc(const std::string& name, int& loc) const
{
loc = glGetAttribLocation(m_id, name.c_str());
if (loc < 0) {
m_error = "Attribute variable '" + name + "' was not found in shader.";
return false;
}
return true;
}
bool OpenGLShaderProgram::getUniformLoc(const std::string& name, int& loc) const
{
loc = glGetUniformLocation(m_id, name.c_str());
if (loc < 0) {
m_error = std::string("Uniform variable '" + name + "' was not found in shader.");
return false;
}
return true;
}
std::string OpenGLShaderProgram::fetchErrorLog() const
{
GLchar buf[4096] = { '\0' };
glGetProgramInfoLog(m_id, sizeof(buf), NULL, buf);
return std::string(buf);
}
bool OpenGLShaderProgram::compileShader(GLuint id)
{
glCompileShader(id);
// Query OpenGL for status.
GLint status;
glGetShaderiv(id, GL_COMPILE_STATUS, &status);
if (status == GL_FALSE) {
GLchar buf[4096] = { '\0' };
glGetShaderInfoLog(id, sizeof(buf), NULL, buf);
m_error = std::string(buf);
return false;
}
return true;
}
bool OpenGLShaderProgram::attachShader(GLuint id)
{
GLenum err;
glAttachShader(m_id, id);
err = glGetError();
if (err == GL_INVALID_VALUE) {
m_error = "Invalid Value";
return false;
} else if (err == GL_INVALID_OPERATION) {
m_error = "Invalid operation";
return false;
} else if (err != GL_NO_ERROR) {
m_error = "Unkown Error";
return false;
}
return true;
}
} // namespace sp

View file

@ -0,0 +1,70 @@
#ifndef SPECTRE_GFXDRIVER_OPENGL_OPENGLSHADERPROGRAM_H
#define SPECTRE_GFXDRIVER_OPENGL_OPENGLSHADERPROGRAM_H
#include <Graphics/GL/gl.h>
#include <Spectre/GfxDriver/ShaderProgram.h>
namespace sp {
class OpenGLShaderProgram : public ShaderProgram
{
public:
OpenGLShaderProgram();
virtual ~OpenGLShaderProgram();
// Load a shader from memory.
virtual bool loadFromMemory(const std::string& source, ShaderType type);
// Link the program.
virtual bool link();
// Enable this shader
// All shader operations after this call will affect this shader.
virtual void enable() const;
// Disable this shader
// Operations will no longer affect this shader after this call.
virtual void disable() const;
// ---------------------
// Variables.
// ---------------------
virtual bool setMVPMatrix(const Matrix4f& matrix);
// ---------------------
// General Variables.
// ---------------------
virtual bool setAttribute(const std::string& name, float value) const;
virtual bool setAttribute(const std::string& name, const Matrix4f& matrix) const;
virtual bool setUniform(const std::string& name, const Matrix4f& matrix) const;
virtual bool setUniform(const std::string& name, const Color& color) const;
protected :
// Compile a shader.
bool compileShader(GLuint id);
// Attach shader to program.
bool attachShader(GLuint id);
bool getAttribLoc(const std::string& name, int& loc) const;
bool getUniformLoc(const std::string& name, int& loc) const;
std::string fetchErrorLog() const;
protected :
// Program ID
GLuint m_id;
};
} // namespace sp
#endif /* SPECTRE_GFXDRIVER_OPENGL_OPENGLSHADERPROGRAM_H */

View file

@ -0,0 +1,69 @@
#include <Spectre/System/Path.h>
#include <Spectre/System/File.h>
#include <Spectre/GfxDriver/ShaderProgram.h>
#include <string>
namespace sp
{
ShaderProgram::~ShaderProgram()
{
}
bool ShaderProgram::loadFromFile(const std::string& filename)
{
std::string extension = Path::getExtension(filename);
// Meta file. load real shaders.
if (extension == "shader." + m_extension) {
// FIXME: This is ugly :)
std::string base_name = filename.substr(0, filename.length() - extension.length());
// vert and frag are not optional. they must exist.
return loadFromFile(base_name + "vert." + m_extension, ShaderType::Vertex) &&
loadFromFile(base_name + "frag." + m_extension, ShaderType::Fragment);
} else if (extension == "vert." + m_extension) {
return loadFromFile(filename, ShaderType::Vertex);
} else if (extension == "frag." + m_extension) {
return loadFromFile(filename, ShaderType::Fragment);
}
m_error = "Invalid file extension: " + extension;
return false;
}
bool ShaderProgram::loadFromFile(const std::string& filename, ShaderType type)
{
std::string src;
File file;
if (!file.open(filename)) {
m_error = "Can't open file: " + filename;
return false;
}
// Load file into memory.
if (!file.read(src)) {
m_error = "Could not read file: " + filename;
return false;
}
return loadFromMemory(src, type);
}
bool ShaderProgram::isLinked() const
{
return m_linked;
}
std::string ShaderProgram::getLastError() const
{
return m_error;
}
} // namespace sp

View file

@ -1,12 +1,12 @@
#include <Spectre/System/Log.h> #include <Spectre/System/Log.h>
#include <Spectre/Graphics/OpenGL.h>
#include <Spectre/Graphics/Renderable.h> #include <Spectre/Graphics/Renderable.h>
#include <Spectre/Graphics/RenderState.h> #include <Spectre/Graphics/RenderState.h>
#include <Spectre/Graphics/ShaderProgram.h>
#include <Spectre/Graphics/Texture.h> #include <Spectre/Graphics/Texture.h>
#include <Spectre/Graphics/BatchRenderer2D.h> #include <Spectre/Graphics/BatchRenderer2D.h>
#include <Spectre/Math/Math.h> #include <Spectre/Math/Math.h>
#include <GfxDriver/OpenGL/OpenGLShaderProgram.h>
#include <Graphics/GL/gl.h>
#include <algorithm> #include <algorithm>
@ -49,22 +49,24 @@ BatchRenderer2D::BatchRenderer2D()
glEnableVertexAttribArray(VertexAttribTexCoord0); glEnableVertexAttribArray(VertexAttribTexCoord0);
glVertexAttribPointer(VertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)24); glVertexAttribPointer(VertexAttribTexCoord0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)24);
m_textShader.create(); m_textShader = new OpenGLShaderProgram();
if (!m_textShader.loadFromFile("assets/shaders/text.shader.glsl")) {
std::cout << "Failed to load shader: " << m_textShader.getLastError() << std::endl; if (!m_textShader->loadFromFile("assets/shaders/text.shader.glsl")) {
std::cout << "Failed to load shader: " << m_textShader->getLastError() << std::endl;
} }
if (!m_textShader.link()) { if (!m_textShader->link()) {
std::cout << "Failed to link shader: " << m_textShader.getLastError() << std::endl; std::cout << "Failed to link shader: " << m_textShader->getLastError() << std::endl;
} }
m_spriteShader.create(); m_spriteShader = new OpenGLShaderProgram();
if (!m_spriteShader.loadFromFile("assets/shaders/standard.shader.glsl")) {
std::cout << "Failed to load shader: " << m_spriteShader.getLastError() << std::endl; if (!m_spriteShader->loadFromFile("assets/shaders/standard.shader.glsl")) {
std::cout << "Failed to load shader: " << m_spriteShader->getLastError() << std::endl;
} }
if (!m_spriteShader.link()) { if (!m_spriteShader->link()) {
std::cout << "Failed to link shader: " << m_spriteShader.getLastError() << std::endl; std::cout << "Failed to link shader: " << m_spriteShader->getLastError() << std::endl;
} }
} }
@ -73,6 +75,9 @@ BatchRenderer2D::~BatchRenderer2D()
glDeleteBuffers(1, &m_VBO); glDeleteBuffers(1, &m_VBO);
glDeleteBuffers(1, &m_IBO); glDeleteBuffers(1, &m_IBO);
glDeleteVertexArrays(1, &m_VAO); glDeleteVertexArrays(1, &m_VAO);
delete m_textShader;
delete m_spriteShader;
} }
void BatchRenderer2D::setBatchSize(unsigned short size) void BatchRenderer2D::setBatchSize(unsigned short size)
@ -146,13 +151,13 @@ void BatchRenderer2D::render()
glBindVertexArray(m_VAO); glBindVertexArray(m_VAO);
// Set shader uniforms. // Set shader uniforms.
m_textShader.enable(); m_textShader->enable();
m_textShader.setUniform("u_MVP", MVP); m_textShader->setUniform("u_MVP", MVP);
m_textShader.disable(); m_textShader->disable();
m_spriteShader.enable(); m_spriteShader->enable();
m_spriteShader.setUniform("u_MVP", MVP); m_spriteShader->setUniform("u_MVP", MVP);
m_spriteShader.disable(); m_spriteShader->disable();
prepareQueue(); prepareQueue();
@ -242,9 +247,9 @@ void BatchRenderer2D::drawBatch(Batch& batch)
glEnable(GL_BLEND); glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
shader = &m_textShader; shader = m_textShader;
} else { } else {
shader = &m_spriteShader; shader = m_spriteShader;
} }
// enable shader. // enable shader.

View file

@ -1,20 +1,21 @@
#include <Spectre/Graphics/Texture.h> #include <Spectre/Graphics/Texture.h>
#include <Spectre/Graphics/OpenGL.h>
#include <Spectre/Graphics/Renderable.h> #include <Spectre/Graphics/Renderable.h>
#include <Spectre/Graphics/DefaultRenderer2D.h> #include <Spectre/Graphics/DefaultRenderer2D.h>
#include <GfxDriver/OpenGL/OpenGLShaderProgram.h>
#include <Graphics/GL/gl.h>
namespace sp { namespace sp {
DefaultRenderer2D::DefaultRenderer2D() DefaultRenderer2D::DefaultRenderer2D()
{ {
m_shader.create(); m_shader = new OpenGLShaderProgram();
if (!m_shader.loadFromFile("assets/shaders/standard.shader.glsl")) { if (!m_shader->loadFromFile("assets/shaders/standard.shader.glsl")) {
std::cout << "Failed to load shader: " << m_shader.getLastError() << std::endl; std::cout << "Failed to load shader: " << m_shader->getLastError() << std::endl;
} }
if (!m_shader.link()) { if (!m_shader->link()) {
std::cout << "Failed to link shader: " << m_shader.getLastError() << std::endl; std::cout << "Failed to link shader: " << m_shader->getLastError() << std::endl;
} }
} }
@ -33,7 +34,7 @@ void DefaultRenderer2D::render()
viewMatrix = Matrix4f::Identity; viewMatrix = Matrix4f::Identity;
} }
m_shader.enable(); m_shader->enable();
glEnableVertexAttribArray(VertexAttribPosition); glEnableVertexAttribArray(VertexAttribPosition);
glEnableVertexAttribArray(VertexAttribColor0); glEnableVertexAttribArray(VertexAttribColor0);
@ -48,7 +49,7 @@ void DefaultRenderer2D::render()
const Texture *tex = obj->getTexture(); const Texture *tex = obj->getTexture();
Matrix4f modelViewMatrix = viewMatrix * obj->getTransform().getMatrix(); Matrix4f modelViewMatrix = viewMatrix * obj->getTransform().getMatrix();
m_shader.setMVPMatrix(modelViewMatrix); m_shader->setMVPMatrix(modelViewMatrix);
glVertexAttribPointer(VertexAttribPosition, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), data + 0); glVertexAttribPointer(VertexAttribPosition, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), data + 0);
glVertexAttribPointer(VertexAttribColor0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), data + 8); glVertexAttribPointer(VertexAttribColor0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), data + 8);
@ -69,7 +70,7 @@ void DefaultRenderer2D::render()
glDisableVertexAttribArray(VertexAttribColor0); glDisableVertexAttribArray(VertexAttribColor0);
glDisableVertexAttribArray(VertexAttribTexCoord0); glDisableVertexAttribArray(VertexAttribTexCoord0);
m_shader.disable(); m_shader->disable();
m_queue.clear(); m_queue.clear();
} }

View file

@ -5,27 +5,27 @@
#include <Spectre/Graphics/Image.h> #include <Spectre/Graphics/Image.h>
#include <Spectre/Graphics/Texture.h> #include <Spectre/Graphics/Texture.h>
#include <Spectre/Math/Math.h> #include <Spectre/Math/Math.h>
#include "Font/FreeTypeDriver.h" #include "Font/Engine/FreeTypeEngine.h"
namespace sp { namespace sp {
Font::Font() : Font::Font() :
m_driver (new FreeTypeDriver()) m_engine (new FreeTypeEngine())
{ {
} }
Font::~Font() Font::~Font()
{ {
delete m_driver; delete m_engine;
} }
bool Font::loadFromFile(const std::string& filename) bool Font::loadFromFile(const std::string& filename)
{ {
if (!m_driver->loadFromFile(filename)) { if (!m_engine->loadFromFile(filename)) {
return false; return false;
} }
if (!m_driver->setCharacterSize(22)) { if (!m_engine->setCharacterSize(22)) {
return false; return false;
} }
@ -42,7 +42,7 @@ bool Font::loadFromMemory(const void *data)
return false; return false;
} }
Font::Glyph Font::getGlyph(unsigned int code) const Glyph Font::getGlyph(unsigned int code) const
{ {
if (m_charset.find(code) == m_charset.end()) { if (m_charset.find(code) == m_charset.end()) {
@ -54,13 +54,13 @@ Font::Glyph Font::getGlyph(unsigned int code) const
void Font::loadChar(unsigned char code) const void Font::loadChar(unsigned char code) const
{ {
Image img; Image img;
Font::Glyph glyph; Glyph glyph;
if (!m_driver) { if (!m_engine) {
return; return;
} }
glyph = m_driver->loadGlyph(code, img); glyph = m_engine->loadGlyph(code, img);
if (glyph.size > vec2b(0, 0)) { if (glyph.size > vec2b(0, 0)) {

Some files were not shown because too many files have changed in this diff Show more