-
Notifications
You must be signed in to change notification settings - Fork 210
/
Canvas.cpp
1137 lines (920 loc) · 33 KB
/
Canvas.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (c) 2014 Aerys
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING
BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include "minko/Canvas.hpp"
#include "minko/data/Provider.hpp"
#include "minko/async/Worker.hpp"
#include "minko/file/Options.hpp"
#include "minko/log/Logger.hpp"
#include "minko/SDLBackend.hpp"
#include "minko/scene/Node.hpp"
#include "minko/component/SceneManager.hpp"
#include "minko/component/Renderer.hpp"
#include "minko/component/Transform.hpp"
#include "minko/component/Camera.hpp"
#if MINKO_PLATFORM != MINKO_PLATFORM_HTML5 && MINKO_PLATFORM != MINKO_PLATFORM_ANDROID
# include "minko/file/FileProtocolWorker.hpp"
#endif
#if MINKO_PLATFORM == MINKO_PLATFORM_ANDROID
# include "minko/file/APKProtocolWorker.hpp"
#endif
#include "SDL.h"
#include "SDL_syswm.h"
#if MINKO_PLATFORM == MINKO_PLATFORM_HTML5
# include "minko/SDLWebGLBackend.hpp"
#elif MINKO_PLATFORM == MINKO_PLATFORM_ANDROID
# include "minko/file/APKProtocol.hpp"
#elif MINKO_PLATFORM == MINKO_PLATFORM_IOS
// # include "SDL_opengles.h"
// # include "SDL_syswm.h"
#elif defined(MINKO_PLUGIN_ANGLE)
# include "minko/MinkoAngle.hpp"
#elif defined(MINKO_PLUGIN_OFFSCREEN)
# include "minko/MinkoOffscreen.hpp"
#endif
#include "minko/audio/SDLAudio.hpp"
#if MINKO_PLATFORM == MINKO_PLATFORM_WINDOWS
# include "Windows.h"
#endif
using namespace minko;
using namespace minko::component;
using namespace minko::scene;
using namespace minko::async;
Canvas::Canvas(const std::string& name, const uint width, const uint height, int flags) :
_name(name),
_flags(flags),
_data(data::Provider::create()),
_active(false),
_previousTime(std::chrono::high_resolution_clock::now()),
_startTime(std::chrono::high_resolution_clock::now()),
_framerate(0.f),
_desiredFramerate(60.f),
_desiredFramerateChanged(false),
_desiredEventrate(60.f),
_swapBuffersAtEnterFrame(true),
_enterFrame(Signal<AbstractCanvas::Ptr, float, float, bool>::create()),
_resized(Signal<AbstractCanvas::Ptr, uint, uint>::create()),
_fileDropped(Signal<const std::string&>::create()),
_joystickAdded(Signal<AbstractCanvas::Ptr, std::shared_ptr<input::Joystick>>::create()),
_joystickRemoved(Signal<AbstractCanvas::Ptr, std::shared_ptr<input::Joystick>>::create()),
_suspended(Signal<AbstractCanvas::Ptr>::create()),
_resumed(Signal<AbstractCanvas::Ptr>::create()),
_width(width),
_height(height),
_x(0),
_y(0),
_onWindow(false),
_enableRendering(true)
{
_data->set("viewport", math::vec4(0.f, 0.f, (float)width, (float)height));
}
void
Canvas::initialize()
{
#if MINKO_PLATFORM == MINKO_PLATFORM_ANDROID
file::Options::registerDefaultProtocol<file::APKProtocol>("file");
#endif
#if MINKO_PLATFORM == MINKO_PLATFORM_IOS
// Exclude Library and Document folders from iCloud backup system
NSString* appLibraryFolder = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString* appDocumentFolder = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSArray* backupFolders = [NSArray arrayWithObjects: appLibraryFolder, appDocumentFolder, nil];
NSURL * url;
for (NSString* folder in backupFolders)
{
url = [NSURL fileURLWithPath:folder];
assert([[NSFileManager defaultManager] fileExistsAtPath: [url path]]);
NSLog(@"Final URL: %@", url);
NSError *error = nil;
BOOL success = [url setResourceValue: [NSNumber numberWithBool: YES]
forKey: NSURLIsExcludedFromBackupKey error: &error];
if(!success)
NSLog(@"Error excluding %@ from backup %@", [url lastPathComponent], error);
}
#endif
initializeWindow();
initializeContext();
initializeInputs();
#if MINKO_PLATFORM != MINKO_PLATFORM_HTML5 && MINKO_PLATFORM != MINKO_PLATFORM_ANDROID
registerWorker<file::FileProtocolWorker>("file-protocol");
#endif
#if MINKO_PLATFORM == MINKO_PLATFORM_ANDROID
registerWorker<file::APKProtocolWorker>("apk-protocol");
#endif
#if MINKO_PLATFORM == MINKO_PLATFORM_WINDOWS
SetConsoleCtrlHandler([](DWORD type) -> BOOL { return type == CTRL_CLOSE_EVENT; }, true);
#endif
}
void
Canvas::initializeInputs()
{
_mouse = input::SDLMouse::create(shared_from_this());
_keyboard = input::SDLKeyboard::create();
_touch = input::SDLTouch::create(shared_from_this());
#if (MINKO_PLATFORM & (MINKO_PLATFORM_LINUX | MINKO_PLATFORM_OSX | MINKO_PLATFORM_WINDOWS))
for (int i = 0; i < SDL_NumJoysticks(); ++i)
{
SDL_Joystick* joystick = SDL_JoystickOpen(i);
if (!joystick)
continue;
else
_joysticks[i] = input::SDLJoystick::create(shared_from_this(), SDL_JoystickInstanceID(joystick), joystick);
}
#endif
}
void
Canvas::initializeWindow()
{
#if MINKO_PLATFORM == MINKO_PLATFORM_ANDROID
// SDL_SetHint() function MUST be called before SDL_Init()
// Android accelerometer will not be considered as a joystick anymore
SDL_SetHint(SDL_HINT_ACCELEROMETER_AS_JOYSTICK, "0");
#endif
int initFlags = 0;
#if !defined(MINKO_PLUGIN_OFFSCREEN)
initFlags = SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_JOYSTICK;
#endif
if (SDL_Init(initFlags) < 0)
throw std::runtime_error(SDL_GetError());
if (_flags & STENCIL)
SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8);
#if MINKO_PLATFORM == MINKO_PLATFORM_IOS || MINKO_PLATFORM == MINKO_PLATFORM_ANDROID
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_ES);
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 0);
#endif
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 0);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BUFFER_SIZE, 32);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 16);
// SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0);
SDL_GL_SetSwapInterval(0);
#if MINKO_PLATFORM == MINKO_PLATFORM_HTML5
SDL_WM_SetCaption(_name.c_str(), nullptr);
SDL_SetVideoMode(_width, _height, 0, SDL_OPENGL | SDL_WINDOW_RESIZABLE);
_window = nullptr;
#else
int windowFlags = SDL_WINDOW_OPENGL;
if (_flags & RESIZABLE)
windowFlags |= SDL_WINDOW_RESIZABLE;
if (_flags & CHROMELESS)
windowFlags |= SDL_WINDOW_BORDERLESS;
if (_flags & FULLSCREEN)
windowFlags |= SDL_WINDOW_FULLSCREEN;
if (_flags & HIDDEN)
windowFlags |= SDL_WINDOW_HIDDEN;
# if !defined(MINKO_PLUGIN_OFFSCREEN)
_window = SDL_CreateWindow(
_name.c_str(),
SDL_WINDOWPOS_CENTERED, // SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_CENTERED, // SDL_WINDOWPOS_UNDEFINED,
_width, _height,
windowFlags
);
// Reset window size after window creation because certain platforms (iOS, Android)
// ignore passed arguments and use fullscreen window size. Not failing if the
// window couln't be created (Offscreen support).
if (_window)
{
int w, h;
SDL_GetWindowSize(_window, &w, &h);
width(w);
height(h);
}
else
{
const auto error = SDL_GetError();
LOG_ERROR(error);
}
# endif
_audio = audio::SDLAudio::create(shared_from_this());
#endif
}
void*
Canvas::systemWindow() const
{
SDL_Window* sdlWindow = _window;
SDL_SysWMinfo info;
SDL_VERSION(&info.version);
if (SDL_GetWindowWMInfo(sdlWindow, &info))
{
#if MINKO_PLATFORM == MINKO_PLATFORM_IOS
return info.info.uikit.window;
#elif MINKO_PLATFORM == MINKO_PLATFORM_OSX
return info.info.cocoa.window;
#elif MINKO_PLATFORM == MINKO_PLATFORM_WINDOWS
return info.info.win.window;
#endif
}
return nullptr;
}
void
Canvas::initializeContext()
{
#if (MINKO_PLATFORM == MINKO_PLATFORM_WINDOWS) && defined(MINKO_PLUGIN_ANGLE)
_backend = SDLAngleBackend::create();
#elif (defined(MINKO_PLUGIN_OFFSCREEN))
_backend = SDLOffscreenBackend::create();
#elif MINKO_PLATFORM == MINKO_PLATFORM_HTML5
_backend = SDLWebGLBackend::create();
#else
_backend = SDLBackend::create();
#endif
_backend->initialize(shared_from_this());
_context = minko::render::OpenGLES2Context::create();
if (!_context)
throw std::runtime_error("Could not create context");
}
Canvas::NodePtr
Canvas::createScene()
{
auto sceneManager = SceneManager::create(shared_from_this());
auto root = Node::create("root")
->addComponent(sceneManager);
_camera = Node::create("camera")
->addComponent(Renderer::create(0x7f7f7fff))
->addComponent(Transform::create(
math::inverse(math::lookAt(math::vec3(0.f, 0.f, 3.f), math::vec3(), math::vec3(0.f, 1.f, 0.f)))
))
->addComponent(Camera::create(math::perspective(.785f, shared_from_this()->aspectRatio(), 0.1f, 1000.f)));
root->addChild(_camera);
_resizedSlot = _resized->connect([&](AbstractCanvas::Ptr canvas, uint w, uint h)
{
_camera->component<Camera>()->projectionMatrix(math::perspective(.785f, float(w) / float(h), 0.1f, 1000.f));
});
return root;
}
uint
Canvas::x()
{
return _x;
}
uint
Canvas::y()
{
return _y;
}
uint
Canvas::width()
{
return _width;
}
uint
Canvas::height()
{
return _height;
}
void
Canvas::x(uint value)
{
if (value != _x)
{
auto viewport = _data->get<math::vec4>("viewport");
_x = value;
viewport.x = (float)value;
_data->set<math::vec4>("viewport", viewport);
}
}
void
Canvas::y(uint value)
{
if (value != _y)
{
auto viewport = _data->get<math::vec4>("viewport");
_y = value;
viewport.y = (float)value;
_data->set<math::vec4>("viewport", viewport);
}
}
void
Canvas::width(uint value)
{
if (value != _width)
{
auto viewport = _data->get<math::vec4>("viewport");
_width = value;
viewport.z = (float)value;
_data->set<math::vec4>("viewport", viewport);
}
}
void
Canvas::height(uint value)
{
if (value != _height)
{
auto viewport = _data->get<math::vec4>("viewport");
_height = value;
viewport.w = (float)value;
_data->set<math::vec4>("viewport", viewport);
}
}
void
Canvas::step()
{
auto that = shared_from_this();
#if MINKO_PLATFORM == MINKO_PLATFORM_HTML5
// Detect new joystick
auto invalidJoysticks = 0;
for (int i = 0; i < SDL_NumJoysticks(); i++)
{
if (!SDL_JoystickOpened(i))
{
auto joystick = SDL_JoystickOpen(i);
if (joystick)
{
if (_joysticks.find(i) == _joysticks.end())
{
auto sdlJoystick = input::SDLJoystick::create(that, i, joystick);
_joysticks[i] = sdlJoystick;
}
_joystickAdded->execute(that, _joysticks[i]);
# if defined(DEBUG)
printf("New joystick found!\n");
printf("Joystick %i\n", i);
printf("Name: %s\n", SDL_JoystickName(i));
printf("Number of Axes: %d\n", SDL_JoystickNumAxes(joystick));
printf("Number of Buttons: %d\n", SDL_JoystickNumButtons(joystick));
printf("Number of Balls: %d\n", SDL_JoystickNumBalls(joystick));
# endif // DEBUG
}
else
{
invalidJoysticks++;
}
}
}
// A gamepad has been removed ?
if (_joysticks.size() != (SDL_NumJoysticks() - invalidJoysticks))
{
// We looking for the missing gamepad
int joystickId = 0;
for (auto it = _joysticks.begin(); it != _joysticks.end(); ++it)
{
if (!SDL_JoystickOpen(it->first))
{
joystickId = it->first;
break;
}
}
auto joystick = _joysticks[joystickId]->_joystick;
_joystickRemoved->execute(that, _joysticks[joystickId]);
SDL_JoystickClose(joystick);
_joysticks.erase(joystickId);
}
#endif
SDL_Event event;
#if MINKO_PLATFORM != MINKO_PLATFORM_HTML5
SDL_EventState(SDL_DROPFILE, SDL_ENABLE);
#endif // MINKO_PLATFORM != MINKO_PLATFORM_HTML5
auto enteredOrLeftThisFrame = false;
std::vector<char16_t> chars;
auto executeMouseMove = false;
auto executePinchZoom = false;
_mouse->dX(0);
_mouse->dY(0);
auto mouseDX = 0;
auto mouseDY = 0;
_touch->resetDeltas();
while (SDL_PollEvent(&event))
{
switch (event.type)
{
case SDL_QUIT:
{
quit();
break;
}
#if MINKO_PLATFORM != MINKO_PLATFORM_HTML5
case SDL_DROPFILE:
{
_fileDropped->execute(std::string(event.drop.file));
break;
}
#endif // MINKO_PLATFORM != MINKO_PLATFORM_HTML5
case SDL_TEXTINPUT:
{
int i = 0;
char16_t c = 0;
while (event.text.text[i] != '\0' && event.text.text[i] != 0)
i++;
if (i == 1)
{
c = event.text.text[0] & 0x00FF;
}
else if (i == 2)
{
int c1 = event.text.text[0] & 0xFF;
int c2 = event.text.text[1] & 0xFF;
if (c1 == 0xC3)
c2 += 0x40;
else if (c1 == 0xC4)
c2 += 0x80;
else if (c1 == 0xC5)
c2 += 0xC0;
c = c2;
}
if (c != 0)
{
bool found = false;
for (size_t i = 0; i < chars.size(); ++i)
{
if (chars[i] == c)
{
found = true;
break;
}
}
if (!found)
{
chars.push_back(c);
_keyboard->textInput()->execute(_keyboard, c);
}
}
break;
}
case SDL_TEXTEDITING:
{
//std::cout << "text editing" << std::endl;
break;
}
case SDL_KEYDOWN:
{
_keyboard->keyDown()->execute(_keyboard);
auto keyCode = static_cast<input::Keyboard::KeyCode>(event.key.keysym.sym);
for (uint i = 0; i < input::Keyboard::NUM_KEYS; ++i)
{
auto code = static_cast<input::Keyboard::Key>(i);
if (!_keyboard->hasKeyDownSignal(code))
continue;
auto pair = input::KeyMap::keyToKeyCodeMap.find(code);
if (pair != input::KeyMap::keyToKeyCodeMap.end() && pair->second == keyCode)
_keyboard->keyDown(code)->execute(_keyboard, i);
}
break;
}
case SDL_KEYUP:
{
_keyboard->keyUp()->execute(_keyboard);
auto keyCode = static_cast<input::Keyboard::KeyCode>(event.key.keysym.sym);
for (uint i = 0; i < input::Keyboard::NUM_KEYS; ++i)
{
auto code = static_cast<input::Keyboard::Key>(i);
if (!_keyboard->hasKeyUpSignal(code))
continue;
auto pair = input::KeyMap::keyToKeyCodeMap.find(code);
if (pair != input::KeyMap::keyToKeyCodeMap.end() && pair->second == keyCode)
_keyboard->keyUp(code)->execute(_keyboard, i);
}
for (uint i = 0; i < input::Keyboard::NUM_KEYS; ++i)
{
auto code = static_cast<input::Keyboard::Key>(i);
if (_keyboard->_keyboardState[i] && _keyboard->hasKeyUpSignal(code))
_keyboard->keyUp(code)->execute(_keyboard, i);
}
break;
}
case SDL_MOUSEMOTION:
{
int windowW;
int windowH;
SDL_GetWindowSize(_window, &windowW, &windowH);
auto x = event.motion.x;
auto y = event.motion.y;
auto dX = event.motion.xrel;
auto dY = event.motion.yrel;
if (windowW != _width || windowH != _height)
{
x = int(float(_width) * float(x) / float(windowW));
y = int(float(_height) * float(y) / float(windowH));
dX = int(float(_width) * float(dX) / float(windowW));
dY = int(float(_height) * float(dY) / float(windowH));
}
_mouse->x(x);
_mouse->y(y);
mouseDX += dX;
mouseDY += dY;
_mouse->dX(mouseDX);
_mouse->dY(mouseDY);
executeMouseMove = true;
break;
}
case SDL_MOUSEBUTTONDOWN:
{
if (enteredOrLeftThisFrame)
break;
switch (event.button.button)
{
case SDL_BUTTON_LEFT:
_mouse->leftButtonDown()->execute(_mouse);
break;
case SDL_BUTTON_RIGHT:
_mouse->rightButtonDown()->execute(_mouse);
break;
case SDL_BUTTON_MIDDLE:
_mouse->middleButtonDown()->execute(_mouse);
break;
#if MINKO_PLATFORM != MINKO_PLATFORM_HTML5
case SDL_BUTTON_X1:
_mouse->wheel()->execute(_mouse, 0, 1);
break;
case SDL_BUTTON_X2:
_mouse->wheel()->execute(_mouse, 0, -1);
break;
#endif
}
break;
}
case SDL_MOUSEBUTTONUP:
{
switch (event.button.button)
{
case SDL_BUTTON_LEFT:
_mouse->leftButtonUp()->execute(_mouse);
break;
case SDL_BUTTON_RIGHT:
_mouse->rightButtonUp()->execute(_mouse);
break;
case SDL_BUTTON_MIDDLE:
_mouse->middleButtonUp()->execute(_mouse);
break;
}
break;
}
case SDL_MOUSEWHEEL:
{
_mouse->wheel()->execute(_mouse, event.wheel.x, event.wheel.y);
break;
}
// Touch events
case SDL_FINGERDOWN:
{
auto x = event.tfinger.x * _width;
auto y = event.tfinger.y * _height;
auto id = static_cast<int>(event.tfinger.fingerId);
_touch->addTouch(id, x, y, 0.f, 0.f);
_mouse->x(static_cast<int>(_touch->averageX()));
_mouse->y(static_cast<int>(_touch->averageY()));
_touch->touchDown()->execute(
_touch,
id,
x,
y
);
if (_touch->numTouches() == 1)
{
_touch->lastTouchDownTime(_relativeTime);
_touch->lastTouchDownX(x);
_touch->lastTouchDownY(y);
}
else
{
_touch->lastTouchDownTime(-1.f);
_touch->lastTapTime(-1.f);
}
break;
}
case SDL_FINGERUP:
{
auto x = event.tfinger.x * _width;
auto y = event.tfinger.y * _height;
auto id = static_cast<int>(event.tfinger.fingerId);
_mouse->x(static_cast<int>(_touch->averageX()));
_mouse->y(static_cast<int>(_touch->averageY()));
_touch->removeTouch(id);
_touch->touchUp()->execute(
_touch,
id,
x,
y
);
if (_touch->numTouches() == 0 && _touch->lastTouchDownTime() != -1.0f )
{
auto dX = std::abs(x - _touch->lastTouchDownX());
auto dY = std::abs(y - _touch->lastTouchDownY());
auto dT = _relativeTime - _touch->lastTouchDownTime();
if (dT < input::SDLTouch::TAP_DELAY_THRESHOLD &&
dX < input::SDLTouch::TAP_MOVE_THRESHOLD &&
dY < input::SDLTouch::TAP_MOVE_THRESHOLD)
{
_touch->tap()->execute(_touch, x, y);
dX = std::abs(x - _touch->lastTapX()) * 0.75f;
dY = std::abs(y - _touch->lastTapY()) * 0.75f;
dT = _relativeTime - _touch->lastTapTime();
if (_touch->lastTapTime() != -1.0f &&
dT < input::SDLTouch::DOUBLE_TAP_DELAY_THRESHOLD &&
dX < input::SDLTouch::TAP_MOVE_THRESHOLD &&
dY < input::SDLTouch::TAP_MOVE_THRESHOLD)
{
_touch->doubleTap()->execute(_touch, x, y);
_touch->lastTapTime(-1.0f);
}
else
{
_touch->lastTapTime(_relativeTime);
}
_touch->lastTapX(x);
_touch->lastTapY(y);
}
}
_touch->lastTouchDownTime(-1.0f);
break;
}
case SDL_FINGERMOTION:
{
auto id = static_cast<int>(event.tfinger.fingerId);
auto normalizedX = event.tfinger.x;
auto normalizedY = event.tfinger.y;
auto normalizedDX = event.tfinger.dx;
auto normalizedDY = event.tfinger.dy;
auto x = normalizedX * _width;
auto y = normalizedY * _height;
auto dx = normalizedDX * _width;
auto dy = normalizedDY * _height;
if (std::abs(_touch->lastTouchDownX() - x) > input::SDLTouch::TAP_MOVE_THRESHOLD ||
std::abs(_touch->lastTouchDownY() - y) > input::SDLTouch::TAP_MOVE_THRESHOLD)
{
_touch->lastTouchDownTime(-1.0f);
}
_touch->updateTouch(id, x, y, dx, dy);
_mouse->x(static_cast<int>(_touch->averageX()));
_mouse->y(static_cast<int>(_touch->averageY()));
_mouse->dX(static_cast<int>(_touch->averageDX()));
_mouse->dY(static_cast<int>(_touch->averageDY()));
executeMouseMove = true;
_touch->touchMove()->execute(_touch, id, dx, dy);
// Gestures
if (event.tfinger.dx > input::SDLTouch::SWIPE_PRECISION)
{
_touch->swipeRight()->execute(_touch);
}
if (-event.tfinger.dx > input::SDLTouch::SWIPE_PRECISION)
{
_touch->swipeLeft()->execute(_touch);
}
if (event.tfinger.dy > input::SDLTouch::SWIPE_PRECISION)
{
_touch->swipeDown()->execute(_touch);
}
if (-event.tfinger.dy > input::SDLTouch::SWIPE_PRECISION)
{
_touch->swipeUp()->execute(_touch);
}
executePinchZoom = _touch->numTouches() == 2;
break;
}
case SDL_JOYAXISMOTION:
{
_joysticks[event.jaxis.which]->joystickAxisMotion()->execute(
_joysticks[event.jaxis.which], event.jaxis.which, event.jaxis.axis, event.jaxis.value
);
break;
}
case SDL_JOYHATMOTION:
{
_joysticks[event.jhat.which]->joystickHatMotion()->execute(
_joysticks[event.jhat.which], event.jhat.which, event.jhat.hat, event.jhat.value
);
break;
}
case SDL_JOYBUTTONDOWN:
{
input::SDLJoystick::Button button = input::SDLJoystick::button(event.jbutton.button);
_joysticks[event.jbutton.which]->joystickButtonDown()->execute(
_joysticks[event.jbutton.which], event.jbutton.which, input::SDLJoystick::buttonId(button)
);
break;
}
case SDL_JOYBUTTONUP:
{
input::SDLJoystick::Button button = input::SDLJoystick::button(event.jbutton.button);
_joysticks[event.jbutton.which]->joystickButtonUp()->execute(
_joysticks[event.jbutton.which], event.jbutton.which, input::SDLJoystick::buttonId(button)
);
break;
}
#if MINKO_PLATFORM != MINKO_PLATFORM_HTML5
case SDL_JOYDEVICEADDED:
{
int device = event.cdevice.which;
auto joystick = SDL_JoystickOpen(device);
SDL_JoystickID instance_id = SDL_JoystickInstanceID(joystick);
if (_joysticks.find(instance_id) == _joysticks.end())
{
auto sdlJoystick = input::SDLJoystick::create(that, instance_id, joystick);
_joysticks[instance_id] = sdlJoystick;
}
_joystickAdded->execute(that, _joysticks[instance_id]);
break;
}
case SDL_JOYDEVICEREMOVED:
{
auto joystick = _joysticks[event.cdevice.which]->_joystick;
_joystickRemoved->execute(that, _joysticks[event.cdevice.which]);
SDL_JoystickClose(joystick);
_joysticks.erase(event.cdevice.which);
break;
}
#endif // MINKO_PLATFORM_HTML5
#if MINKO_PLATFORM == MINKO_PLATFORM_HTML5
case SDL_VIDEORESIZE:
{
width(event.resize.w);
height(event.resize.h);
_screen = SDL_SetVideoMode(width(), height(), 0, SDL_OPENGL | SDL_WINDOW_RESIZABLE);
_context->configureViewport(x(), y(), width(), height());
_resized->execute(that, width(), height());
break;
}
#else
case SDL_WINDOWEVENT:
{
switch (event.window.event)
{
case SDL_WINDOWEVENT_RESIZED:
if (width() == event.window.data1 && height() == event.window.data2)
break;
width(event.window.data1);
height(event.window.data2);
_context->configureViewport(x(), y(), width(), height());
_resized->execute(that, width(), height());
break;
case SDL_WINDOWEVENT_ENTER:
_onWindow = true;
enteredOrLeftThisFrame = true;
break;
case SDL_WINDOWEVENT_LEAVE:
_onWindow = false;
enteredOrLeftThisFrame = true;
break;
default:
_resized->execute(that, width(), height());
break;
}
break;
}
#endif // MINKO_PLATFORM_HTML5
#if MINKO_PLATFORM == MINKO_PLATFORM_IOS || MINKO_PLATFORM == MINKO_PLATFORM_ANDROID
case SDL_APP_DIDENTERBACKGROUND:
suspended()->execute(shared_from_this());
_enableRendering = false;
break;
case SDL_APP_DIDENTERFOREGROUND:
resumed()->execute(shared_from_this());
_enableRendering = true;
break;
#endif // MINKO_PLATFORM == MINKO_PLATFORM_IOS || MINKO_PLATFORM == MINKO_PLATFORM_ANDROID
default:
break;
}
}
// Execute Pinch-Zoom event if needed.
if (executePinchZoom && _touch->numTouches() == 2)
{
input::Touch::TouchPoint touch1 = _touch->touch(_touch->identifiers()[0]);
input::Touch::TouchPoint touch2 = _touch->touch(_touch->identifiers()[1]);
auto normalizedPos1 = math::vec2(touch1.x / static_cast<float>(_width), touch1.y / static_cast<float>(_height));
auto normalizedDPos1 = math::vec2(touch1.dX / static_cast<float>(_width), touch1.dY / static_cast<float>(_height));
auto normalizedPos2 = math::vec2(touch2.x / static_cast<float>(_width), touch2.y / static_cast<float>(_height));
auto normalizedDPos2 = math::vec2(touch2.dX / static_cast<float>(_width), touch2.dY / static_cast<float>(_height));
auto previousDelta = (normalizedPos2 - normalizedDPos2) - (normalizedPos1 - normalizedDPos1);
auto currentDelta = normalizedPos2 - normalizedPos1;
auto previousDist = math::length(previousDelta);
auto currentDist = math::length(currentDelta);
auto normalizedDeltaDistance = currentDist - previousDist;
if (normalizedDeltaDistance != 0.0)
{
// normalizedDeltaDistance is a percentage of the screen
auto deltaDistance = normalizedDeltaDistance * 100.f;
_touch->pinchZoom()->execute(_touch, deltaDistance);
}
}
// Update delta mouse pos.
if (mouseDX != 0)
_mouse->dX(mouseDX);
if (mouseDY != 0)
_mouse->dY(mouseDY);
// Execute mouse move event only once per frame
if (executeMouseMove)
_mouse->move()->execute(_mouse, _mouse->dX(), _mouse->dY());
if (_touch->numTouches() && _touch->lastTouchDownTime() != -1.0f && (_relativeTime - _touch->lastTouchDownTime()) > input::SDLTouch::LONG_HOLD_DELAY_THRESHOLD)
{
_touch->longHold()->execute(_touch, _touch->averageX(), _touch->averageY());