P-E-R-R-Y
Utilitaires, contrats et vendors du moteur, en une seule doc
Loading...
Searching...
No Matches
SdlWindow.hpp
Go to the documentation of this file.
1
10
11#ifndef SDLWINDOW_HPP_
12#define SDLWINDOW_HPP_
13
14//Sdl
15#include <SDL3/SDL.h>
16
17//Interface
18#include "IWindow2.hpp"
19
20//encapsulation
21#include "SdlGamepad.hpp"
22#include "SdlKeyboard.hpp"
23#include "SdlMouse.hpp"
24#include "SdlPolygon.hpp"
25#include "SdlSprite.hpp"
26#include "SdlText.hpp"
27
28#include <array>
29#include <string>
30#include <unordered_map>
31#include <vector>
32
50class SdlWindow : public graphic::IWindow2 {
51
52 public:
53 SdlWindow(int32_t screenWidth, int32_t screenHeight, std::string title) {
54 /* SDL3 ne prend plus de position : le gestionnaire place la
55 * fenetre, et setPosition() reste la pour qui veut choisir. */
56 _window = SDL_CreateWindow(title.c_str(), screenWidth, screenHeight,
57 SDL_WINDOW_HIGH_PIXEL_DENSITY);
58 if (!_window)
59 return;
60
61 //nullptr : on laisse SDL choisir son pilote, Metal sur macOS
62 _renderer = SDL_CreateRenderer(_window, nullptr);
63 if (_renderer) {
64 //sinon un alpha < 255 est ecrase au lieu d'etre melange
65 SDL_SetRenderDrawBlendMode(_renderer, SDL_BLENDMODE_BLEND);
66 /* Une unite de dessin = un pixel logique, quel que soit
67 * l'ecran. Sans ca, sur un ecran retina la souris et le
68 * dessin ne parlent plus du meme repere - le meme piege que
69 * la vue chez sfml. */
70 SDL_SetRenderLogicalPresentation(_renderer, screenWidth, screenHeight,
71 SDL_LOGICAL_PRESENTATION_LETTERBOX);
72 }
73
74 _id = SDL_GetWindowID(_window);
75 registry()[_id] = this;
76 _lastTicks = SDL_GetTicks();
77 }
78
80 /* On part : si c'est nous qui l'avions cache, on le rend. Le
81 * pump suivant le recachera si la souris se trouve sur une
82 * autre fenetre qui le demande. */
83 registry().erase(_id);
84 if (!_cursor && !shown()) {
85 shown() = true;
86 SDL_ShowCursor();
87 }
88 if (_renderer)
89 SDL_DestroyRenderer(_renderer);
90 if (_window)
91 SDL_DestroyWindow(_window);
92 }
93
94 //lifecycle
95 bool isOpen() override { return _open && _window != nullptr; }
96
97 void close() override { _open = false; }
98
99 Vector2f getPosition() override {
100 int x = 0, y = 0;
101
102 SDL_GetWindowPosition(_window, &x, &y);
103 return {static_cast<double>(x), static_cast<double>(y)};
104 }
105
106 void setPosition(Vector2f position) override {
107 SDL_SetWindowPosition(_window, static_cast<int>(position.x), static_cast<int>(position.y));
108 }
109
110 Vector2f getSize() override {
111 int w = 0, h = 0;
112
113 SDL_GetWindowSize(_window, &w, &h);
114 return {static_cast<double>(w), static_cast<double>(h)};
115 }
116
117 void setSize(Vector2f size) override {
118 SDL_SetWindowSize(_window, static_cast<int>(size.x), static_cast<int>(size.y));
119 if (_renderer)
120 SDL_SetRenderLogicalPresentation(_renderer, static_cast<int>(size.x), static_cast<int>(size.y),
121 SDL_LOGICAL_PRESENTATION_LETTERBOX);
122 }
123
124 void setFrameLimit(int32_t limit) override { _frameLimit = limit; }
125
140 void setMouseVisibility(bool visible) override { _cursor = visible; }
141
142 int32_t getDelta() override { return _delta; }
143
150 bool pollEvent() override {
151 pump();
152 return !_events.empty();
153 }
154
155 void eventClose() override {
156 for (const SDL_Event &event : _events) {
157 if (event.type == SDL_EVENT_QUIT ||
158 event.type == SDL_EVENT_WINDOW_CLOSE_REQUESTED ||
159 (event.type == SDL_EVENT_KEY_DOWN && event.key.scancode == SDL_SCANCODE_ESCAPE)) {
160 _open = false;
161 return;
162 }
163 }
164 }
165
166 //2D
167 void beginDraw() override {
168 if (!_renderer)
169 return;
170 SDL_SetRenderDrawColor(_renderer, 0, 0, 0, 255);
171 SDL_RenderClear(_renderer);
172 }
173
174 void endDraw() override {
175 if (_renderer)
176 SDL_RenderPresent(_renderer);
177
178 const uint64_t now = SDL_GetTicks();
179
180 _delta = static_cast<int32_t>(now - _lastTicks);
181
182 /* SDL n'a pas de limiteur : on attend nous-memes de quoi tenir
183 * la cadence demandee, sinon la boucle tourne a vide et mange
184 * un coeur entier. */
185 if (_frameLimit > 0) {
186 const int32_t budget = 1000 / _frameLimit;
187
188 if (_delta < budget) {
189 SDL_Delay(static_cast<uint32_t>(budget - _delta));
190 _delta = budget;
191 }
192 }
193
194 _lastTicks = SDL_GetTicks();
195 _events.clear(); //la frontiere de frame, cf. IWindow::pollEvent
196 }
197
198 void drawPoly(graphic::IPolygon *polygon) override;
199 void drawSprite(graphic::ISprite *sprite) override;
200 void drawText(graphic::IText *text) override;
201
202 friend class SdlKeyboard;
203 friend class SdlMouse;
204 friend class SdlGamepad;
205
206 private:
208 static std::unordered_map<uint32_t, SdlWindow *> &registry() {
209 static std::unordered_map<uint32_t, SdlWindow *> windows;
210
211 return windows;
212 }
213
222 static void pump() {
223 SDL_Event event;
224
225 /* Le curseur AVANT la file : l'etat suit le survol, et le survol
226 * a pu changer depuis la frame precedente meme sans evenement. */
227 applyCursor(SDL_GetMouseFocus());
228
229 while (SDL_PollEvent(&event)) {
230 const uint32_t target = windowOf(event);
231
232 if (target == 0) {
233 for (auto &[id, window] : registry())
234 window->push(event);
235 continue;
236 }
237
238 const auto found = registry().find(target);
239
240 if (found == registry().end())
241 continue; //une fenetre deja detruite : l'evenement tombe
242 found->second->push(event);
243 }
244 }
245
257 static void applyCursor(SDL_Window *focused) {
258 if (!focused)
259 return;
260
261 const auto found = registry().find(SDL_GetWindowID(focused));
262
263 if (found == registry().end())
264 return;
265
266 const bool wanted = found->second->_cursor;
267
268 if (wanted == shown())
269 return;
270 shown() = wanted;
271 if (wanted)
272 SDL_ShowCursor();
273 else
274 SDL_HideCursor();
275 }
276
278 static bool &shown() {
279 static bool visible = true;
280
281 return visible;
282 }
283
285 static uint32_t windowOf(const SDL_Event &event) {
286 /* SDL3 a eclate SDL_WINDOWEVENT en un type par cas, tous ranges
287 * dans une plage : les prendre d'un bloc evite d'en oublier un
288 * a chaque version. */
289 if (event.type >= SDL_EVENT_WINDOW_FIRST && event.type <= SDL_EVENT_WINDOW_LAST)
290 return event.window.windowID;
291
292 switch (event.type) {
293 case SDL_EVENT_KEY_DOWN:
294 case SDL_EVENT_KEY_UP: return event.key.windowID;
295 case SDL_EVENT_MOUSE_BUTTON_DOWN:
296 case SDL_EVENT_MOUSE_BUTTON_UP: return event.button.windowID;
297 case SDL_EVENT_MOUSE_MOTION: return event.motion.windowID;
298 case SDL_EVENT_MOUSE_WHEEL: return event.wheel.windowID;
299 case SDL_EVENT_TEXT_INPUT: return event.text.windowID;
300 default: return 0;
301 }
302 }
303
313 void push(const SDL_Event &event) {
314 if (_events.size() >= MAX_EVENTS)
315 _events.erase(_events.begin());
316 _events.push_back(event);
317 feedEvent(event);
318 }
319
320 /* L'etat reconstruit DEPUIS LES EVENEMENTS, jamais par une requete
321 * globale comme SDL_GetKeyboardState() : celle-la est commune au
322 * processus, donc deux fenetres y liraient la meme chose meme si
323 * une seule a le focus.
324 *
325 * Seul ce qu'aucun evenement ne peut dire est garde : une touche
326 * reste "enfoncee" entre son KEYDOWN et son KEYUP. Les fronts, eux,
327 * se relisent dans _events, qui porte la frame. */
328 void feedEvent(const SDL_Event &event) {
329 switch (event.type) {
330 case SDL_EVENT_KEY_DOWN:
331 if (!event.key.repeat)
332 _keysDown[event.key.scancode] = true;
333 break;
334 case SDL_EVENT_KEY_UP:
335 _keysDown[event.key.scancode] = false;
336 break;
337 case SDL_EVENT_MOUSE_BUTTON_DOWN:
338 _mouseDown[event.button.button] = true;
339 break;
340 case SDL_EVENT_MOUSE_BUTTON_UP:
341 _mouseDown[event.button.button] = false;
342 break;
343 case SDL_EVENT_MOUSE_MOTION:
344 _mousePosition = {static_cast<double>(event.motion.x), static_cast<double>(event.motion.y)};
345 break;
346 case SDL_EVENT_WINDOW_FOCUS_LOST:
347 //sans ca, une touche relachee hors focus resterait "enfoncee"
348 _keysDown.fill(false);
349 _mouseDown.fill(false);
350 break;
351 default:
352 break;
353 }
354 }
355
357 static constexpr size_t MAX_EVENTS = 1024;
358
359 SDL_Window *_window = nullptr;
360 SDL_Renderer *_renderer = nullptr;
361 uint32_t _id = 0;
362 bool _open = true;
363 bool _cursor = true;
364
365 /* Les evenements de la frame. Rempli par pump(), vide par endDraw() :
366 * entre les deux, tout le monde y lit la meme chose. */
367 std::vector<SDL_Event> _events;
368
369 uint64_t _lastTicks = 0;
370 int32_t _delta = 0;
371 int32_t _frameLimit = 0;
372
373 std::array<bool, SDL_SCANCODE_COUNT> _keysDown{};
374 std::array<bool, 8> _mouseDown{};
375 Vector2f _mousePosition{0, 0};
376};
377
379 SdlPolygon *sdlPolygon = static_cast<SdlPolygon *>(polygon);
380
381 if (!_renderer || sdlPolygon->_vertices.empty())
382 return;
383
384 /* SDL_RenderGeometry n'a pas de transformation : il faut lui donner des
385 * coordonnees ecran. On recopie les sommets locaux en ajoutant la
386 * position, dans un tampon qui appartient au polygone - donc aucune
387 * allocation apres la premiere frame. */
388 const float x = static_cast<float>(sdlPolygon->_position.x);
389 const float y = static_cast<float>(sdlPolygon->_position.y);
390
391 for (size_t i = 0; i < sdlPolygon->_vertices.size(); i++) {
392 sdlPolygon->_screen[i] = sdlPolygon->_vertices[i];
393 sdlPolygon->_screen[i].position.x += x;
394 sdlPolygon->_screen[i].position.y += y;
395 }
396
397 SDL_RenderGeometry(_renderer, nullptr,
398 sdlPolygon->_screen.data(), static_cast<int>(sdlPolygon->_screen.size()),
399 nullptr, 0);
400}
401
403 SdlSprite *sdlSprite = static_cast<SdlSprite *>(sprite);
404 SDL_Texture *texture = sdlSprite->_texture.handle(_renderer);
405
406 if (!texture)
407 return;
408
409 /* SDL3 est passe au flottant partout : plus d'arrondi au pixel entier
410 * entre ce que le contrat donne et ce qui est trace. */
411 const SDL_FRect source{
412 sdlSprite->_crop.x, sdlSprite->_crop.y,
413 sdlSprite->_crop.w, sdlSprite->_crop.h};
414 const SDL_FRect destination{
415 static_cast<float>(sdlSprite->_position.x), static_cast<float>(sdlSprite->_position.y),
416 static_cast<float>(sdlSprite->_size.x), static_cast<float>(sdlSprite->_size.y)};
417
418 SDL_RenderTextureRotated(_renderer, texture, &source, &destination,
419 sdlSprite->_rotation, nullptr, SDL_FLIP_NONE);
420}
421
423 SdlText *sdlText = static_cast<SdlText *>(text);
424 SDL_Texture *texture = sdlText->handle(_renderer);
425
426 if (!texture)
427 return;
428
429 const SDL_FRect destination{
430 static_cast<float>(sdlText->_position.x), static_cast<float>(sdlText->_position.y),
431 static_cast<float>(sdlText->_width), static_cast<float>(sdlText->_height)};
432
433 SDL_RenderTextureRotated(_renderer, texture, nullptr, &destination,
434 sdlText->_rotation, nullptr, SDL_FLIP_NONE);
435}
436
437/* Entrees.
438 *
439 * isKeyPressed / isKeyReleased : les evenements de la frame sont encore
440 * dans _events, donc un front s'y relit. Rien n'est consomme, donc
441 * n'importe quel nombre de lecteurs obtient la meme reponse.
442 * isKeyDown / isKeyUp : l'etat que la fenetre tient, puisqu'aucun
443 * evenement seul ne peut dire qu'une touche est toujours enfoncee.
444 */
445
447template <typename Match>
448static bool anyEvent(const std::vector<SDL_Event> &events, uint32_t type, Match match) {
449 for (const SDL_Event &event : events)
450 if (event.type == type && match(event))
451 return true;
452 return false;
453}
454
455std::vector<graphic::IKeyboard::Keys> SdlKeyboard::whichKeyDown() const {
456 std::vector<Keys> keys;
457
458 for (const auto &[key, code] : _keys)
459 if (_window._keysDown[code])
460 keys.push_back(key);
461 return keys;
462}
463
464bool SdlKeyboard::isKeyPressed(Keys key) const {
465 const SDL_Scancode code = _keys.at(key);
466
467 return anyEvent(_window._events, SDL_EVENT_KEY_DOWN,
468 [code](const SDL_Event &event) { return event.key.scancode == code && !event.key.repeat; });
469}
470
471bool SdlKeyboard::isKeyReleased(Keys key) const {
472 const SDL_Scancode code = _keys.at(key);
473
474 return anyEvent(_window._events, SDL_EVENT_KEY_UP,
475 [code](const SDL_Event &event) { return event.key.scancode == code; });
476}
477
478bool SdlKeyboard::isKeyDown(Keys key) const { return _window._keysDown[_keys.at(key)]; }
479bool SdlKeyboard::isKeyUp(Keys key) const { return !isKeyDown(key); }
480
481bool SdlMouse::isButtonPressed(Buttons key) const {
482 const uint8_t button = _buttons.at(key);
483
484 return anyEvent(_window._events, SDL_EVENT_MOUSE_BUTTON_DOWN,
485 [button](const SDL_Event &event) { return event.button.button == button; });
486}
487
488bool SdlMouse::isButtonReleased(Buttons key) const {
489 const uint8_t button = _buttons.at(key);
490
491 return anyEvent(_window._events, SDL_EVENT_MOUSE_BUTTON_UP,
492 [button](const SDL_Event &event) { return event.button.button == button; });
493}
494
495bool SdlMouse::isButtonDown(Buttons key) const { return _window._mouseDown[_buttons.at(key)]; }
496bool SdlMouse::isButtonUp(Buttons key) const { return !isButtonDown(key); }
497
498Vector2f SdlMouse::getPosition() const { return _window._mousePosition; }
499
500void SdlMouse::setPosition(Vector2f position) {
501 _window._mousePosition = position;
502 SDL_WarpMouseInWindow(_window._window, static_cast<float>(position.x), static_cast<float>(position.y));
503}
504
505float SdlMouse::GetMouseWheelMove() const {
506 float delta = 0.f;
507
508 //additionne : deux crans dans la meme frame, sinon on en perd un
509 for (const SDL_Event &event : _window._events)
510 if (event.type == SDL_EVENT_MOUSE_WHEEL)
511 delta += event.wheel.y; //deja flottant en SDL3
512 return delta;
513}
514
515bool SdlGamepad::isButtonPressed(Button button) const {
516 const SDL_GamepadButton raw = _buttons.at(button);
517
518 return anyEvent(_window._events, SDL_EVENT_GAMEPAD_BUTTON_DOWN,
519 [raw](const SDL_Event &event) { return event.gbutton.button == raw; });
520}
521
522bool SdlGamepad::isButtonReleased(Button button) const {
523 const SDL_GamepadButton raw = _buttons.at(button);
524
525 return anyEvent(_window._events, SDL_EVENT_GAMEPAD_BUTTON_UP,
526 [raw](const SDL_Event &event) { return event.gbutton.button == raw; });
527}
528
530
531#endif /* !SDLWINDOW_HPP_ */
SDL_Texture * handle(SDL_Renderer *renderer) const
La texture pour CE renderer, fabriquee au besoin.
Definition SdlTexture.hpp:64
Une fenetre SDL et son renderer, implemente IWindow2.
Definition SdlWindow.hpp:50
~SdlWindow()
Definition SdlWindow.hpp:79
Vector2f getPosition() override
Where the window sits on the desktop, in pixels, origin top-left of the primary screen.
Definition SdlWindow.hpp:99
void eventClose() override
notice the window that a close was requested
Definition SdlWindow.hpp:155
void drawText(graphic::IText *text) override
draw a text
SdlWindow(int32_t screenWidth, int32_t screenHeight, std::string title)
Definition SdlWindow.hpp:53
bool pollEvent() override
Vide la file SDL une fois, puis rend l'etat de CETTE fenetre.
Definition SdlWindow.hpp:150
void setPosition(Vector2f position) override
Move the window on the desktop.
Definition SdlWindow.hpp:106
void drawSprite(graphic::ISprite *sprite) override
draw a sprite
void setFrameLimit(int32_t limit) override
Set the Frame Limit object.
Definition SdlWindow.hpp:124
void setSize(Vector2f size) override
Resize the drawable area.
Definition SdlWindow.hpp:117
friend class SdlMouse
Definition SdlWindow.hpp:200
friend class SdlKeyboard
Definition SdlWindow.hpp:199
void beginDraw() override
allowing to draw 2D on the window
Definition SdlWindow.hpp:167
void drawPoly(graphic::IPolygon *polygon) override
draw a polygon
void endDraw() override
end the 2D drawing
Definition SdlWindow.hpp:174
int32_t getDelta() override
Get the Delta object.
Definition SdlWindow.hpp:142
friend class SdlGamepad
Definition SdlWindow.hpp:201
Vector2f getSize() override
The drawable area, in pixels - NOT the desktop size. A hit-test built on IMouse::getPosition() compar...
Definition SdlWindow.hpp:110
void close() override
close the window
Definition SdlWindow.hpp:97
void setMouseVisibility(bool visible) override
Cache ou montre le pointeur SUR CETTE FENETRE.
Definition SdlWindow.hpp:140
bool isOpen() override
notice if the window is open
Definition SdlWindow.hpp:95
Button
Definition IGamepad.hpp:30
Polygon interface.
Definition IPolygon.hpp:34
Sprite interface.
Definition ISprite.hpp:22
Text interface.
Definition IText.hpp:26
A window that can draw 2D. Adds only the 2D drawing surface on top of IWindow's lifecycle/input.
Definition IWindow2.hpp:25
bool isKeyPressed(Keys key) const override
Check if the key is pressed.
Definition SdlWindow.hpp:453
void drawText(graphic::IText *text) override
draw a text
Definition SdlWindow.hpp:411
bool isKeyDown(Keys key) const override
Check if the key is down.
Definition SdlWindow.hpp:467
bool isButtonPressed(Buttons key) const override
notice if a button is pressed
Definition SdlWindow.hpp:470
void drawSprite(graphic::ISprite *sprite) override
draw a sprite
Definition SdlWindow.hpp:393
void setPosition(Vector2f position) override
set the position of the mouse
Definition SdlWindow.hpp:489
bool isButtonDown(Buttons key) const override
notice if a button is down
Definition SdlWindow.hpp:484
bool isKeyUp(Keys key) const override
Check if the key is up.
Definition SdlWindow.hpp:468
void drawPoly(graphic::IPolygon *polygon) override
draw a polygon
Definition SdlWindow.hpp:369
float GetMouseWheelMove() const override
get the mouse wheel move
Definition SdlWindow.hpp:494
bool isButtonReleased(Buttons key) const override
notice if a button is released
Definition SdlWindow.hpp:477
bool isButtonUp(Buttons key) const override
notice if a button is up
Definition SdlWindow.hpp:485
bool isButtonReleased(Button button) const override
notice if the button is released
Definition SdlWindow.hpp:511
bool isKeyReleased(Keys key) const override
Check if the key is released.
Definition SdlWindow.hpp:460
bool isButtonPressed(Button button) const override
notice if the button is pressed
Definition SdlWindow.hpp:504
Vector2f getPosition() const override
get the position of the mouse
Definition SdlWindow.hpp:487
std::vector< Keys > whichKeyDown() const override
Every key HELD right now - like isKeyDown, without having to name the key.
Definition SdlWindow.hpp:444
Vector2< double > Vector2f
Definition Vector2.hpp:112
T w
Definition Shape.hpp:33
T h
Definition Shape.hpp:33
T y
Definition Shape.hpp:33
T x
Definition Shape.hpp:33
T y
Definition Vector2.hpp:21
T x
Definition Vector2.hpp:21