]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/camwindow.cpp
Remove -Wno-extra
[xonotic/netradiant.git] / radiant / camwindow.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 //
23 // Camera Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "camwindow.h"
29
30 #include <gtk/gtk.h>
31 #include <gdk/gdkkeysyms.h>
32
33 #include "debugging/debugging.h"
34
35 #include "iscenegraph.h"
36 #include "irender.h"
37 #include "igl.h"
38 #include "icamera.h"
39 #include "cullable.h"
40 #include "renderable.h"
41 #include "preferencesystem.h"
42
43 #include "signal/signal.h"
44 #include "container/array.h"
45 #include "scenelib.h"
46 #include "render.h"
47 #include "cmdlib.h"
48 #include "math/frustum.h"
49
50 #include "gtkutil/widget.h"
51 #include "gtkutil/button.h"
52 #include "gtkutil/toolbar.h"
53 #include "gtkutil/glwidget.h"
54 #include "gtkutil/xorrectangle.h"
55 #include "gtkmisc.h"
56 #include "selection.h"
57 #include "mainframe.h"
58 #include "preferences.h"
59 #include "commands.h"
60 #include "xywindow.h"
61 #include "windowobservers.h"
62 #include "renderstate.h"
63
64 #include "timer.h"
65
66 Signal0 g_cameraMoved_callbacks;
67
68 void AddCameraMovedCallback( const SignalHandler& handler ){
69         g_cameraMoved_callbacks.connectLast( handler );
70 }
71
72 void CameraMovedNotify(){
73         g_cameraMoved_callbacks();
74 }
75
76
77 struct camwindow_globals_private_t
78 {
79         int m_nMoveSpeed;
80         bool m_bCamLinkSpeed;
81         int m_nAngleSpeed;
82         bool m_bCamInverseMouse;
83         bool m_bCamDiscrete;
84         bool m_bCubicClipping;
85         bool m_showStats;
86         int m_nStrafeMode;
87
88         camwindow_globals_private_t() :
89                 m_nMoveSpeed( 100 ),
90                 m_bCamLinkSpeed( true ),
91                 m_nAngleSpeed( 3 ),
92                 m_bCamInverseMouse( false ),
93                 m_bCamDiscrete( true ),
94                 m_bCubicClipping( true ),
95                 m_showStats( true ),
96                 m_nStrafeMode( 0 ){
97         }
98
99 };
100
101 camwindow_globals_private_t g_camwindow_globals_private;
102
103
104 const Matrix4 g_opengl2radiant(
105         0, 0,-1, 0,
106         -1, 0, 0, 0,
107         0, 1, 0, 0,
108         0, 0, 0, 1
109         );
110
111 const Matrix4 g_radiant2opengl(
112         0,-1, 0, 0,
113         0, 0, 1, 0,
114         -1, 0, 0, 0,
115         0, 0, 0, 1
116         );
117
118 struct camera_t;
119 void Camera_mouseMove( camera_t& camera, int x, int y );
120
121 enum camera_draw_mode
122 {
123         cd_wire,
124         cd_solid,
125         cd_texture,
126         cd_lighting
127 };
128
129 struct camera_t
130 {
131         int width, height;
132
133         bool timing;
134
135         Vector3 origin;
136         Vector3 angles;
137
138         Vector3 color; // background
139
140         Vector3 forward, right; // move matrix (TTimo: used to have up but it was not updated)
141         Vector3 vup, vpn, vright; // view matrix (taken from the modelview matrix)
142
143         Matrix4 projection;
144         Matrix4 modelview;
145
146         bool m_strafe; // true when in strafemode toggled by the ctrl-key
147         bool m_strafe_forward; // true when in strafemode by ctrl-key and shift is pressed for forward strafing
148
149         unsigned int movementflags; // movement flags
150         Timer m_keycontrol_timer;
151         guint m_keymove_handler;
152
153
154         float fieldOfView;
155
156         DeferredMotionDelta m_mouseMove;
157
158         static void motionDelta( int x, int y, void* data ){
159                 Camera_mouseMove( *reinterpret_cast<camera_t*>( data ), x, y );
160         }
161
162         View* m_view;
163         Callback m_update;
164
165         static camera_draw_mode draw_mode;
166
167         camera_t( View* view, const Callback& update )
168                 : width( 0 ),
169                 height( 0 ),
170                 timing( false ),
171                 origin( 0, 0, 0 ),
172                 angles( 0, 0, 0 ),
173                 color( 0, 0, 0 ),
174                 movementflags( 0 ),
175                 m_keymove_handler( 0 ),
176                 fieldOfView( 90.0f ),
177                 m_mouseMove( motionDelta, this ),
178                 m_view( view ),
179                 m_update( update ){
180         }
181 };
182
183 camera_draw_mode camera_t::draw_mode = cd_texture;
184
185 inline Matrix4 projection_for_camera( float near_z, float far_z, float fieldOfView, int width, int height ){
186         const float half_width = static_cast<float>( near_z * tan( degrees_to_radians( fieldOfView * 0.5 ) ) );
187         const float half_height = half_width * ( static_cast<float>( height ) / static_cast<float>( width ) );
188
189         return matrix4_frustum(
190                            -half_width,
191                            half_width,
192                            -half_height,
193                            half_height,
194                            near_z,
195                            far_z
196                            );
197 }
198
199 float Camera_getFarClipPlane( camera_t& camera ){
200         return ( g_camwindow_globals_private.m_bCubicClipping ) ? pow( 2.0, ( g_camwindow_globals.m_nCubicScale + 7 ) / 2.0 ) : 32768.0f;
201 }
202
203 void Camera_updateProjection( camera_t& camera ){
204         float farClip = Camera_getFarClipPlane( camera );
205         camera.projection = projection_for_camera( farClip / 4096.0f, farClip, camera.fieldOfView, camera.width, camera.height );
206
207         camera.m_view->Construct( camera.projection, camera.modelview, camera.width, camera.height );
208 }
209
210 void Camera_updateVectors( camera_t& camera ){
211         for ( int i = 0 ; i < 3 ; i++ )
212         {
213                 camera.vright[i] = camera.modelview[( i << 2 ) + 0];
214                 camera.vup[i] = camera.modelview[( i << 2 ) + 1];
215                 camera.vpn[i] = camera.modelview[( i << 2 ) + 2];
216         }
217 }
218
219 void Camera_updateModelview( camera_t& camera ){
220         camera.modelview = g_matrix4_identity;
221
222         // roll, pitch, yaw
223         Vector3 radiant_eulerXYZ( 0, -camera.angles[CAMERA_PITCH], camera.angles[CAMERA_YAW] );
224
225         matrix4_translate_by_vec3( camera.modelview, camera.origin );
226         matrix4_rotate_by_euler_xyz_degrees( camera.modelview, radiant_eulerXYZ );
227         matrix4_multiply_by_matrix4( camera.modelview, g_radiant2opengl );
228         matrix4_affine_invert( camera.modelview );
229
230         Camera_updateVectors( camera );
231
232         camera.m_view->Construct( camera.projection, camera.modelview, camera.width, camera.height );
233 }
234
235
236 void Camera_Move_updateAxes( camera_t& camera ){
237         double ya = degrees_to_radians( camera.angles[CAMERA_YAW] );
238
239         // the movement matrix is kept 2d
240         camera.forward[0] = static_cast<float>( cos( ya ) );
241         camera.forward[1] = static_cast<float>( sin( ya ) );
242         camera.forward[2] = 0;
243         camera.right[0] = camera.forward[1];
244         camera.right[1] = -camera.forward[0];
245 }
246
247 void Camera_Freemove_updateAxes( camera_t& camera ){
248         camera.right = camera.vright;
249         camera.forward = vector3_negated( camera.vpn );
250 }
251
252 const Vector3& Camera_getOrigin( camera_t& camera ){
253         return camera.origin;
254 }
255
256 void Camera_setOrigin( camera_t& camera, const Vector3& origin ){
257         camera.origin = origin;
258         Camera_updateModelview( camera );
259         camera.m_update();
260         CameraMovedNotify();
261 }
262
263 const Vector3& Camera_getAngles( camera_t& camera ){
264         return camera.angles;
265 }
266
267 void Camera_setAngles( camera_t& camera, const Vector3& angles ){
268         camera.angles = angles;
269         Camera_updateModelview( camera );
270         camera.m_update();
271         CameraMovedNotify();
272 }
273
274
275 void Camera_FreeMove( camera_t& camera, int dx, int dy ){
276         // free strafe mode, toggled by the ctrl key with optional shift for forward movement
277         if ( camera.m_strafe ) {
278                 float strafespeed = 0.65f;
279
280                 if ( g_camwindow_globals_private.m_bCamLinkSpeed ) {
281                         strafespeed = (float)g_camwindow_globals_private.m_nMoveSpeed / 100;
282                 }
283
284                 camera.origin -= camera.vright * strafespeed * dx;
285                 if ( camera.m_strafe_forward ) {
286                         camera.origin += camera.vpn * strafespeed * dy;
287                 }
288                 else{
289                         camera.origin += camera.vup * strafespeed * dy;
290                 }
291         }
292         else // free rotation
293         {
294                 const float dtime = 0.1f;
295
296                 if ( g_camwindow_globals_private.m_bCamInverseMouse ) {
297                         camera.angles[CAMERA_PITCH] -= dy * dtime * g_camwindow_globals_private.m_nAngleSpeed;
298                 }
299                 else{
300                         camera.angles[CAMERA_PITCH] += dy * dtime * g_camwindow_globals_private.m_nAngleSpeed;
301                 }
302
303                 camera.angles[CAMERA_YAW] += dx * dtime * g_camwindow_globals_private.m_nAngleSpeed;
304
305                 if ( camera.angles[CAMERA_PITCH] > 90 ) {
306                         camera.angles[CAMERA_PITCH] = 90;
307                 }
308                 else if ( camera.angles[CAMERA_PITCH] < -90 ) {
309                         camera.angles[CAMERA_PITCH] = -90;
310                 }
311
312                 if ( camera.angles[CAMERA_YAW] >= 360 ) {
313                         camera.angles[CAMERA_YAW] -= 360;
314                 }
315                 else if ( camera.angles[CAMERA_YAW] <= 0 ) {
316                         camera.angles[CAMERA_YAW] += 360;
317                 }
318         }
319
320         Camera_updateModelview( camera );
321         Camera_Freemove_updateAxes( camera );
322 }
323
324 void Cam_MouseControl( camera_t& camera, int x, int y ){
325         int xl, xh;
326         int yl, yh;
327         float xf, yf;
328
329         xf = (float)( x - camera.width / 2 ) / ( camera.width / 2 );
330         yf = (float)( y - camera.height / 2 ) / ( camera.height / 2 );
331
332         xl = camera.width / 3;
333         xh = xl * 2;
334         yl = camera.height / 3;
335         yh = yl * 2;
336
337         xf *= 1.0f - fabsf( yf );
338         if ( xf < 0 ) {
339                 xf += 0.1f;
340                 if ( xf > 0 ) {
341                         xf = 0;
342                 }
343         }
344         else
345         {
346                 xf -= 0.1f;
347                 if ( xf < 0 ) {
348                         xf = 0;
349                 }
350         }
351
352         vector3_add( camera.origin, vector3_scaled( camera.forward, yf * 0.1f * g_camwindow_globals_private.m_nMoveSpeed ) );
353         camera.angles[CAMERA_YAW] += xf * -0.1f * g_camwindow_globals_private.m_nAngleSpeed;
354
355         Camera_updateModelview( camera );
356 }
357
358 void Camera_mouseMove( camera_t& camera, int x, int y ){
359         //globalOutputStream() << "mousemove... ";
360         Camera_FreeMove( camera, -x, -y );
361         camera.m_update();
362         CameraMovedNotify();
363 }
364
365 const unsigned int MOVE_NONE = 0;
366 const unsigned int MOVE_FORWARD = 1 << 0;
367 const unsigned int MOVE_BACK = 1 << 1;
368 const unsigned int MOVE_ROTRIGHT = 1 << 2;
369 const unsigned int MOVE_ROTLEFT = 1 << 3;
370 const unsigned int MOVE_STRAFERIGHT = 1 << 4;
371 const unsigned int MOVE_STRAFELEFT = 1 << 5;
372 const unsigned int MOVE_UP = 1 << 6;
373 const unsigned int MOVE_DOWN = 1 << 7;
374 const unsigned int MOVE_PITCHUP = 1 << 8;
375 const unsigned int MOVE_PITCHDOWN = 1 << 9;
376 const unsigned int MOVE_ALL = MOVE_FORWARD | MOVE_BACK | MOVE_ROTRIGHT | MOVE_ROTLEFT | MOVE_STRAFERIGHT | MOVE_STRAFELEFT | MOVE_UP | MOVE_DOWN | MOVE_PITCHUP | MOVE_PITCHDOWN;
377
378 void Cam_KeyControl( camera_t& camera, float dtime ){
379         // Update angles
380         if ( camera.movementflags & MOVE_ROTLEFT ) {
381                 camera.angles[CAMERA_YAW] += 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed;
382         }
383         if ( camera.movementflags & MOVE_ROTRIGHT ) {
384                 camera.angles[CAMERA_YAW] -= 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed;
385         }
386         if ( camera.movementflags & MOVE_PITCHUP ) {
387                 camera.angles[CAMERA_PITCH] += 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed;
388                 if ( camera.angles[CAMERA_PITCH] > 90 ) {
389                         camera.angles[CAMERA_PITCH] = 90;
390                 }
391         }
392         if ( camera.movementflags & MOVE_PITCHDOWN ) {
393                 camera.angles[CAMERA_PITCH] -= 15 * dtime * g_camwindow_globals_private.m_nAngleSpeed;
394                 if ( camera.angles[CAMERA_PITCH] < -90 ) {
395                         camera.angles[CAMERA_PITCH] = -90;
396                 }
397         }
398
399         Camera_updateModelview( camera );
400         Camera_Freemove_updateAxes( camera );
401
402         // Update position
403         if ( camera.movementflags & MOVE_FORWARD ) {
404                 vector3_add( camera.origin, vector3_scaled( camera.forward, dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
405         }
406         if ( camera.movementflags & MOVE_BACK ) {
407                 vector3_add( camera.origin, vector3_scaled( camera.forward, -dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
408         }
409         if ( camera.movementflags & MOVE_STRAFELEFT ) {
410                 vector3_add( camera.origin, vector3_scaled( camera.right, -dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
411         }
412         if ( camera.movementflags & MOVE_STRAFERIGHT ) {
413                 vector3_add( camera.origin, vector3_scaled( camera.right, dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
414         }
415         if ( camera.movementflags & MOVE_UP ) {
416                 vector3_add( camera.origin, vector3_scaled( g_vector3_axis_z, dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
417         }
418         if ( camera.movementflags & MOVE_DOWN ) {
419                 vector3_add( camera.origin, vector3_scaled( g_vector3_axis_z, -dtime * g_camwindow_globals_private.m_nMoveSpeed ) );
420         }
421
422         Camera_updateModelview( camera );
423 }
424
425 void Camera_keyMove( camera_t& camera ){
426         camera.m_mouseMove.flush();
427
428         //globalOutputStream() << "keymove... ";
429         float time_seconds = camera.m_keycontrol_timer.elapsed_msec() / static_cast<float>( msec_per_sec );
430         camera.m_keycontrol_timer.start();
431         if ( time_seconds > 0.05f ) {
432                 time_seconds = 0.05f; // 20fps
433         }
434         Cam_KeyControl( camera, time_seconds * 5.0f );
435
436         camera.m_update();
437         CameraMovedNotify();
438 }
439
440 gboolean camera_keymove( gpointer data ){
441         Camera_keyMove( *reinterpret_cast<camera_t*>( data ) );
442         return TRUE;
443 }
444
445 void Camera_setMovementFlags( camera_t& camera, unsigned int mask ){
446         if ( ( ~camera.movementflags & mask ) != 0 && camera.movementflags == 0 ) {
447                 camera.m_keymove_handler = g_idle_add( camera_keymove, &camera );
448         }
449         camera.movementflags |= mask;
450 }
451 void Camera_clearMovementFlags( camera_t& camera, unsigned int mask ){
452         if ( ( camera.movementflags & ~mask ) == 0 && camera.movementflags != 0 ) {
453                 g_source_remove( camera.m_keymove_handler );
454                 camera.m_keymove_handler = 0;
455         }
456         camera.movementflags &= ~mask;
457 }
458
459 void Camera_MoveForward_KeyDown( camera_t& camera ){
460         Camera_setMovementFlags( camera, MOVE_FORWARD );
461 }
462 void Camera_MoveForward_KeyUp( camera_t& camera ){
463         Camera_clearMovementFlags( camera, MOVE_FORWARD );
464 }
465 void Camera_MoveBack_KeyDown( camera_t& camera ){
466         Camera_setMovementFlags( camera, MOVE_BACK );
467 }
468 void Camera_MoveBack_KeyUp( camera_t& camera ){
469         Camera_clearMovementFlags( camera, MOVE_BACK );
470 }
471
472 void Camera_MoveLeft_KeyDown( camera_t& camera ){
473         Camera_setMovementFlags( camera, MOVE_STRAFELEFT );
474 }
475 void Camera_MoveLeft_KeyUp( camera_t& camera ){
476         Camera_clearMovementFlags( camera, MOVE_STRAFELEFT );
477 }
478 void Camera_MoveRight_KeyDown( camera_t& camera ){
479         Camera_setMovementFlags( camera, MOVE_STRAFERIGHT );
480 }
481 void Camera_MoveRight_KeyUp( camera_t& camera ){
482         Camera_clearMovementFlags( camera, MOVE_STRAFERIGHT );
483 }
484
485 void Camera_MoveUp_KeyDown( camera_t& camera ){
486         Camera_setMovementFlags( camera, MOVE_UP );
487 }
488 void Camera_MoveUp_KeyUp( camera_t& camera ){
489         Camera_clearMovementFlags( camera, MOVE_UP );
490 }
491 void Camera_MoveDown_KeyDown( camera_t& camera ){
492         Camera_setMovementFlags( camera, MOVE_DOWN );
493 }
494 void Camera_MoveDown_KeyUp( camera_t& camera ){
495         Camera_clearMovementFlags( camera, MOVE_DOWN );
496 }
497
498 void Camera_RotateLeft_KeyDown( camera_t& camera ){
499         Camera_setMovementFlags( camera, MOVE_ROTLEFT );
500 }
501 void Camera_RotateLeft_KeyUp( camera_t& camera ){
502         Camera_clearMovementFlags( camera, MOVE_ROTLEFT );
503 }
504 void Camera_RotateRight_KeyDown( camera_t& camera ){
505         Camera_setMovementFlags( camera, MOVE_ROTRIGHT );
506 }
507 void Camera_RotateRight_KeyUp( camera_t& camera ){
508         Camera_clearMovementFlags( camera, MOVE_ROTRIGHT );
509 }
510
511 void Camera_PitchUp_KeyDown( camera_t& camera ){
512         Camera_setMovementFlags( camera, MOVE_PITCHUP );
513 }
514 void Camera_PitchUp_KeyUp( camera_t& camera ){
515         Camera_clearMovementFlags( camera, MOVE_PITCHUP );
516 }
517 void Camera_PitchDown_KeyDown( camera_t& camera ){
518         Camera_setMovementFlags( camera, MOVE_PITCHDOWN );
519 }
520 void Camera_PitchDown_KeyUp( camera_t& camera ){
521         Camera_clearMovementFlags( camera, MOVE_PITCHDOWN );
522 }
523
524
525 typedef ReferenceCaller<camera_t, &Camera_MoveForward_KeyDown> FreeMoveCameraMoveForwardKeyDownCaller;
526 typedef ReferenceCaller<camera_t, &Camera_MoveForward_KeyUp> FreeMoveCameraMoveForwardKeyUpCaller;
527 typedef ReferenceCaller<camera_t, &Camera_MoveBack_KeyDown> FreeMoveCameraMoveBackKeyDownCaller;
528 typedef ReferenceCaller<camera_t, &Camera_MoveBack_KeyUp> FreeMoveCameraMoveBackKeyUpCaller;
529 typedef ReferenceCaller<camera_t, &Camera_MoveLeft_KeyDown> FreeMoveCameraMoveLeftKeyDownCaller;
530 typedef ReferenceCaller<camera_t, &Camera_MoveLeft_KeyUp> FreeMoveCameraMoveLeftKeyUpCaller;
531 typedef ReferenceCaller<camera_t, &Camera_MoveRight_KeyDown> FreeMoveCameraMoveRightKeyDownCaller;
532 typedef ReferenceCaller<camera_t, &Camera_MoveRight_KeyUp> FreeMoveCameraMoveRightKeyUpCaller;
533 typedef ReferenceCaller<camera_t, &Camera_MoveUp_KeyDown> FreeMoveCameraMoveUpKeyDownCaller;
534 typedef ReferenceCaller<camera_t, &Camera_MoveUp_KeyUp> FreeMoveCameraMoveUpKeyUpCaller;
535 typedef ReferenceCaller<camera_t, &Camera_MoveDown_KeyDown> FreeMoveCameraMoveDownKeyDownCaller;
536 typedef ReferenceCaller<camera_t, &Camera_MoveDown_KeyUp> FreeMoveCameraMoveDownKeyUpCaller;
537
538
539 #define SPEED_MOVE 32
540 #define SPEED_TURN 22.5
541 #define MIN_CAM_SPEED 10
542 #define MAX_CAM_SPEED 610
543 #define CAM_SPEED_STEP 50
544
545 void Camera_MoveForward_Discrete( camera_t& camera ){
546         Camera_Move_updateAxes( camera );
547         Camera_setOrigin( camera, vector3_added( Camera_getOrigin( camera ), vector3_scaled( camera.forward, SPEED_MOVE ) ) );
548 }
549 void Camera_MoveBack_Discrete( camera_t& camera ){
550         Camera_Move_updateAxes( camera );
551         Camera_setOrigin( camera, vector3_added( Camera_getOrigin( camera ), vector3_scaled( camera.forward, -SPEED_MOVE ) ) );
552 }
553
554 void Camera_MoveUp_Discrete( camera_t& camera ){
555         Vector3 origin( Camera_getOrigin( camera ) );
556         origin[2] += SPEED_MOVE;
557         Camera_setOrigin( camera, origin );
558 }
559 void Camera_MoveDown_Discrete( camera_t& camera ){
560         Vector3 origin( Camera_getOrigin( camera ) );
561         origin[2] -= SPEED_MOVE;
562         Camera_setOrigin( camera, origin );
563 }
564
565 void Camera_MoveLeft_Discrete( camera_t& camera ){
566         Camera_Move_updateAxes( camera );
567         Camera_setOrigin( camera, vector3_added( Camera_getOrigin( camera ), vector3_scaled( camera.right, -SPEED_MOVE ) ) );
568 }
569 void Camera_MoveRight_Discrete( camera_t& camera ){
570         Camera_Move_updateAxes( camera );
571         Camera_setOrigin( camera, vector3_added( Camera_getOrigin( camera ), vector3_scaled( camera.right, SPEED_MOVE ) ) );
572 }
573
574 void Camera_RotateLeft_Discrete( camera_t& camera ){
575         Vector3 angles( Camera_getAngles( camera ) );
576         angles[CAMERA_YAW] += SPEED_TURN;
577         Camera_setAngles( camera, angles );
578 }
579 void Camera_RotateRight_Discrete( camera_t& camera ){
580         Vector3 angles( Camera_getAngles( camera ) );
581         angles[CAMERA_YAW] -= SPEED_TURN;
582         Camera_setAngles( camera, angles );
583 }
584
585 void Camera_PitchUp_Discrete( camera_t& camera ){
586         Vector3 angles( Camera_getAngles( camera ) );
587         angles[CAMERA_PITCH] += SPEED_TURN;
588         if ( angles[CAMERA_PITCH] > 90 ) {
589                 angles[CAMERA_PITCH] = 90;
590         }
591         Camera_setAngles( camera, angles );
592 }
593 void Camera_PitchDown_Discrete( camera_t& camera ){
594         Vector3 angles( Camera_getAngles( camera ) );
595         angles[CAMERA_PITCH] -= SPEED_TURN;
596         if ( angles[CAMERA_PITCH] < -90 ) {
597                 angles[CAMERA_PITCH] = -90;
598         }
599         Camera_setAngles( camera, angles );
600 }
601
602
603 class RadiantCameraView : public CameraView
604 {
605 camera_t& m_camera;
606 View* m_view;
607 Callback m_update;
608 public:
609 RadiantCameraView( camera_t& camera, View* view, const Callback& update ) : m_camera( camera ), m_view( view ), m_update( update ){
610 }
611 void update(){
612         m_view->Construct( m_camera.projection, m_camera.modelview, m_camera.width, m_camera.height );
613         m_update();
614 }
615 void setModelview( const Matrix4& modelview ){
616         m_camera.modelview = modelview;
617         matrix4_multiply_by_matrix4( m_camera.modelview, g_radiant2opengl );
618         matrix4_affine_invert( m_camera.modelview );
619         Camera_updateVectors( m_camera );
620         update();
621 }
622 void setFieldOfView( float fieldOfView ){
623         float farClip = Camera_getFarClipPlane( m_camera );
624         m_camera.projection = projection_for_camera( farClip / 4096.0f, farClip, fieldOfView, m_camera.width, m_camera.height );
625         update();
626 }
627 };
628
629
630 void Camera_motionDelta( int x, int y, unsigned int state, void* data ){
631         camera_t* cam = reinterpret_cast<camera_t*>( data );
632
633         cam->m_mouseMove.motion_delta( x, y, state );
634
635         switch ( g_camwindow_globals_private.m_nStrafeMode )
636         {
637         case 0:
638                 cam->m_strafe = ( state & GDK_CONTROL_MASK ) != 0;
639                 if ( cam->m_strafe ) {
640                         cam->m_strafe_forward = ( state & GDK_SHIFT_MASK ) != 0;
641                 }
642                 else{
643                         cam->m_strafe_forward = false;
644                 }
645                 break;
646         case 1:
647                 cam->m_strafe = ( state & GDK_CONTROL_MASK ) != 0 && ( state & GDK_SHIFT_MASK ) == 0;
648                 cam->m_strafe_forward = false;
649                 break;
650         case 2:
651                 cam->m_strafe = ( state & GDK_CONTROL_MASK ) != 0 && ( state & GDK_SHIFT_MASK ) == 0;
652                 cam->m_strafe_forward = cam->m_strafe;
653                 break;
654         }
655 }
656
657 class CamWnd
658 {
659 View m_view;
660 camera_t m_Camera;
661 RadiantCameraView m_cameraview;
662 #if 0
663 int m_PositionDragCursorX;
664 int m_PositionDragCursorY;
665 #endif
666
667 guint m_freemove_handle_focusout;
668
669 static Shader* m_state_select1;
670 static Shader* m_state_select2;
671
672 FreezePointer m_freezePointer;
673
674 public:
675 ui::GLArea m_gl_widget;
676 ui::Window m_parent{ui::null};
677
678 SelectionSystemWindowObserver* m_window_observer;
679 XORRectangle m_XORRectangle;
680
681 DeferredDraw m_deferredDraw;
682 DeferredMotion m_deferred_motion;
683
684 guint m_selection_button_press_handler;
685 guint m_selection_button_release_handler;
686 guint m_selection_motion_handler;
687
688 guint m_freelook_button_press_handler;
689
690 guint m_sizeHandler;
691 guint m_exposeHandler;
692
693 CamWnd();
694 ~CamWnd();
695
696 bool m_drawing;
697 void queue_draw(){
698         //ASSERT_MESSAGE(!m_drawing, "CamWnd::queue_draw(): called while draw is already in progress");
699         if ( m_drawing ) {
700                 return;
701         }
702         //globalOutputStream() << "queue... ";
703         m_deferredDraw.draw();
704 }
705 void draw();
706
707 static void captureStates(){
708         m_state_select1 = GlobalShaderCache().capture( "$CAM_HIGHLIGHT" );
709         m_state_select2 = GlobalShaderCache().capture( "$CAM_OVERLAY" );
710 }
711 static void releaseStates(){
712         GlobalShaderCache().release( "$CAM_HIGHLIGHT" );
713         GlobalShaderCache().release( "$CAM_OVERLAY" );
714 }
715
716 camera_t& getCamera(){
717         return m_Camera;
718 };
719
720 void BenchMark();
721 void Cam_ChangeFloor( bool up );
722
723 void DisableFreeMove();
724 void EnableFreeMove();
725 bool m_bFreeMove;
726
727 CameraView& getCameraView(){
728         return m_cameraview;
729 }
730
731 private:
732 void Cam_Draw();
733 };
734
735 typedef MemberCaller<CamWnd, &CamWnd::queue_draw> CamWndQueueDraw;
736
737 Shader* CamWnd::m_state_select1 = 0;
738 Shader* CamWnd::m_state_select2 = 0;
739
740 CamWnd* NewCamWnd(){
741         return new CamWnd;
742 }
743 void DeleteCamWnd( CamWnd* camwnd ){
744         delete camwnd;
745 }
746
747 void CamWnd_constructStatic(){
748         CamWnd::captureStates();
749 }
750
751 void CamWnd_destroyStatic(){
752         CamWnd::releaseStates();
753 }
754
755 static CamWnd* g_camwnd = 0;
756
757 void GlobalCamera_setCamWnd( CamWnd& camwnd ){
758         g_camwnd = &camwnd;
759 }
760
761
762 ui::GLArea CamWnd_getWidget( CamWnd& camwnd ){
763         return camwnd.m_gl_widget;
764 }
765
766 ui::Window CamWnd_getParent( CamWnd& camwnd ){
767         return camwnd.m_parent;
768 }
769
770 ToggleShown g_camera_shown( true );
771
772 void CamWnd_setParent( CamWnd& camwnd, ui::Window parent ){
773         camwnd.m_parent = parent;
774         g_camera_shown.connect( camwnd.m_parent );
775 }
776
777 void CamWnd_Update( CamWnd& camwnd ){
778         camwnd.queue_draw();
779 }
780
781
782
783 camwindow_globals_t g_camwindow_globals;
784
785 const Vector3& Camera_getOrigin( CamWnd& camwnd ){
786         return Camera_getOrigin( camwnd.getCamera() );
787 }
788
789 void Camera_setOrigin( CamWnd& camwnd, const Vector3& origin ){
790         Camera_setOrigin( camwnd.getCamera(), origin );
791 }
792
793 const Vector3& Camera_getAngles( CamWnd& camwnd ){
794         return Camera_getAngles( camwnd.getCamera() );
795 }
796
797 void Camera_setAngles( CamWnd& camwnd, const Vector3& angles ){
798         Camera_setAngles( camwnd.getCamera(), angles );
799 }
800
801
802 // =============================================================================
803 // CamWnd class
804
805 gboolean enable_freelook_button_press( ui::Widget widget, GdkEventButton* event, CamWnd* camwnd ){
806         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
807                 camwnd->EnableFreeMove();
808                 return TRUE;
809         }
810         return FALSE;
811 }
812
813 gboolean disable_freelook_button_press( ui::Widget widget, GdkEventButton* event, CamWnd* camwnd ){
814         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
815                 camwnd->DisableFreeMove();
816                 return TRUE;
817         }
818         return FALSE;
819 }
820
821 #if 0
822 gboolean mousecontrol_button_press( ui::Widget widget, GdkEventButton* event, CamWnd* camwnd ){
823         if ( event->type == GDK_BUTTON_PRESS && event->button == 3 ) {
824                 Cam_MouseControl( camwnd->getCamera(), event->x, widget->allocation.height - 1 - event->y );
825         }
826         return FALSE;
827 }
828 #endif
829
830 void camwnd_update_xor_rectangle( CamWnd& self, rect_t area ){
831         if ( self.m_gl_widget.visible() ) {
832                 self.m_XORRectangle.set( rectangle_from_area( area.min, area.max, self.getCamera().width, self.getCamera().height ) );
833         }
834 }
835
836
837 gboolean selection_button_press( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
838         if ( event->type == GDK_BUTTON_PRESS ) {
839                 observer->onMouseDown( WindowVector_forDouble( event->x, event->y ), button_for_button( event->button ), modifiers_for_state( event->state ) );
840         }
841         return FALSE;
842 }
843
844 gboolean selection_button_release( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
845         if ( event->type == GDK_BUTTON_RELEASE ) {
846                 observer->onMouseUp( WindowVector_forDouble( event->x, event->y ), button_for_button( event->button ), modifiers_for_state( event->state ) );
847         }
848         return FALSE;
849 }
850
851 void selection_motion( gdouble x, gdouble y, guint state, void* data ){
852         //globalOutputStream() << "motion... ";
853         reinterpret_cast<WindowObserver*>( data )->onMouseMotion( WindowVector_forDouble( x, y ), modifiers_for_state( state ) );
854 }
855
856 inline WindowVector windowvector_for_widget_centre( ui::Widget widget ){
857         auto allocation = widget.dimensions();
858         return WindowVector( static_cast<float>( allocation.width / 2 ), static_cast<float>(allocation.height / 2 ) );
859 }
860
861 gboolean selection_button_press_freemove( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
862         if ( event->type == GDK_BUTTON_PRESS ) {
863                 observer->onMouseDown( windowvector_for_widget_centre( widget ), button_for_button( event->button ), modifiers_for_state( event->state ) );
864         }
865         return FALSE;
866 }
867
868 gboolean selection_button_release_freemove( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
869         if ( event->type == GDK_BUTTON_RELEASE ) {
870                 observer->onMouseUp( windowvector_for_widget_centre( widget ), button_for_button( event->button ), modifiers_for_state( event->state ) );
871         }
872         return FALSE;
873 }
874
875 gboolean selection_motion_freemove( ui::Widget widget, GdkEventMotion *event, WindowObserver* observer ){
876         observer->onMouseMotion( windowvector_for_widget_centre( widget ), modifiers_for_state( event->state ) );
877         return FALSE;
878 }
879
880 gboolean wheelmove_scroll( ui::Widget widget, GdkEventScroll* event, CamWnd* camwnd ){
881         if ( event->direction == GDK_SCROLL_UP ) {
882                 Camera_Freemove_updateAxes( camwnd->getCamera() );
883                 Camera_setOrigin( *camwnd, vector3_added( Camera_getOrigin( *camwnd ), vector3_scaled( camwnd->getCamera().forward, static_cast<float>( g_camwindow_globals_private.m_nMoveSpeed ) ) ) );
884         }
885         else if ( event->direction == GDK_SCROLL_DOWN ) {
886                 Camera_Freemove_updateAxes( camwnd->getCamera() );
887                 Camera_setOrigin( *camwnd, vector3_added( Camera_getOrigin( *camwnd ), vector3_scaled( camwnd->getCamera().forward, -static_cast<float>( g_camwindow_globals_private.m_nMoveSpeed ) ) ) );
888         }
889
890         return FALSE;
891 }
892
893 gboolean camera_size_allocate( ui::Widget widget, GtkAllocation* allocation, CamWnd* camwnd ){
894         camwnd->getCamera().width = allocation->width;
895         camwnd->getCamera().height = allocation->height;
896         Camera_updateProjection( camwnd->getCamera() );
897         camwnd->m_window_observer->onSizeChanged( camwnd->getCamera().width, camwnd->getCamera().height );
898         camwnd->queue_draw();
899         return FALSE;
900 }
901
902 gboolean camera_expose( ui::Widget widget, GdkEventExpose* event, gpointer data ){
903         reinterpret_cast<CamWnd*>( data )->draw();
904         return FALSE;
905 }
906
907 void KeyEvent_connect( const char* name ){
908         const KeyEvent& keyEvent = GlobalKeyEvents_find( name );
909         keydown_accelerators_add( keyEvent.m_accelerator, keyEvent.m_keyDown );
910         keyup_accelerators_add( keyEvent.m_accelerator, keyEvent.m_keyUp );
911 }
912
913 void KeyEvent_disconnect( const char* name ){
914         const KeyEvent& keyEvent = GlobalKeyEvents_find( name );
915         keydown_accelerators_remove( keyEvent.m_accelerator );
916         keyup_accelerators_remove( keyEvent.m_accelerator );
917 }
918
919 void CamWnd_registerCommands( CamWnd& camwnd ){
920         GlobalKeyEvents_insert( "CameraForward", Accelerator( GDK_KEY_Up ),
921                                                         ReferenceCaller<camera_t, Camera_MoveForward_KeyDown>( camwnd.getCamera() ),
922                                                         ReferenceCaller<camera_t, Camera_MoveForward_KeyUp>( camwnd.getCamera() )
923                                                         );
924         GlobalKeyEvents_insert( "CameraBack", Accelerator( GDK_KEY_Down ),
925                                                         ReferenceCaller<camera_t, Camera_MoveBack_KeyDown>( camwnd.getCamera() ),
926                                                         ReferenceCaller<camera_t, Camera_MoveBack_KeyUp>( camwnd.getCamera() )
927                                                         );
928         GlobalKeyEvents_insert( "CameraLeft", Accelerator( GDK_KEY_Left ),
929                                                         ReferenceCaller<camera_t, Camera_RotateLeft_KeyDown>( camwnd.getCamera() ),
930                                                         ReferenceCaller<camera_t, Camera_RotateLeft_KeyUp>( camwnd.getCamera() )
931                                                         );
932         GlobalKeyEvents_insert( "CameraRight", Accelerator( GDK_KEY_Right ),
933                                                         ReferenceCaller<camera_t, Camera_RotateRight_KeyDown>( camwnd.getCamera() ),
934                                                         ReferenceCaller<camera_t, Camera_RotateRight_KeyUp>( camwnd.getCamera() )
935                                                         );
936         GlobalKeyEvents_insert( "CameraStrafeRight", Accelerator( GDK_KEY_period ),
937                                                         ReferenceCaller<camera_t, Camera_MoveRight_KeyDown>( camwnd.getCamera() ),
938                                                         ReferenceCaller<camera_t, Camera_MoveRight_KeyUp>( camwnd.getCamera() )
939                                                         );
940         GlobalKeyEvents_insert( "CameraStrafeLeft", Accelerator( GDK_KEY_comma ),
941                                                         ReferenceCaller<camera_t, Camera_MoveLeft_KeyDown>( camwnd.getCamera() ),
942                                                         ReferenceCaller<camera_t, Camera_MoveLeft_KeyUp>( camwnd.getCamera() )
943                                                         );
944         GlobalKeyEvents_insert( "CameraUp", Accelerator( 'D' ),
945                                                         ReferenceCaller<camera_t, Camera_MoveUp_KeyDown>( camwnd.getCamera() ),
946                                                         ReferenceCaller<camera_t, Camera_MoveUp_KeyUp>( camwnd.getCamera() )
947                                                         );
948         GlobalKeyEvents_insert( "CameraDown", Accelerator( 'C' ),
949                                                         ReferenceCaller<camera_t, Camera_MoveDown_KeyDown>( camwnd.getCamera() ),
950                                                         ReferenceCaller<camera_t, Camera_MoveDown_KeyUp>( camwnd.getCamera() )
951                                                         );
952         GlobalKeyEvents_insert( "CameraAngleDown", Accelerator( 'A' ),
953                                                         ReferenceCaller<camera_t, Camera_PitchDown_KeyDown>( camwnd.getCamera() ),
954                                                         ReferenceCaller<camera_t, Camera_PitchDown_KeyUp>( camwnd.getCamera() )
955                                                         );
956         GlobalKeyEvents_insert( "CameraAngleUp", Accelerator( 'Z' ),
957                                                         ReferenceCaller<camera_t, Camera_PitchUp_KeyDown>( camwnd.getCamera() ),
958                                                         ReferenceCaller<camera_t, Camera_PitchUp_KeyUp>( camwnd.getCamera() )
959                                                         );
960
961         GlobalKeyEvents_insert( "CameraFreeMoveForward", Accelerator( GDK_KEY_Up ),
962                                                         FreeMoveCameraMoveForwardKeyDownCaller( camwnd.getCamera() ),
963                                                         FreeMoveCameraMoveForwardKeyUpCaller( camwnd.getCamera() )
964                                                         );
965         GlobalKeyEvents_insert( "CameraFreeMoveBack", Accelerator( GDK_KEY_Down ),
966                                                         FreeMoveCameraMoveBackKeyDownCaller( camwnd.getCamera() ),
967                                                         FreeMoveCameraMoveBackKeyUpCaller( camwnd.getCamera() )
968                                                         );
969         GlobalKeyEvents_insert( "CameraFreeMoveLeft", Accelerator( GDK_KEY_Left ),
970                                                         FreeMoveCameraMoveLeftKeyDownCaller( camwnd.getCamera() ),
971                                                         FreeMoveCameraMoveLeftKeyUpCaller( camwnd.getCamera() )
972                                                         );
973         GlobalKeyEvents_insert( "CameraFreeMoveRight", Accelerator( GDK_KEY_Right ),
974                                                         FreeMoveCameraMoveRightKeyDownCaller( camwnd.getCamera() ),
975                                                         FreeMoveCameraMoveRightKeyUpCaller( camwnd.getCamera() )
976                                                         );
977         GlobalKeyEvents_insert( "CameraFreeMoveUp", Accelerator( 'D' ),
978                                                         FreeMoveCameraMoveUpKeyDownCaller( camwnd.getCamera() ),
979                                                         FreeMoveCameraMoveUpKeyUpCaller( camwnd.getCamera() )
980                                                         );
981         GlobalKeyEvents_insert( "CameraFreeMoveDown", Accelerator( 'C' ),
982                                                         FreeMoveCameraMoveDownKeyDownCaller( camwnd.getCamera() ),
983                                                         FreeMoveCameraMoveDownKeyUpCaller( camwnd.getCamera() )
984                                                         );
985
986         GlobalCommands_insert( "CameraForward", ReferenceCaller<camera_t, Camera_MoveForward_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Up ) );
987         GlobalCommands_insert( "CameraBack", ReferenceCaller<camera_t, Camera_MoveBack_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Down ) );
988         GlobalCommands_insert( "CameraLeft", ReferenceCaller<camera_t, Camera_RotateLeft_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Left ) );
989         GlobalCommands_insert( "CameraRight", ReferenceCaller<camera_t, Camera_RotateRight_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Right ) );
990         GlobalCommands_insert( "CameraStrafeRight", ReferenceCaller<camera_t, Camera_MoveRight_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_period ) );
991         GlobalCommands_insert( "CameraStrafeLeft", ReferenceCaller<camera_t, Camera_MoveLeft_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_comma ) );
992
993         GlobalCommands_insert( "CameraUp", ReferenceCaller<camera_t, Camera_MoveUp_Discrete>( camwnd.getCamera() ), Accelerator( 'D' ) );
994         GlobalCommands_insert( "CameraDown", ReferenceCaller<camera_t, Camera_MoveDown_Discrete>( camwnd.getCamera() ), Accelerator( 'C' ) );
995         GlobalCommands_insert( "CameraAngleUp", ReferenceCaller<camera_t, Camera_PitchUp_Discrete>( camwnd.getCamera() ), Accelerator( 'A' ) );
996         GlobalCommands_insert( "CameraAngleDown", ReferenceCaller<camera_t, Camera_PitchDown_Discrete>( camwnd.getCamera() ), Accelerator( 'Z' ) );
997 }
998
999 void CamWnd_Move_Enable( CamWnd& camwnd ){
1000         KeyEvent_connect( "CameraForward" );
1001         KeyEvent_connect( "CameraBack" );
1002         KeyEvent_connect( "CameraLeft" );
1003         KeyEvent_connect( "CameraRight" );
1004         KeyEvent_connect( "CameraStrafeRight" );
1005         KeyEvent_connect( "CameraStrafeLeft" );
1006         KeyEvent_connect( "CameraUp" );
1007         KeyEvent_connect( "CameraDown" );
1008         KeyEvent_connect( "CameraAngleUp" );
1009         KeyEvent_connect( "CameraAngleDown" );
1010 }
1011
1012 void CamWnd_Move_Disable( CamWnd& camwnd ){
1013         KeyEvent_disconnect( "CameraForward" );
1014         KeyEvent_disconnect( "CameraBack" );
1015         KeyEvent_disconnect( "CameraLeft" );
1016         KeyEvent_disconnect( "CameraRight" );
1017         KeyEvent_disconnect( "CameraStrafeRight" );
1018         KeyEvent_disconnect( "CameraStrafeLeft" );
1019         KeyEvent_disconnect( "CameraUp" );
1020         KeyEvent_disconnect( "CameraDown" );
1021         KeyEvent_disconnect( "CameraAngleUp" );
1022         KeyEvent_disconnect( "CameraAngleDown" );
1023 }
1024
1025 void CamWnd_Move_Discrete_Enable( CamWnd& camwnd ){
1026         command_connect_accelerator( "CameraForward" );
1027         command_connect_accelerator( "CameraBack" );
1028         command_connect_accelerator( "CameraLeft" );
1029         command_connect_accelerator( "CameraRight" );
1030         command_connect_accelerator( "CameraStrafeRight" );
1031         command_connect_accelerator( "CameraStrafeLeft" );
1032         command_connect_accelerator( "CameraUp" );
1033         command_connect_accelerator( "CameraDown" );
1034         command_connect_accelerator( "CameraAngleUp" );
1035         command_connect_accelerator( "CameraAngleDown" );
1036 }
1037
1038 void CamWnd_Move_Discrete_Disable( CamWnd& camwnd ){
1039         command_disconnect_accelerator( "CameraForward" );
1040         command_disconnect_accelerator( "CameraBack" );
1041         command_disconnect_accelerator( "CameraLeft" );
1042         command_disconnect_accelerator( "CameraRight" );
1043         command_disconnect_accelerator( "CameraStrafeRight" );
1044         command_disconnect_accelerator( "CameraStrafeLeft" );
1045         command_disconnect_accelerator( "CameraUp" );
1046         command_disconnect_accelerator( "CameraDown" );
1047         command_disconnect_accelerator( "CameraAngleUp" );
1048         command_disconnect_accelerator( "CameraAngleDown" );
1049 }
1050
1051 void CamWnd_Move_Discrete_Import( CamWnd& camwnd, bool value ){
1052         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1053                 CamWnd_Move_Discrete_Disable( camwnd );
1054         }
1055         else
1056         {
1057                 CamWnd_Move_Disable( camwnd );
1058         }
1059
1060         g_camwindow_globals_private.m_bCamDiscrete = value;
1061
1062         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1063                 CamWnd_Move_Discrete_Enable( camwnd );
1064         }
1065         else
1066         {
1067                 CamWnd_Move_Enable( camwnd );
1068         }
1069 }
1070
1071 void CamWnd_Move_Discrete_Import( bool value ){
1072         if ( g_camwnd != 0 ) {
1073                 CamWnd_Move_Discrete_Import( *g_camwnd, value );
1074         }
1075         else
1076         {
1077                 g_camwindow_globals_private.m_bCamDiscrete = value;
1078         }
1079 }
1080
1081
1082
1083 void CamWnd_Add_Handlers_Move( CamWnd& camwnd ){
1084         camwnd.m_selection_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( selection_button_press ), camwnd.m_window_observer );
1085         camwnd.m_selection_button_release_handler = camwnd.m_gl_widget.connect( "button_release_event", G_CALLBACK( selection_button_release ), camwnd.m_window_observer );
1086         camwnd.m_selection_motion_handler = camwnd.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( DeferredMotion::gtk_motion ), &camwnd.m_deferred_motion );
1087
1088         camwnd.m_freelook_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( enable_freelook_button_press ), &camwnd );
1089
1090         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1091                 CamWnd_Move_Discrete_Enable( camwnd );
1092         }
1093         else
1094         {
1095                 CamWnd_Move_Enable( camwnd );
1096         }
1097 }
1098
1099 void CamWnd_Remove_Handlers_Move( CamWnd& camwnd ){
1100         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_press_handler );
1101         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_release_handler );
1102         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_motion_handler );
1103
1104         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_freelook_button_press_handler );
1105
1106         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1107                 CamWnd_Move_Discrete_Disable( camwnd );
1108         }
1109         else
1110         {
1111                 CamWnd_Move_Disable( camwnd );
1112         }
1113 }
1114
1115 void CamWnd_Add_Handlers_FreeMove( CamWnd& camwnd ){
1116         camwnd.m_selection_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( selection_button_press_freemove ), camwnd.m_window_observer );
1117         camwnd.m_selection_button_release_handler = camwnd.m_gl_widget.connect( "button_release_event", G_CALLBACK( selection_button_release_freemove ), camwnd.m_window_observer );
1118         camwnd.m_selection_motion_handler = camwnd.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( selection_motion_freemove ), camwnd.m_window_observer );
1119
1120         camwnd.m_freelook_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( disable_freelook_button_press ), &camwnd );
1121
1122         KeyEvent_connect( "CameraFreeMoveForward" );
1123         KeyEvent_connect( "CameraFreeMoveBack" );
1124         KeyEvent_connect( "CameraFreeMoveLeft" );
1125         KeyEvent_connect( "CameraFreeMoveRight" );
1126         KeyEvent_connect( "CameraFreeMoveUp" );
1127         KeyEvent_connect( "CameraFreeMoveDown" );
1128 }
1129
1130 void CamWnd_Remove_Handlers_FreeMove( CamWnd& camwnd ){
1131         KeyEvent_disconnect( "CameraFreeMoveForward" );
1132         KeyEvent_disconnect( "CameraFreeMoveBack" );
1133         KeyEvent_disconnect( "CameraFreeMoveLeft" );
1134         KeyEvent_disconnect( "CameraFreeMoveRight" );
1135         KeyEvent_disconnect( "CameraFreeMoveUp" );
1136         KeyEvent_disconnect( "CameraFreeMoveDown" );
1137
1138         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_press_handler );
1139         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_release_handler );
1140         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_motion_handler );
1141
1142         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_freelook_button_press_handler );
1143 }
1144
1145 CamWnd::CamWnd() :
1146         m_view( true ),
1147         m_Camera( &m_view, CamWndQueueDraw( *this ) ),
1148         m_cameraview( m_Camera, &m_view, ReferenceCaller<CamWnd, CamWnd_Update>( *this ) ),
1149         m_gl_widget( glwidget_new( TRUE ) ),
1150         m_window_observer( NewWindowObserver() ),
1151         m_XORRectangle( m_gl_widget ),
1152         m_deferredDraw( WidgetQueueDrawCaller( m_gl_widget ) ),
1153         m_deferred_motion( selection_motion, m_window_observer ),
1154         m_selection_button_press_handler( 0 ),
1155         m_selection_button_release_handler( 0 ),
1156         m_selection_motion_handler( 0 ),
1157         m_freelook_button_press_handler( 0 ),
1158         m_drawing( false ){
1159         m_bFreeMove = false;
1160
1161         GlobalWindowObservers_add( m_window_observer );
1162         GlobalWindowObservers_connectWidget( m_gl_widget );
1163
1164         m_window_observer->setRectangleDrawCallback( ReferenceCaller1<CamWnd, rect_t, camwnd_update_xor_rectangle>( *this ) );
1165         m_window_observer->setView( m_view );
1166
1167         g_object_ref( m_gl_widget._handle );
1168
1169         gtk_widget_set_events( m_gl_widget, GDK_DESTROY | GDK_EXPOSURE_MASK | GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK | GDK_POINTER_MOTION_MASK | GDK_SCROLL_MASK );
1170         gtk_widget_set_can_focus( m_gl_widget, true );
1171
1172         m_sizeHandler = m_gl_widget.connect( "size_allocate", G_CALLBACK( camera_size_allocate ), this );
1173         m_exposeHandler = m_gl_widget.on_render( G_CALLBACK( camera_expose ), this );
1174
1175         Map_addValidCallback( g_map, DeferredDrawOnMapValidChangedCaller( m_deferredDraw ) );
1176
1177         CamWnd_registerCommands( *this );
1178
1179         CamWnd_Add_Handlers_Move( *this );
1180
1181         m_gl_widget.connect( "scroll_event", G_CALLBACK( wheelmove_scroll ), this );
1182
1183         AddSceneChangeCallback( ReferenceCaller<CamWnd, CamWnd_Update>( *this ) );
1184
1185         PressedButtons_connect( g_pressedButtons, m_gl_widget );
1186 }
1187
1188 CamWnd::~CamWnd(){
1189         if ( m_bFreeMove ) {
1190                 DisableFreeMove();
1191         }
1192
1193         CamWnd_Remove_Handlers_Move( *this );
1194
1195         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_sizeHandler );
1196         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_exposeHandler );
1197
1198         m_gl_widget.unref();
1199
1200         m_window_observer->release();
1201 }
1202
1203 class FloorHeightWalker : public scene::Graph::Walker
1204 {
1205 float m_current;
1206 float& m_bestUp;
1207 float& m_bestDown;
1208 public:
1209 FloorHeightWalker( float current, float& bestUp, float& bestDown ) :
1210         m_current( current ), m_bestUp( bestUp ), m_bestDown( bestDown ){
1211         bestUp = g_MaxWorldCoord;
1212         bestDown = -g_MaxWorldCoord;
1213 }
1214 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1215         if ( path.top().get().visible()
1216                  && Node_isBrush( path.top() ) ) { // this node is a floor
1217                 const AABB& aabb = instance.worldAABB();
1218                 float floorHeight = aabb.origin.z() + aabb.extents.z();
1219                 if ( floorHeight > m_current && floorHeight < m_bestUp ) {
1220                         m_bestUp = floorHeight;
1221                 }
1222                 if ( floorHeight < m_current && floorHeight > m_bestDown ) {
1223                         m_bestDown = floorHeight;
1224                 }
1225         }
1226         return true;
1227 }
1228 };
1229
1230 void CamWnd::Cam_ChangeFloor( bool up ){
1231         float current = m_Camera.origin[2] - 48;
1232         float bestUp;
1233         float bestDown;
1234         GlobalSceneGraph().traverse( FloorHeightWalker( current, bestUp, bestDown ) );
1235
1236         if ( up && bestUp != g_MaxWorldCoord ) {
1237                 current = bestUp;
1238         }
1239         if ( !up && bestDown != -g_MaxWorldCoord ) {
1240                 current = bestDown;
1241         }
1242
1243         m_Camera.origin[2] = current + 48;
1244         Camera_updateModelview( getCamera() );
1245         CamWnd_Update( *this );
1246         CameraMovedNotify();
1247 }
1248
1249
1250 #if 0
1251
1252 // button_press
1253 Sys_GetCursorPos( &m_PositionDragCursorX, &m_PositionDragCursorY );
1254
1255 // motion
1256 if ( ( m_bFreeMove && ( buttons == ( RAD_CONTROL | RAD_SHIFT ) ) )
1257          || ( !m_bFreeMove && ( buttons == ( RAD_RBUTTON | RAD_CONTROL ) ) ) ) {
1258         Cam_PositionDrag();
1259         CamWnd_Update( camwnd );
1260         CameraMovedNotify();
1261         return;
1262 }
1263
1264 void CamWnd::Cam_PositionDrag(){
1265         int x, y;
1266
1267         Sys_GetCursorPos( GTK_WINDOW( m_gl_widget ), &x, &y );
1268         if ( x != m_PositionDragCursorX || y != m_PositionDragCursorY ) {
1269                 x -= m_PositionDragCursorX;
1270                 vector3_add( m_Camera.origin, vector3_scaled( m_Camera.vright, x ) );
1271                 y -= m_PositionDragCursorY;
1272                 m_Camera.origin[2] -= y;
1273                 Camera_updateModelview();
1274                 CamWnd_Update( camwnd );
1275                 CameraMovedNotify();
1276
1277                 Sys_SetCursorPos( GTK_WINDOW( m_parent ), m_PositionDragCursorX, m_PositionDragCursorY );
1278         }
1279 }
1280 #endif
1281
1282
1283 // NOTE TTimo if there's an OS-level focus out of the application
1284 //   then we can release the camera cursor grab
1285 static gboolean camwindow_freemove_focusout( ui::Widget widget, GdkEventFocus* event, gpointer data ){
1286         reinterpret_cast<CamWnd*>( data )->DisableFreeMove();
1287         return FALSE;
1288 }
1289
1290 void CamWnd::EnableFreeMove(){
1291         //globalOutputStream() << "EnableFreeMove\n";
1292
1293         ASSERT_MESSAGE( !m_bFreeMove, "EnableFreeMove: free-move was already enabled" );
1294         m_bFreeMove = true;
1295         Camera_clearMovementFlags( getCamera(), MOVE_ALL );
1296
1297         CamWnd_Remove_Handlers_Move( *this );
1298         CamWnd_Add_Handlers_FreeMove( *this );
1299
1300         gtk_window_set_focus( m_parent, m_gl_widget );
1301         m_freemove_handle_focusout = m_gl_widget.connect( "focus_out_event", G_CALLBACK( camwindow_freemove_focusout ), this );
1302         m_freezePointer.freeze_pointer( m_parent, Camera_motionDelta, &m_Camera );
1303
1304         CamWnd_Update( *this );
1305 }
1306
1307 void CamWnd::DisableFreeMove(){
1308         //globalOutputStream() << "DisableFreeMove\n";
1309
1310         ASSERT_MESSAGE( m_bFreeMove, "DisableFreeMove: free-move was not enabled" );
1311         m_bFreeMove = false;
1312         Camera_clearMovementFlags( getCamera(), MOVE_ALL );
1313
1314         CamWnd_Remove_Handlers_FreeMove( *this );
1315         CamWnd_Add_Handlers_Move( *this );
1316
1317         m_freezePointer.unfreeze_pointer( m_parent );
1318         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_freemove_handle_focusout );
1319
1320         CamWnd_Update( *this );
1321 }
1322
1323
1324 #include "renderer.h"
1325
1326 class CamRenderer : public Renderer
1327 {
1328 struct state_type
1329 {
1330         state_type() : m_highlight( 0 ), m_state( 0 ), m_lights( 0 ){
1331         }
1332         unsigned int m_highlight;
1333         Shader* m_state;
1334         const LightList* m_lights;
1335 };
1336
1337 std::vector<state_type> m_state_stack;
1338 RenderStateFlags m_globalstate;
1339 Shader* m_state_select0;
1340 Shader* m_state_select1;
1341 const Vector3& m_viewer;
1342
1343 public:
1344 CamRenderer( RenderStateFlags globalstate, Shader* select0, Shader* select1, const Vector3& viewer ) :
1345         m_globalstate( globalstate ),
1346         m_state_select0( select0 ),
1347         m_state_select1( select1 ),
1348         m_viewer( viewer ){
1349         ASSERT_NOTNULL( select0 );
1350         ASSERT_NOTNULL( select1 );
1351         m_state_stack.push_back( state_type() );
1352 }
1353
1354 void SetState( Shader* state, EStyle style ){
1355         ASSERT_NOTNULL( state );
1356         if ( style == eFullMaterials ) {
1357                 m_state_stack.back().m_state = state;
1358         }
1359 }
1360 EStyle getStyle() const {
1361         return eFullMaterials;
1362 }
1363 void PushState(){
1364         m_state_stack.push_back( m_state_stack.back() );
1365 }
1366 void PopState(){
1367         ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" );
1368         m_state_stack.pop_back();
1369 }
1370 void Highlight( EHighlightMode mode, bool bEnable = true ){
1371         ( bEnable )
1372         ? m_state_stack.back().m_highlight |= mode
1373                                                                                   : m_state_stack.back().m_highlight &= ~mode;
1374 }
1375 void setLights( const LightList& lights ){
1376         m_state_stack.back().m_lights = &lights;
1377 }
1378 void addRenderable( const OpenGLRenderable& renderable, const Matrix4& world ){
1379         if ( m_state_stack.back().m_highlight & ePrimitive ) {
1380                 m_state_select0->addRenderable( renderable, world, m_state_stack.back().m_lights );
1381         }
1382         if ( m_state_stack.back().m_highlight & eFace ) {
1383                 m_state_select1->addRenderable( renderable, world, m_state_stack.back().m_lights );
1384         }
1385
1386         m_state_stack.back().m_state->addRenderable( renderable, world, m_state_stack.back().m_lights );
1387 }
1388
1389 void render( const Matrix4& modelview, const Matrix4& projection ){
1390         GlobalShaderCache().render( m_globalstate, modelview, projection, m_viewer );
1391 }
1392 };
1393
1394 /*
1395    ==============
1396    Cam_Draw
1397    ==============
1398  */
1399
1400 void ShowStatsToggle(){
1401         g_camwindow_globals_private.m_showStats ^= 1;
1402 }
1403 typedef FreeCaller<ShowStatsToggle> ShowStatsToggleCaller;
1404
1405 void ShowStatsExport( const BoolImportCallback& importer ){
1406         importer( g_camwindow_globals_private.m_showStats );
1407 }
1408 typedef FreeCaller1<const BoolImportCallback&, ShowStatsExport> ShowStatsExportCaller;
1409
1410 ShowStatsExportCaller g_show_stats_caller;
1411 BoolExportCallback g_show_stats_callback( g_show_stats_caller );
1412 ToggleItem g_show_stats( g_show_stats_callback );
1413
1414 void CamWnd::Cam_Draw(){
1415         glViewport( 0, 0, m_Camera.width, m_Camera.height );
1416 #if 0
1417         GLint viewprt[4];
1418         glGetIntegerv( GL_VIEWPORT, viewprt );
1419 #endif
1420
1421         // enable depth buffer writes
1422         glDepthMask( GL_TRUE );
1423         glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
1424
1425         Vector3 clearColour( 0, 0, 0 );
1426         if ( m_Camera.draw_mode != cd_lighting ) {
1427                 clearColour = g_camwindow_globals.color_cameraback;
1428         }
1429
1430         glClearColor( clearColour[0], clearColour[1], clearColour[2], 0 );
1431         glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
1432
1433         extern void Renderer_ResetStats();
1434         Renderer_ResetStats();
1435         extern void Cull_ResetStats();
1436         Cull_ResetStats();
1437
1438         glMatrixMode( GL_PROJECTION );
1439         glLoadMatrixf( reinterpret_cast<const float*>( &m_Camera.projection ) );
1440
1441         glMatrixMode( GL_MODELVIEW );
1442         glLoadMatrixf( reinterpret_cast<const float*>( &m_Camera.modelview ) );
1443
1444
1445         // one directional light source directly behind the viewer
1446         {
1447                 GLfloat inverse_cam_dir[4], ambient[4], diffuse[4]; //, material[4];
1448
1449                 ambient[0] = ambient[1] = ambient[2] = 0.4f;
1450                 ambient[3] = 1.0f;
1451                 diffuse[0] = diffuse[1] = diffuse[2] = 0.4f;
1452                 diffuse[3] = 1.0f;
1453                 //material[0] = material[1] = material[2] = 0.8f;
1454                 //material[3] = 1.0f;
1455
1456                 inverse_cam_dir[0] = m_Camera.vpn[0];
1457                 inverse_cam_dir[1] = m_Camera.vpn[1];
1458                 inverse_cam_dir[2] = m_Camera.vpn[2];
1459                 inverse_cam_dir[3] = 0;
1460
1461                 glLightfv( GL_LIGHT0, GL_POSITION, inverse_cam_dir );
1462
1463                 glLightfv( GL_LIGHT0, GL_AMBIENT, ambient );
1464                 glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
1465
1466                 glEnable( GL_LIGHT0 );
1467         }
1468
1469
1470         unsigned int globalstate = RENDER_DEPTHTEST | RENDER_COLOURWRITE | RENDER_DEPTHWRITE | RENDER_ALPHATEST | RENDER_BLEND | RENDER_CULLFACE | RENDER_COLOURARRAY | RENDER_OFFSETLINE | RENDER_POLYGONSMOOTH | RENDER_LINESMOOTH | RENDER_FOG | RENDER_COLOURCHANGE;
1471         switch ( m_Camera.draw_mode )
1472         {
1473         case cd_wire:
1474                 break;
1475         case cd_solid:
1476                 globalstate |= RENDER_FILL
1477                                            | RENDER_LIGHTING
1478                                            | RENDER_SMOOTH
1479                                            | RENDER_SCALED;
1480                 break;
1481         case cd_texture:
1482                 globalstate |= RENDER_FILL
1483                                            | RENDER_LIGHTING
1484                                            | RENDER_TEXTURE
1485                                            | RENDER_SMOOTH
1486                                            | RENDER_SCALED;
1487                 break;
1488         case cd_lighting:
1489                 globalstate |= RENDER_FILL
1490                                            | RENDER_LIGHTING
1491                                            | RENDER_TEXTURE
1492                                            | RENDER_SMOOTH
1493                                            | RENDER_SCALED
1494                                            | RENDER_BUMP
1495                                            | RENDER_PROGRAM
1496                                            | RENDER_SCREEN;
1497                 break;
1498         default:
1499                 globalstate = 0;
1500                 break;
1501         }
1502
1503         if ( !g_xywindow_globals.m_bNoStipple ) {
1504                 globalstate |= RENDER_LINESTIPPLE | RENDER_POLYGONSTIPPLE;
1505         }
1506
1507         {
1508                 CamRenderer renderer( globalstate, m_state_select2, m_state_select1, m_view.getViewer() );
1509
1510                 Scene_Render( renderer, m_view );
1511
1512                 renderer.render( m_Camera.modelview, m_Camera.projection );
1513         }
1514
1515         // prepare for 2d stuff
1516         glColor4f( 1, 1, 1, 1 );
1517         glDisable( GL_BLEND );
1518         glMatrixMode( GL_PROJECTION );
1519         glLoadIdentity();
1520         glOrtho( 0, (float)m_Camera.width, 0, (float)m_Camera.height, -100, 100 );
1521         glScalef( 1, -1, 1 );
1522         glTranslatef( 0, -(float)m_Camera.height, 0 );
1523         glMatrixMode( GL_MODELVIEW );
1524         glLoadIdentity();
1525
1526         if ( GlobalOpenGL().GL_1_3() ) {
1527                 glClientActiveTexture( GL_TEXTURE0 );
1528                 glActiveTexture( GL_TEXTURE0 );
1529         }
1530
1531         glDisableClientState( GL_TEXTURE_COORD_ARRAY );
1532         glDisableClientState( GL_NORMAL_ARRAY );
1533         glDisableClientState( GL_COLOR_ARRAY );
1534
1535         glDisable( GL_TEXTURE_2D );
1536         glDisable( GL_LIGHTING );
1537         glDisable( GL_COLOR_MATERIAL );
1538         glDisable( GL_DEPTH_TEST );
1539         glColor3f( 1.f, 1.f, 1.f );
1540         glLineWidth( 1 );
1541
1542         // draw the crosshair
1543         if ( m_bFreeMove ) {
1544                 glBegin( GL_LINES );
1545                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 6 );
1546                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 2 );
1547                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 6 );
1548                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 2 );
1549                 glVertex2f( (float)m_Camera.width / 2.f + 6, (float)m_Camera.height / 2.f );
1550                 glVertex2f( (float)m_Camera.width / 2.f + 2, (float)m_Camera.height / 2.f );
1551                 glVertex2f( (float)m_Camera.width / 2.f - 6, (float)m_Camera.height / 2.f );
1552                 glVertex2f( (float)m_Camera.width / 2.f - 2, (float)m_Camera.height / 2.f );
1553                 glEnd();
1554         }
1555
1556         if ( g_camwindow_globals_private.m_showStats ) {
1557                 glRasterPos3f( 1.0f, static_cast<float>( m_Camera.height ) - GlobalOpenGL().m_font->getPixelDescent(), 0.0f );
1558                 extern const char* Renderer_GetStats();
1559                 GlobalOpenGL().drawString( Renderer_GetStats() );
1560
1561                 glRasterPos3f( 1.0f, static_cast<float>( m_Camera.height ) - GlobalOpenGL().m_font->getPixelDescent() - GlobalOpenGL().m_font->getPixelHeight(), 0.0f );
1562                 extern const char* Cull_GetStats();
1563                 GlobalOpenGL().drawString( Cull_GetStats() );
1564         }
1565
1566         // bind back to the default texture so that we don't have problems
1567         // elsewhere using/modifying texture maps between contexts
1568         glBindTexture( GL_TEXTURE_2D, 0 );
1569 }
1570
1571 void CamWnd::draw(){
1572         m_drawing = true;
1573
1574         //globalOutputStream() << "draw...\n";
1575         if ( glwidget_make_current( m_gl_widget ) != FALSE ) {
1576                 if ( Map_Valid( g_map ) && ScreenUpdates_Enabled() ) {
1577                         GlobalOpenGL_debugAssertNoErrors();
1578                         Cam_Draw();
1579                         GlobalOpenGL_debugAssertNoErrors();
1580                         //qglFinish();
1581
1582                         m_XORRectangle.set( rectangle_t() );
1583                 }
1584
1585                 glwidget_swap_buffers( m_gl_widget );
1586         }
1587
1588         m_drawing = false;
1589 }
1590
1591 void CamWnd::BenchMark(){
1592         double dStart = Sys_DoubleTime();
1593         for ( int i = 0 ; i < 100 ; i++ )
1594         {
1595                 Vector3 angles;
1596                 angles[CAMERA_ROLL] = 0;
1597                 angles[CAMERA_PITCH] = 0;
1598                 angles[CAMERA_YAW] = static_cast<float>( i * ( 360.0 / 100.0 ) );
1599                 Camera_setAngles( *this, angles );
1600         }
1601         double dEnd = Sys_DoubleTime();
1602         globalOutputStream() << FloatFormat( dEnd - dStart, 5, 2 ) << " seconds\n";
1603 }
1604
1605
1606 void fill_view_camera_menu( ui::Menu menu ){
1607         create_check_menu_item_with_mnemonic( menu, "Camera View", "ToggleCamera" );
1608 }
1609
1610 void GlobalCamera_ResetAngles(){
1611         CamWnd& camwnd = *g_camwnd;
1612         Vector3 angles;
1613         angles[CAMERA_ROLL] = angles[CAMERA_PITCH] = 0;
1614         angles[CAMERA_YAW] = static_cast<float>( 22.5 * floor( ( Camera_getAngles( camwnd )[CAMERA_YAW] + 11 ) / 22.5 ) );
1615         Camera_setAngles( camwnd, angles );
1616 }
1617
1618 void Camera_ChangeFloorUp(){
1619         CamWnd& camwnd = *g_camwnd;
1620         camwnd.Cam_ChangeFloor( true );
1621 }
1622
1623 void Camera_ChangeFloorDown(){
1624         CamWnd& camwnd = *g_camwnd;
1625         camwnd.Cam_ChangeFloor( false );
1626 }
1627
1628 void Camera_CubeIn(){
1629         CamWnd& camwnd = *g_camwnd;
1630         g_camwindow_globals.m_nCubicScale--;
1631         if ( g_camwindow_globals.m_nCubicScale < 1 ) {
1632                 g_camwindow_globals.m_nCubicScale = 1;
1633         }
1634         Camera_updateProjection( camwnd.getCamera() );
1635         CamWnd_Update( camwnd );
1636         g_pParentWnd->SetGridStatus();
1637 }
1638
1639 void Camera_CubeOut(){
1640         CamWnd& camwnd = *g_camwnd;
1641         g_camwindow_globals.m_nCubicScale++;
1642         if ( g_camwindow_globals.m_nCubicScale > 23 ) {
1643                 g_camwindow_globals.m_nCubicScale = 23;
1644         }
1645         Camera_updateProjection( camwnd.getCamera() );
1646         CamWnd_Update( camwnd );
1647         g_pParentWnd->SetGridStatus();
1648 }
1649
1650 bool Camera_GetFarClip(){
1651         return g_camwindow_globals_private.m_bCubicClipping;
1652 }
1653
1654 BoolExportCaller g_getfarclip_caller( g_camwindow_globals_private.m_bCubicClipping );
1655 ToggleItem g_getfarclip_item( g_getfarclip_caller );
1656
1657 void Camera_SetFarClip( bool value ){
1658         CamWnd& camwnd = *g_camwnd;
1659         g_camwindow_globals_private.m_bCubicClipping = value;
1660         g_getfarclip_item.update();
1661         Camera_updateProjection( camwnd.getCamera() );
1662         CamWnd_Update( camwnd );
1663 }
1664
1665 void Camera_ToggleFarClip(){
1666         Camera_SetFarClip( !Camera_GetFarClip() );
1667 }
1668
1669
1670 void CamWnd_constructToolbar( ui::Toolbar toolbar ){
1671         toolbar_append_toggle_button( toolbar, "Cubic clip the camera view (\\)", "view_cubicclipping.png", "ToggleCubicClip" );
1672 }
1673
1674 void CamWnd_registerShortcuts(){
1675         toggle_add_accelerator( "ToggleCubicClip" );
1676
1677         if ( g_pGameDescription->mGameType == "doom3" ) {
1678                 command_connect_accelerator( "TogglePreview" );
1679         }
1680
1681         command_connect_accelerator( "CameraSpeedInc" );
1682         command_connect_accelerator( "CameraSpeedDec" );
1683 }
1684
1685
1686 void GlobalCamera_Benchmark(){
1687         CamWnd& camwnd = *g_camwnd;
1688         camwnd.BenchMark();
1689 }
1690
1691 void GlobalCamera_Update(){
1692         CamWnd& camwnd = *g_camwnd;
1693         CamWnd_Update( camwnd );
1694 }
1695
1696 camera_draw_mode CamWnd_GetMode(){
1697         return camera_t::draw_mode;
1698 }
1699 void CamWnd_SetMode( camera_draw_mode mode ){
1700         ShaderCache_setBumpEnabled( mode == cd_lighting );
1701         camera_t::draw_mode = mode;
1702         if ( g_camwnd != 0 ) {
1703                 CamWnd_Update( *g_camwnd );
1704         }
1705 }
1706
1707 void CamWnd_TogglePreview( void ){
1708         // gametype must be doom3 for this function to work
1709         // if the gametype is not doom3 something is wrong with the
1710         // global command list or somebody else calls this function.
1711         ASSERT_MESSAGE( g_pGameDescription->mGameType == "doom3", "CamWnd_TogglePreview called although mGameType is not doom3 compatible" );
1712
1713         // switch between textured and lighting mode
1714         CamWnd_SetMode( ( CamWnd_GetMode() == cd_lighting ) ? cd_texture : cd_lighting );
1715 }
1716
1717
1718 CameraModel* g_camera_model = 0;
1719
1720 void CamWnd_LookThroughCamera( CamWnd& camwnd ){
1721         if ( g_camera_model != 0 ) {
1722                 CamWnd_Add_Handlers_Move( camwnd );
1723                 g_camera_model->setCameraView( 0, Callback() );
1724                 g_camera_model = 0;
1725                 Camera_updateModelview( camwnd.getCamera() );
1726                 Camera_updateProjection( camwnd.getCamera() );
1727                 CamWnd_Update( camwnd );
1728         }
1729 }
1730
1731 inline CameraModel* Instance_getCameraModel( scene::Instance& instance ){
1732         return InstanceTypeCast<CameraModel>::cast( instance );
1733 }
1734
1735 void CamWnd_LookThroughSelected( CamWnd& camwnd ){
1736         if ( g_camera_model != 0 ) {
1737                 CamWnd_LookThroughCamera( camwnd );
1738         }
1739
1740         if ( GlobalSelectionSystem().countSelected() != 0 ) {
1741                 scene::Instance& instance = GlobalSelectionSystem().ultimateSelected();
1742                 CameraModel* cameraModel = Instance_getCameraModel( instance );
1743                 if ( cameraModel != 0 ) {
1744                         CamWnd_Remove_Handlers_Move( camwnd );
1745                         g_camera_model = cameraModel;
1746                         g_camera_model->setCameraView( &camwnd.getCameraView(), ReferenceCaller<CamWnd, CamWnd_LookThroughCamera>( camwnd ) );
1747                 }
1748         }
1749 }
1750
1751 void GlobalCamera_LookThroughSelected(){
1752         CamWnd_LookThroughSelected( *g_camwnd );
1753 }
1754
1755 void GlobalCamera_LookThroughCamera(){
1756         CamWnd_LookThroughCamera( *g_camwnd );
1757 }
1758
1759
1760 void RenderModeImport( int value ){
1761         switch ( value )
1762         {
1763         case 0:
1764                 CamWnd_SetMode( cd_wire );
1765                 break;
1766         case 1:
1767                 CamWnd_SetMode( cd_solid );
1768                 break;
1769         case 2:
1770                 CamWnd_SetMode( cd_texture );
1771                 break;
1772         case 3:
1773                 CamWnd_SetMode( cd_lighting );
1774                 break;
1775         default:
1776                 CamWnd_SetMode( cd_texture );
1777         }
1778 }
1779 typedef FreeCaller1<int, RenderModeImport> RenderModeImportCaller;
1780
1781 void RenderModeExport( const IntImportCallback& importer ){
1782         switch ( CamWnd_GetMode() )
1783         {
1784         case cd_wire:
1785                 importer( 0 );
1786                 break;
1787         case cd_solid:
1788                 importer( 1 );
1789                 break;
1790         case cd_texture:
1791                 importer( 2 );
1792                 break;
1793         case cd_lighting:
1794                 importer( 3 );
1795                 break;
1796         }
1797 }
1798 typedef FreeCaller1<const IntImportCallback&, RenderModeExport> RenderModeExportCaller;
1799
1800 void Camera_constructPreferences( PreferencesPage& page ){
1801         page.appendSlider( "Movement Speed", g_camwindow_globals_private.m_nMoveSpeed, TRUE, 0, 0, 100, MIN_CAM_SPEED, MAX_CAM_SPEED, 1, 10 );
1802         page.appendCheckBox( "", "Link strafe speed to movement speed", g_camwindow_globals_private.m_bCamLinkSpeed );
1803         page.appendSlider( "Rotation Speed", g_camwindow_globals_private.m_nAngleSpeed, TRUE, 0, 0, 3, 1, 180, 1, 10 );
1804         page.appendCheckBox( "", "Invert mouse vertical axis", g_camwindow_globals_private.m_bCamInverseMouse );
1805         page.appendCheckBox(
1806                 "", "Discrete movement",
1807                 FreeCaller1<bool, CamWnd_Move_Discrete_Import>(),
1808                 BoolExportCaller( g_camwindow_globals_private.m_bCamDiscrete )
1809                 );
1810         page.appendCheckBox(
1811                 "", "Enable far-clip plane",
1812                 FreeCaller1<bool, Camera_SetFarClip>(),
1813                 BoolExportCaller( g_camwindow_globals_private.m_bCubicClipping )
1814                 );
1815
1816         if ( g_pGameDescription->mGameType == "doom3" ) {
1817                 const char* render_mode[] = { "Wireframe", "Flatshade", "Textured", "Lighting" };
1818
1819                 page.appendCombo(
1820                         "Render Mode",
1821                         STRING_ARRAY_RANGE( render_mode ),
1822                         IntImportCallback( RenderModeImportCaller() ),
1823                         IntExportCallback( RenderModeExportCaller() )
1824                         );
1825         }
1826         else
1827         {
1828                 const char* render_mode[] = { "Wireframe", "Flatshade", "Textured" };
1829
1830                 page.appendCombo(
1831                         "Render Mode",
1832                         STRING_ARRAY_RANGE( render_mode ),
1833                         IntImportCallback( RenderModeImportCaller() ),
1834                         IntExportCallback( RenderModeExportCaller() )
1835                         );
1836         }
1837
1838         const char* strafe_mode[] = { "Both", "Forward", "Up" };
1839
1840         page.appendCombo(
1841                 "Strafe Mode",
1842                 g_camwindow_globals_private.m_nStrafeMode,
1843                 STRING_ARRAY_RANGE( strafe_mode )
1844                 );
1845 }
1846 void Camera_constructPage( PreferenceGroup& group ){
1847         PreferencesPage page( group.createPage( "Camera", "Camera View Preferences" ) );
1848         Camera_constructPreferences( page );
1849 }
1850 void Camera_registerPreferencesPage(){
1851         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Camera_constructPage>() );
1852 }
1853
1854 #include "preferencesystem.h"
1855 #include "stringio.h"
1856 #include "dialog.h"
1857
1858 typedef FreeCaller1<bool, CamWnd_Move_Discrete_Import> CamWndMoveDiscreteImportCaller;
1859
1860 void CameraSpeed_increase(){
1861         if ( g_camwindow_globals_private.m_nMoveSpeed <= ( MAX_CAM_SPEED - CAM_SPEED_STEP - 10 ) ) {
1862                 g_camwindow_globals_private.m_nMoveSpeed += CAM_SPEED_STEP;
1863         }
1864         else {
1865                 g_camwindow_globals_private.m_nMoveSpeed = MAX_CAM_SPEED - 10;
1866         }
1867 }
1868
1869 void CameraSpeed_decrease(){
1870         if ( g_camwindow_globals_private.m_nMoveSpeed >= ( MIN_CAM_SPEED + CAM_SPEED_STEP ) ) {
1871                 g_camwindow_globals_private.m_nMoveSpeed -= CAM_SPEED_STEP;
1872         }
1873         else {
1874                 g_camwindow_globals_private.m_nMoveSpeed = MIN_CAM_SPEED;
1875         }
1876 }
1877
1878 /// \brief Initialisation for things that have the same lifespan as this module.
1879 void CamWnd_Construct(){
1880         GlobalCommands_insert( "CenterView", FreeCaller<GlobalCamera_ResetAngles>(), Accelerator( GDK_KEY_End ) );
1881
1882         GlobalToggles_insert( "ToggleCubicClip", FreeCaller<Camera_ToggleFarClip>(), ToggleItem::AddCallbackCaller( g_getfarclip_item ), Accelerator( '\\', (GdkModifierType)GDK_CONTROL_MASK ) );
1883         GlobalCommands_insert( "CubicClipZoomIn", FreeCaller<Camera_CubeIn>(), Accelerator( '[', (GdkModifierType)GDK_CONTROL_MASK ) );
1884         GlobalCommands_insert( "CubicClipZoomOut", FreeCaller<Camera_CubeOut>(), Accelerator( ']', (GdkModifierType)GDK_CONTROL_MASK ) );
1885
1886         GlobalCommands_insert( "UpFloor", FreeCaller<Camera_ChangeFloorUp>(), Accelerator( GDK_KEY_Prior ) );
1887         GlobalCommands_insert( "DownFloor", FreeCaller<Camera_ChangeFloorDown>(), Accelerator( GDK_KEY_Next ) );
1888
1889         GlobalToggles_insert( "ToggleCamera", ToggleShown::ToggleCaller( g_camera_shown ), ToggleItem::AddCallbackCaller( g_camera_shown.m_item ), Accelerator( 'C', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
1890         GlobalCommands_insert( "LookThroughSelected", FreeCaller<GlobalCamera_LookThroughSelected>() );
1891         GlobalCommands_insert( "LookThroughCamera", FreeCaller<GlobalCamera_LookThroughCamera>() );
1892
1893         if ( g_pGameDescription->mGameType == "doom3" ) {
1894                 GlobalCommands_insert( "TogglePreview", FreeCaller<CamWnd_TogglePreview>(), Accelerator( GDK_KEY_F3 ) );
1895         }
1896
1897         GlobalCommands_insert( "CameraSpeedInc", FreeCaller<CameraSpeed_increase>(), Accelerator( GDK_KEY_KP_Add, (GdkModifierType)GDK_SHIFT_MASK ) );
1898         GlobalCommands_insert( "CameraSpeedDec", FreeCaller<CameraSpeed_decrease>(), Accelerator( GDK_KEY_KP_Subtract, (GdkModifierType)GDK_SHIFT_MASK ) );
1899
1900         GlobalShortcuts_insert( "CameraForward", Accelerator( GDK_KEY_Up ) );
1901         GlobalShortcuts_insert( "CameraBack", Accelerator( GDK_KEY_Down ) );
1902         GlobalShortcuts_insert( "CameraLeft", Accelerator( GDK_KEY_Left ) );
1903         GlobalShortcuts_insert( "CameraRight", Accelerator( GDK_KEY_Right ) );
1904         GlobalShortcuts_insert( "CameraStrafeRight", Accelerator( GDK_KEY_period ) );
1905         GlobalShortcuts_insert( "CameraStrafeLeft", Accelerator( GDK_KEY_comma ) );
1906
1907         GlobalShortcuts_insert( "CameraUp", Accelerator( 'D' ) );
1908         GlobalShortcuts_insert( "CameraDown", Accelerator( 'C' ) );
1909         GlobalShortcuts_insert( "CameraAngleUp", Accelerator( 'A' ) );
1910         GlobalShortcuts_insert( "CameraAngleDown", Accelerator( 'Z' ) );
1911
1912         GlobalShortcuts_insert( "CameraFreeMoveForward", Accelerator( GDK_KEY_Up ) );
1913         GlobalShortcuts_insert( "CameraFreeMoveBack", Accelerator( GDK_KEY_Down ) );
1914         GlobalShortcuts_insert( "CameraFreeMoveLeft", Accelerator( GDK_KEY_Left ) );
1915         GlobalShortcuts_insert( "CameraFreeMoveRight", Accelerator( GDK_KEY_Right ) );
1916
1917         GlobalToggles_insert( "ShowStats", ShowStatsToggleCaller(), ToggleItem::AddCallbackCaller( g_show_stats ) );
1918
1919         GlobalPreferenceSystem().registerPreference( "ShowStats", BoolImportStringCaller( g_camwindow_globals_private.m_showStats ), BoolExportStringCaller( g_camwindow_globals_private.m_showStats ) );
1920         GlobalPreferenceSystem().registerPreference( "MoveSpeed", IntImportStringCaller( g_camwindow_globals_private.m_nMoveSpeed ), IntExportStringCaller( g_camwindow_globals_private.m_nMoveSpeed ) );
1921         GlobalPreferenceSystem().registerPreference( "CamLinkSpeed", BoolImportStringCaller( g_camwindow_globals_private.m_bCamLinkSpeed ), BoolExportStringCaller( g_camwindow_globals_private.m_bCamLinkSpeed ) );
1922         GlobalPreferenceSystem().registerPreference( "AngleSpeed", IntImportStringCaller( g_camwindow_globals_private.m_nAngleSpeed ), IntExportStringCaller( g_camwindow_globals_private.m_nAngleSpeed ) );
1923         GlobalPreferenceSystem().registerPreference( "CamInverseMouse", BoolImportStringCaller( g_camwindow_globals_private.m_bCamInverseMouse ), BoolExportStringCaller( g_camwindow_globals_private.m_bCamInverseMouse ) );
1924         GlobalPreferenceSystem().registerPreference( "CamDiscrete", makeBoolStringImportCallback( CamWndMoveDiscreteImportCaller() ), BoolExportStringCaller( g_camwindow_globals_private.m_bCamDiscrete ) );
1925         GlobalPreferenceSystem().registerPreference( "CubicClipping", BoolImportStringCaller( g_camwindow_globals_private.m_bCubicClipping ), BoolExportStringCaller( g_camwindow_globals_private.m_bCubicClipping ) );
1926         GlobalPreferenceSystem().registerPreference( "CubicScale", IntImportStringCaller( g_camwindow_globals.m_nCubicScale ), IntExportStringCaller( g_camwindow_globals.m_nCubicScale ) );
1927         GlobalPreferenceSystem().registerPreference( "SI_Colors4", Vector3ImportStringCaller( g_camwindow_globals.color_cameraback ), Vector3ExportStringCaller( g_camwindow_globals.color_cameraback ) );
1928         GlobalPreferenceSystem().registerPreference( "SI_Colors12", Vector3ImportStringCaller( g_camwindow_globals.color_selbrushes3d ), Vector3ExportStringCaller( g_camwindow_globals.color_selbrushes3d ) );
1929         GlobalPreferenceSystem().registerPreference( "CameraRenderMode", makeIntStringImportCallback( RenderModeImportCaller() ), makeIntStringExportCallback( RenderModeExportCaller() ) );
1930         GlobalPreferenceSystem().registerPreference( "StrafeMode", IntImportStringCaller( g_camwindow_globals_private.m_nStrafeMode ), IntExportStringCaller( g_camwindow_globals_private.m_nStrafeMode ) );
1931
1932         CamWnd_constructStatic();
1933
1934         Camera_registerPreferencesPage();
1935 }
1936 void CamWnd_Destroy(){
1937         CamWnd_destroyStatic();
1938 }