/
clientwindow.cpp
1032 lines (875 loc) · 31 KB
/
clientwindow.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
/** @file clientwindow.cpp Top-level window with UI widgets.
* @ingroup base
*
* @todo Platform-specific behavior should be encapsulated in subclasses, e.g.,
* MacWindowBehavior. This would make the code easier to follow and more adaptable
* to the quirks of each platform.
*
* @authors Copyright © 2003-2013 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2005-2013 Daniel Swanson <danij@dengine.net>
* @authors Copyright © 2008 Jamie Jones <jamie_jones_au@yahoo.com.au>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include "ui/clientwindow.h"
#include "clientapp.h"
#include <de/DisplayMode>
#include <de/NumberValue>
#include <QGLFormat>
#include <de/GLState>
#include <de/Drawable>
#include <QCloseEvent>
#include "gl/sys_opengl.h"
#include "gl/gl_main.h"
#include "ui/widgets/legacywidget.h"
#include "ui/widgets/busywidget.h"
#include "ui/widgets/taskbarwidget.h"
#include "ui/widgets/consolewidget.h"
#include "ui/widgets/notificationwidget.h"
#include "ui/widgets/gameselectionwidget.h"
#include "ui/widgets/progresswidget.h"
#include "ui/dialogs/coloradjustmentdialog.h"
#include "CommandAction"
#include "ui/mouse_qt.h"
#include "dd_main.h"
#include "con_main.h"
#include "render/vr.h"
using namespace de;
static String const LEGACY_WIDGET_NAME = "legacy";
DENG2_PIMPL(ClientWindow),
DENG2_OBSERVES(KeyEventSource, KeyEvent),
DENG2_OBSERVES(MouseEventSource, MouseStateChange),
DENG2_OBSERVES(MouseEventSource, MouseEvent),
DENG2_OBSERVES(Canvas, FocusChange),
DENG2_OBSERVES(App, GameChange)
{
bool needMainInit;
bool needRecreateCanvas;
bool needRootSizeUpdate;
Mode mode;
/// Root of the nomal UI widgets of this window.
GuiRootWidget root;
LegacyWidget *legacy;
TaskBarWidget *taskBar;
NotificationWidget *notifications;
ColorAdjustmentDialog *colorAdjust;
LabelWidget *background;
GameSelectionWidget *games;
BusyWidget *busy;
GuiWidget *sidebar;
GuiRootWidget busyRoot;
// FPS notifications.
LabelWidget *fpsCounter;
float oldFps;
// GL objects.
Drawable oculusRift;
GLUniform uOculusRiftFB;
Instance(Public *i)
: Base(i),
needMainInit(true),
needRecreateCanvas(false),
needRootSizeUpdate(false),
mode(Normal),
root(thisPublic),
legacy(0),
taskBar(0),
notifications(0),
colorAdjust(0),
background(0),
games(0),
sidebar(0),
busyRoot(thisPublic),
fpsCounter(0),
oldFps(0),
uOculusRiftFB("texture", GLUniform::Sampler2D)
{
/// @todo The decision whether to receive input notifications from the
/// canvas is really a concern for the input drivers.
App::app().audienceForGameChange += this;
// Listen to input.
self.canvas().audienceForKeyEvent += this;
self.canvas().audienceForMouseStateChange += this;
self.canvas().audienceForMouseEvent += this;
}
~Instance()
{
App::app().audienceForGameChange -= this;
self.canvas().audienceForFocusChange -= this;
self.canvas().audienceForMouseStateChange -= this;
self.canvas().audienceForKeyEvent -= this;
}
void setupUI()
{
Style &style = ClientApp::windowSystem().style();
// Background for Ring Zero.
background = new LabelWidget;
background->setImage(style.images().image("window.background"));
background->setImageFit(ui::FitToSize);
background->setSizePolicy(ui::Filled, ui::Filled);
background->margins().set("");
background->rule()
.setInput(Rule::Left, root.viewLeft())
.setInput(Rule::Top, root.viewTop())
.setInput(Rule::Right, root.viewRight())
.setInput(Rule::Bottom, root.viewBottom());
root.add(background);
legacy = new LegacyWidget(LEGACY_WIDGET_NAME);
legacy->rule()
.setLeftTop (root.viewLeft(), root.viewTop())
.setRightBottom(root.viewWidth(), root.viewBottom());
// Initially the widget is disabled. It will be enabled when the window
// is visible and ready to be drawn.
legacy->disable();
root.add(legacy);
// Game selection.
games = new GameSelectionWidget;
games->rule()
.setInput(Rule::AnchorX, root.viewLeft() + root.viewWidth() / 2)
.setInput(Rule::AnchorY, root.viewTop() + root.viewHeight() / 2)
.setInput(Rule::Width, OperatorRule::minimum(root.viewWidth(),
style.rules().rule("gameselection.max.width")))
.setAnchorPoint(Vector2f(.5f, .5f));
root.add(games);
// Common notification area.
notifications = new NotificationWidget;
notifications->rule()
.setInput(Rule::Top, root.viewTop() + style.rules().rule("gap") - notifications->shift())
.setInput(Rule::Right, legacy->rule().right() - style.rules().rule("gap"));
root.add(notifications);
// FPS counter for the notification area.
fpsCounter = new LabelWidget;
fpsCounter->setSizePolicy(ui::Expand, ui::Expand);
fpsCounter->setAlignment(ui::AlignRight);
// Taskbar is over almost everything else.
taskBar = new TaskBarWidget;
taskBar->rule()
.setInput(Rule::Left, root.viewLeft())
.setInput(Rule::Bottom, root.viewBottom() + taskBar->shift())
.setInput(Rule::Width, root.viewWidth());
root.add(taskBar);
// The game selection's height depends on the taskbar.
games->rule().setInput(Rule::Height,
OperatorRule::minimum(root.viewHeight(),
(taskBar->rule().top() - root.viewHeight() / 2) * 2,
style.rules().rule("gameselection.max.height")));
// Color adjustment dialog.
colorAdjust = new ColorAdjustmentDialog;
colorAdjust->setAnchor(root.viewWidth() / 2, root.viewTop());
colorAdjust->setOpeningDirection(ui::Down);
root.add(colorAdjust);
// For busy mode we have an entirely different widget tree.
busy = new BusyWidget;
busy->rule()
.setLeftTop (busyRoot.viewLeft(), busyRoot.viewTop())
.setRightBottom(busyRoot.viewRight(), busyRoot.viewBottom());
busyRoot.add(busy);
}
void currentGameChanged(game::Game const &newGame)
{
if(newGame.isNull())
{
//legacy->hide();
background->show();
games->show();
taskBar->console().enableBlur();
}
else
{
//legacy->show();
background->hide();
games->hide();
// For the time being, blurring is not compatible with the
// legacy OpenGL rendering.
taskBar->console().enableBlur(false);
}
}
void setMode(Mode const &newMode)
{
LOG_DEBUG("Switching to %s mode") << (newMode == Busy? "Busy" : "Normal");
mode = newMode;
}
void finishMainWindowInit()
{
#ifdef MACOSX
if(self.isFullScreen())
{
// The window must be manually raised above the shielding window put up by
// the fullscreen display capture.
DisplayMode_Native_Raise(self.nativeHandle());
}
#endif
self.raise();
self.activateWindow();
/*
// Automatically grab the mouse from the get-go if in fullscreen mode.
if(Mouse_IsPresent() && self.isFullScreen())
{
self.canvas().trapMouse();
}
*/
self.canvas().audienceForFocusChange += this;
#ifdef WIN32
if(self.isFullScreen())
{
// It would seem we must manually give our canvas focus. Bug in Qt?
self.canvas().setFocus();
}
#endif
self.canvas().makeCurrent();
DD_FinishInitializationAfterWindowReady();
/// @todo This should be called when a VR mode is actually used.
vrInit();
}
void keyEvent(KeyEvent const &ev)
{
/// @todo Input drivers should observe the notification instead, input
/// subsystem passes it to window system. -jk
// Pass the event onto the window system.
ClientApp::windowSystem().processEvent(ev);
}
void mouseStateChanged(MouseEventSource::State state)
{
Mouse_Trap(state == MouseEventSource::Trapped);
}
void mouseEvent(MouseEvent const &event)
{
MouseEvent ev = event;
switch(VR::mode)
{
// Left-right screen split modes
case VR::MODE_SIDE_BY_SIDE:
case VR::MODE_CROSSEYE:
case VR::MODE_PARALLEL:
case VR::MODE_OCULUS_RIFT:
if(ev.type() == Event::MousePosition || ev.type() == Event::MouseButton)
{
// We need to map the real window coordinates to logical
// root view coordinates.
Vector2f pos = ev.pos();
// Make it possible to access both frames.
if(pos.x >= self.width()/2)
{
pos.x -= self.width()/2;
}
pos.x *= 2;
// Scale to logical size.
pos = pos / Vector2f(self.size()) *
Vector2f(root.viewWidth().value(), root.viewHeight().value());
ev.setPos(pos.toVector2i());
}
break;
// Top-bottom screen split modes
case VR::MODE_TOP_BOTTOM:
if(ev.type() == Event::MousePosition || ev.type() == Event::MouseButton)
{
// We need to map the real window coordinates to logical
// root view coordinates.
Vector2f pos = ev.pos();
// Make it possible to access both frames.
if(pos.y >= self.height()/2)
{
pos.y -= self.height()/2;
}
pos.y *= 2;
// Scale to logical size.
pos = pos / Vector2f(self.size()) *
Vector2f(root.viewWidth().value(), root.viewHeight().value());
ev.setPos(pos.toVector2i());
}
break;
default:
break;
}
if(ClientApp::windowSystem().processEvent(ev))
{
// Eaten by the window system.
return;
}
// Fall back to legacy handling.
switch(ev.type())
{
case Event::MouseButton:
Mouse_Qt_SubmitButton(
ev.button() == MouseEvent::Left? IMB_LEFT :
ev.button() == MouseEvent::Middle? IMB_MIDDLE :
ev.button() == MouseEvent::Right? IMB_RIGHT :
ev.button() == MouseEvent::XButton1? IMB_EXTRA1 :
ev.button() == MouseEvent::XButton2? IMB_EXTRA2 : IMB_MAXBUTTONS,
ev.state() == MouseEvent::Pressed);
break;
case Event::MouseMotion:
Mouse_Qt_SubmitMotion(IMA_POINTER, ev.pos().x, ev.pos().y);
break;
case Event::MouseWheel:
Mouse_Qt_SubmitMotion(IMA_WHEEL, ev.pos().x, ev.pos().y);
break;
default:
break;
}
}
void canvasFocusChanged(Canvas &canvas, bool hasFocus)
{
LOG_DEBUG("canvasFocusChanged focus:%b fullscreen:%b hidden:%b minimized:%b")
<< hasFocus << self.isFullScreen() << self.isHidden() << self.isMinimized();
if(!hasFocus)
{
DD_ClearEvents();
I_ResetAllDevices();
canvas.trapMouse(false);
}
else if(self.isFullScreen() && !taskBar->isOpen())
{
// Trap the mouse again in fullscreen mode.
canvas.trapMouse();
}
// Generate an event about this.
ddevent_t ev;
ev.type = E_FOCUS;
ev.focus.gained = hasFocus;
ev.focus.inWindow = 1; /// @todo Ask WindowSystem for an identifier number.
DD_PostEvent(&ev);
}
void updateFpsNotification(float fps)
{
notifications->showOrHide(fpsCounter, self.isFPSCounterVisible());
if(!fequal(oldFps, fps))
{
fpsCounter->setText(QString("%1 " _E(l) + tr("FPS")).arg(fps, 0, 'f', 1));
oldFps = fps;
}
}
void installSidebar(SidebarLocation location, GuiWidget *widget)
{
// Get rid of the old sidebar.
if(sidebar)
{
uninstallSidebar(location);
}
if(!widget) return;
DENG2_ASSERT(sidebar == NULL);
// Attach the widget.
switch(location)
{
case RightEdge:
widget->rule()
.setInput(Rule::Top, root.viewTop())
.setInput(Rule::Right, root.viewRight())
.setInput(Rule::Bottom, taskBar->rule().top());
legacy->rule()
.setInput(Rule::Right, widget->rule().left());
break;
}
sidebar = widget;
root.insertBefore(sidebar, *notifications);
}
void uninstallSidebar(SidebarLocation location)
{
DENG2_ASSERT(sidebar != NULL);
switch(location)
{
case RightEdge:
legacy->rule().setInput(Rule::Right, root.viewRight());
break;
}
root.remove(*sidebar);
sidebar->deleteLater();
sidebar = 0;
}
/*
* Special Viewing Modes: Oculus Rift and other VR
*/
typedef GLBufferT<Vertex3Tex> OculusRiftVBuf;
QScopedPointer<GLTarget> unwarpedTarget;
GLTexture unwarpedTexture;
void vrInit()
{
/// @todo Only do this when Oculus Rift mode is enabled.
/// Free the allocated resources when non-Oculus mode in use.
OculusRiftVBuf *buf = new OculusRiftVBuf;
oculusRift.addBuffer(buf);
// Set up a simple static quad.
OculusRiftVBuf::Type const verts[4] = {
{ Vector3f(-1, 1, 0.5f), Vector2f(0, 1), },
{ Vector3f( 1, 1, 0.5f), Vector2f(1, 1), },
{ Vector3f(-1, -1, 0.5f), Vector2f(0, 0), },
{ Vector3f( 1, -1, 0.5f), Vector2f(1, 0), }
};
buf->setVertices(gl::TriangleStrip, verts, 4, gl::Static);
root.shaders().build(oculusRift.program(), "vr.oculusrift.barrel")
<< uOculusRiftFB;
}
void updateRootSize()
{
needRootSizeUpdate = false;
Canvas::Size size = self.canvas().size();
switch(VR::mode)
{
// Left-right screen split modes
case VR::MODE_CROSSEYE:
case VR::MODE_PARALLEL:
// Adjust effective UI size for stereoscopic rendering.
size.y *= 2;
size *= .75f; // Make it a bit bigger.
break;
case VR::MODE_OCULUS_RIFT:
/// @todo - taskbar needs to elevate above bottom of screen in Rift mode
// Adjust effective UI size for stereoscopic rendering.
size.y *= 2;
size *= 0.75f;
break;
// Allow UI to squish in top/bottom and SBS mode: 3D hardware will unsquish them
case VR::MODE_TOP_BOTTOM:
case VR::MODE_SIDE_BY_SIDE:
default:
break;
}
DENG_ASSERT_IN_MAIN_THREAD();
// Tell the widgets.
root.setViewSize(size);
busyRoot.setViewSize(size);
}
/**
* Draws the entire UI in two halves, one for the left eye and one for the
* right. The Oculus Rift optical distortion effect is applied using a
* shader.
*
* @todo unwarpedTarget and unwarpedTexture should be cleared/deleted when
* Oculus Rift mode is disabled (or whenever they are not needed).
*/
void vrDrawOculusRift()
{
VR::applyFrustumShift = false;
/// @todo head tracking, image warping, shrunken hud, field of view
// Allocate offscreen buffers
Size size = self.canvas().size();
if(unwarpedTexture.size() != size)
{
unwarpedTexture.setUndefinedImage(size, Image::RGBA_8888);
unwarpedTexture.setWrap(gl::ClampToEdge, gl::ClampToEdge);
unwarpedTexture.setFilter(gl::Linear, gl::Linear, gl::MipNone);
unwarpedTarget.reset(new GLTarget(unwarpedTexture, GLTarget::DepthStencil));
uOculusRiftFB = unwarpedTexture;
}
// Set render target to offscreen temporarily.
GLState::push()
.setTarget(*unwarpedTarget)
.apply();
unwarpedTarget->clear(GLTarget::ColorDepth);
// Left eye view on left side of screen.
VR::eyeShift = VR::getEyeShift(-1);
GLState::setActiveRect(Rectangleui(0, 0, size.x/2, size.y), true);
self.root().draw();
// Right eye view on right side of screen.
VR::eyeShift = VR::getEyeShift(+1);
GLState::setActiveRect(Rectangleui(size.x/2, 0, size.x/2, size.y), true);
self.root().draw();
GLState::pop().apply();
glEnable(GL_TEXTURE_2D); // Necessary until the legacy code uses GLState, too.
// Return the drawing to the full target.
GLState::setActiveRect(Rectangleui(), true);
self.canvas().renderTarget().clear(GLTarget::Color);
GLState::push()
.setBlend(false)
.setDepthTest(false);
// Copy contents of offscreen buffer to normal screen.
oculusRift.draw();
glBindTexture(GL_TEXTURE_2D, 0);
GLState::pop().apply();
VR::applyFrustumShift = true; // restore default
}
};
ClientWindow::ClientWindow(String const &id)
: PersistentCanvasWindow(id), d(new Instance(this))
{
canvas().audienceForGLResize += this;
canvas().audienceForGLInit += this;
#ifdef WIN32
// Set an icon for the window.
Path iconPath = DENG2_APP->nativeBasePath() / "data\\graphics\\doomsday.ico";
LOG_DEBUG("Window icon: ") << NativePath(iconPath).pretty();
setWindowIcon(QIcon(iconPath));
#endif
d->setupUI();
}
GuiRootWidget &ClientWindow::root()
{
return d->mode == Busy? d->busyRoot : d->root;
}
TaskBarWidget &ClientWindow::taskBar()
{
return *d->taskBar;
}
ConsoleWidget &ClientWindow::console()
{
return d->taskBar->console();
}
NotificationWidget &ClientWindow::notifications()
{
return *d->notifications;
}
LegacyWidget &ClientWindow::game()
{
return *d->legacy;
}
BusyWidget &ClientWindow::busy()
{
return *d->busy;
}
bool ClientWindow::isFPSCounterVisible() const
{
return App::config().getb(configName("showFps"));
}
void ClientWindow::setMode(Mode const &mode)
{
LOG_AS("ClientWindow");
d->setMode(mode);
}
void ClientWindow::closeEvent(QCloseEvent *ev)
{
LOG_DEBUG("Window is about to close, executing 'quit'.");
/// @todo autosave and quit?
Con_Execute(CMDS_DDAY, "quit", true, false);
// We are not authorizing immediate closing of the window;
// engine shutdown will take care of it later.
ev->ignore(); // don't close
}
void ClientWindow::canvasGLReady(Canvas &canvas)
{
// Update the capability flags.
GL_state.features.multisample = canvas.format().sampleBuffers();
LOG_DEBUG("GL feature: Multisampling: %b") << GL_state.features.multisample;
PersistentCanvasWindow::canvasGLReady(canvas);
// Now that the Canvas is ready for drawing we can enable the LegacyWidget.
d->root.find(LEGACY_WIDGET_NAME)->enable();
// Configure a viewport immediately.
GLState::top().setViewport(Rectangleui(0, 0, canvas.width(), canvas.height())).apply();
LOG_DEBUG("LegacyWidget enabled");
if(d->needMainInit)
{
d->needMainInit = false;
d->finishMainWindowInit();
}
}
void ClientWindow::canvasGLInit(Canvas &)
{
Sys_GLConfigureDefaultState();
GL_Init2DState();
}
void ClientWindow::canvasGLDraw(Canvas &canvas)
{
// All of this occurs during the Canvas paintGL event.
ClientApp::app().preFrame(); /// @todo what about multiwindow?
DENG_ASSERT_IN_MAIN_THREAD();
DENG_ASSERT_GL_CONTEXT_ACTIVE();
if(d->needRootSizeUpdate)
{
d->updateRootSize();
}
switch(VR::mode)
{
// A) Single view type stereo 3D modes here:
case VR::MODE_MONO:
// Non-stereoscopic frame.
root().draw();
break;
case VR::MODE_LEFT:
// Left eye view
VR::eyeShift = VR::getEyeShift(-1);
root().draw();
break;
case VR::MODE_RIGHT:
// Right eye view
VR::eyeShift = VR::getEyeShift(+1);
root().draw();
break;
// B) Split-screen type stereo 3D modes here:
case VR::MODE_TOP_BOTTOM: // Left goes on top
// Left eye view on top of screen.
VR::eyeShift = VR::getEyeShift(-1);
GLState::setActiveRect(Rectangleui(0, 0, width(), height()/2), true);
root().draw();
// Right eye view on bottom of screen.
VR::eyeShift = VR::getEyeShift(+1);
GLState::setActiveRect(Rectangleui(0, height()/2, width(), height()/2), true);
root().draw();
break;
case VR::MODE_SIDE_BY_SIDE: // Squished aspect
// Left eye view on left side of screen.
VR::eyeShift = VR::getEyeShift(-1);
GLState::setActiveRect(Rectangleui(0, 0, width()/2, height()), true);
root().draw();
// Right eye view on right side of screen.
VR::eyeShift = VR::getEyeShift(+1);
GLState::setActiveRect(Rectangleui(width()/2, 0, width()/2, height()), true);
root().draw();
break;
case VR::MODE_PARALLEL: // Normal aspect
// Left eye view on left side of screen.
VR::eyeShift = VR::getEyeShift(-1);
GLState::setActiveRect(Rectangleui(0, 0, width()/2, height()), true);
root().draw();
// Right eye view on right side of screen.
VR::eyeShift = VR::getEyeShift(+1);
GLState::setActiveRect(Rectangleui(width()/2, 0, width()/2, height()), true);
root().draw();
break;
case VR::MODE_CROSSEYE: // Normal aspect
// RIght eye view on left side of screen.
VR::eyeShift = VR::getEyeShift(+1);
GLState::setActiveRect(Rectangleui(0, 0, width()/2, height()), true);
root().draw();
// Left eye view on right side of screen.
VR::eyeShift = VR::getEyeShift(-1);
GLState::setActiveRect(Rectangleui(width()/2, 0, width()/2, height()), true);
root().draw();
break;
case VR::MODE_OCULUS_RIFT:
d->vrDrawOculusRift();
break;
// Overlaid type stereo 3D modes below:
case VR::MODE_GREEN_MAGENTA:
// Left eye view
VR::eyeShift = VR::getEyeShift(-1);
// save previous glColorMask
glPushAttrib(GL_COLOR_BUFFER_BIT);
glColorMask(0, 1, 0, 1); // Left eye view green
root().draw();
// Right eye view
VR::eyeShift = VR::getEyeShift(+1);
glColorMask(1, 0, 1, 1); // Right eye view magenta
root().draw();
glPopAttrib(); // restore glColorMask
break;
case VR::MODE_RED_CYAN:
// Left eye view
VR::eyeShift = VR::getEyeShift(-1);
// save previous glColorMask
glPushAttrib(GL_COLOR_BUFFER_BIT);
glColorMask(1, 0, 0, 1); // Left eye view red
root().draw();
// Right eye view
VR::eyeShift = VR::getEyeShift(+1);
glColorMask(0, 1, 1, 1); // Right eye view cyan
root().draw();
glPopAttrib(); // restore glColorMask
break;
case VR::MODE_QUAD_BUFFERED:
{
/// @todo - attempt to enable a stereo GL context at start up.
GLboolean isStereoContext, isDoubleBuffered;
glGetBooleanv(GL_STEREO, &isStereoContext);
glGetBooleanv(GL_DOUBLEBUFFER, &isDoubleBuffered);
if (isStereoContext) {
// Left eye view
VR::eyeShift = VR::getEyeShift(-1);
if (isDoubleBuffered)
glDrawBuffer(GL_BACK_LEFT);
else
glDrawBuffer(GL_FRONT_LEFT);
root().draw();
// Right eye view
VR::eyeShift = VR::getEyeShift(+1);
if (isDoubleBuffered)
glDrawBuffer(GL_BACK_RIGHT);
else
glDrawBuffer(GL_FRONT_RIGHT);
root().draw();
if (isDoubleBuffered)
glDrawBuffer(GL_BACK);
else
glDrawBuffer(GL_FRONT);
break;
}
else {
// Non-stereoscopic frame.
root().draw();
break;
}
}
case VR::MODE_ROW_INTERLEAVED:
{
// Use absolute screen position of window to determine whether the
// first scan line is odd or even.
QPoint ulCorner(0, 0);
ulCorner = canvas.mapToGlobal(ulCorner); // widget to screen coordinates
bool rowParityIsEven = ((ulCorner.x() % 2) == 0);
/// @todo - use row parity in shader or stencil, to actally interleave rows.
// Left eye view
VR::eyeShift = VR::getEyeShift(-1);
root().draw();
// Right eye view
VR::eyeShift = VR::getEyeShift(+1);
root().draw();
break;
}
case VR::MODE_COLUMN_INTERLEAVED: /// @todo implement column interleaved stereo 3D after row intleaved is working correctly...
case VR::MODE_CHECKERBOARD: /// @todo implement checker stereo 3D after row intleaved is working correctly ...
default:
// Non-stereoscopic frame.
root().draw();
break;
}
// Restore default VR dynamic parameters
GLState::setActiveRect(Rectangleui(), true);
VR::eyeShift = 0;
// Finish GL drawing and swap it on to the screen. Blocks until buffers
// swapped.
GL_DoUpdate();
ClientApp::app().postFrame(); /// @todo what about multiwindow?
PersistentCanvasWindow::canvasGLDraw(canvas);
d->updateFpsNotification(frameRate());
}
void ClientWindow::canvasGLResized(Canvas &canvas)
{
LOG_AS("ClientWindow");
Canvas::Size size = canvas.size();
LOG_TRACE("Canvas resized to ") << size.asText();
GLState::top().setViewport(Rectangleui(0, 0, size.x, size.y));
d->updateRootSize();
}
bool ClientWindow::setDefaultGLFormat() // static
{
LOG_AS("DefaultGLFormat");
// Configure the GL settings for all subsequently created canvases.
QGLFormat fmt;
fmt.setDepthBufferSize(16);
fmt.setStencilBufferSize(8);
fmt.setDoubleBuffer(true);
if(CommandLine_Exists("-novsync") || !Con_GetByte("vid-vsync"))
{
fmt.setSwapInterval(0); // vsync off
LOG_DEBUG("vsync off");
}
else
{
fmt.setSwapInterval(1);
LOG_DEBUG("vsync on");
}
// The value of the "vid-fsaa" variable is written to this settings
// key when the value of the variable changes.
bool configured = de::App::config().getb("window.fsaa");
if(CommandLine_Exists("-nofsaa") || !configured)
{
fmt.setSampleBuffers(false);
LOG_DEBUG("multisampling off");
}
else
{
fmt.setSampleBuffers(true); // multisampling on (default: highest available)
//fmt.setSamples(4);
LOG_DEBUG("multisampling on (max)");
}
if(fmt != QGLFormat::defaultFormat())
{
LOG_DEBUG("Applying new format...");
QGLFormat::setDefaultFormat(fmt);
return true;
}
else
{
LOG_DEBUG("New format is the same as before.");
return false;
}
}
void ClientWindow::draw()
{
// Don't run the main loop until after the paint event has been dealt with.
ClientApp::app().loop().pause();
// The canvas needs to be recreated when the GL format has changed
// (e.g., multisampling).
if(d->needRecreateCanvas)
{
d->needRecreateCanvas = false;
if(setDefaultGLFormat())
{
recreateCanvas();
// Wait until the new Canvas is ready (note: loop remains paused!).
return;
}
}
if(shouldRepaintManually())
{
DENG_ASSERT_GL_CONTEXT_ACTIVE();
// Perform the drawing manually right away.
canvas().updateGL();
}
else
{
// Request update at the earliest convenience.
canvas().update();
}
}
bool ClientWindow::shouldRepaintManually() const
{
// When the mouse is not trapped, allow the system to regulate window
// updates (e.g., for window manipulation).
if(isFullScreen()) return true;
return !Mouse_IsPresent() || canvas().isMouseTrapped();
}
void ClientWindow::grab(image_t &img, bool halfSized) const
{
DENG_ASSERT_IN_MAIN_THREAD();
QSize outputSize = (halfSized? QSize(width()/2, height()/2) : QSize());
QImage grabbed = canvas().grabImage(outputSize);
Image_Init(&img);
img.size.width = grabbed.width();
img.size.height = grabbed.height();
img.pixelSize = grabbed.depth()/8;
img.pixels = (uint8_t *) malloc(grabbed.byteCount());
memcpy(img.pixels, grabbed.constBits(), grabbed.byteCount());
LOG_DEBUG("Canvas: grabbed %i x %i, byteCount:%i depth:%i format:%i")
<< grabbed.width() << grabbed.height()
<< grabbed.byteCount() << grabbed.depth() << grabbed.format();
DENG_ASSERT(img.pixelSize != 0);
}
void ClientWindow::updateCanvasFormat()
{
d->needRecreateCanvas = true;
// Save the relevant format settings.
App::config().set("window.fsaa", Con_GetByte("vid-fsaa") != 0);
}
void ClientWindow::updateRootSize()
{
// This will be done a bit later as the call may originate from another thread.
d->needRootSizeUpdate = true;
}
ClientWindow &ClientWindow::main()
{
return static_cast<ClientWindow &>(PersistentCanvasWindow::main());