]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/camwindow.cpp
Fix GCC7 issues
[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 ( gtk_widget_get_visible( self.m_gl_widget ) ) {
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         GtkAllocation allocation;
858         gtk_widget_get_allocation(widget, &allocation);
859         return WindowVector( static_cast<float>( allocation.width / 2 ), static_cast<float>(allocation.height / 2 ) );
860 }
861
862 gboolean selection_button_press_freemove( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
863         if ( event->type == GDK_BUTTON_PRESS ) {
864                 observer->onMouseDown( windowvector_for_widget_centre( widget ), button_for_button( event->button ), modifiers_for_state( event->state ) );
865         }
866         return FALSE;
867 }
868
869 gboolean selection_button_release_freemove( ui::Widget widget, GdkEventButton* event, WindowObserver* observer ){
870         if ( event->type == GDK_BUTTON_RELEASE ) {
871                 observer->onMouseUp( windowvector_for_widget_centre( widget ), button_for_button( event->button ), modifiers_for_state( event->state ) );
872         }
873         return FALSE;
874 }
875
876 gboolean selection_motion_freemove( ui::Widget widget, GdkEventMotion *event, WindowObserver* observer ){
877         observer->onMouseMotion( windowvector_for_widget_centre( widget ), modifiers_for_state( event->state ) );
878         return FALSE;
879 }
880
881 gboolean wheelmove_scroll( ui::Widget widget, GdkEventScroll* event, CamWnd* camwnd ){
882         if ( event->direction == GDK_SCROLL_UP ) {
883                 Camera_Freemove_updateAxes( camwnd->getCamera() );
884                 Camera_setOrigin( *camwnd, vector3_added( Camera_getOrigin( *camwnd ), vector3_scaled( camwnd->getCamera().forward, static_cast<float>( g_camwindow_globals_private.m_nMoveSpeed ) ) ) );
885         }
886         else if ( event->direction == GDK_SCROLL_DOWN ) {
887                 Camera_Freemove_updateAxes( camwnd->getCamera() );
888                 Camera_setOrigin( *camwnd, vector3_added( Camera_getOrigin( *camwnd ), vector3_scaled( camwnd->getCamera().forward, -static_cast<float>( g_camwindow_globals_private.m_nMoveSpeed ) ) ) );
889         }
890
891         return FALSE;
892 }
893
894 gboolean camera_size_allocate( ui::Widget widget, GtkAllocation* allocation, CamWnd* camwnd ){
895         camwnd->getCamera().width = allocation->width;
896         camwnd->getCamera().height = allocation->height;
897         Camera_updateProjection( camwnd->getCamera() );
898         camwnd->m_window_observer->onSizeChanged( camwnd->getCamera().width, camwnd->getCamera().height );
899         camwnd->queue_draw();
900         return FALSE;
901 }
902
903 gboolean camera_expose( ui::Widget widget, GdkEventExpose* event, gpointer data ){
904         reinterpret_cast<CamWnd*>( data )->draw();
905         return FALSE;
906 }
907
908 void KeyEvent_connect( const char* name ){
909         const KeyEvent& keyEvent = GlobalKeyEvents_find( name );
910         keydown_accelerators_add( keyEvent.m_accelerator, keyEvent.m_keyDown );
911         keyup_accelerators_add( keyEvent.m_accelerator, keyEvent.m_keyUp );
912 }
913
914 void KeyEvent_disconnect( const char* name ){
915         const KeyEvent& keyEvent = GlobalKeyEvents_find( name );
916         keydown_accelerators_remove( keyEvent.m_accelerator );
917         keyup_accelerators_remove( keyEvent.m_accelerator );
918 }
919
920 void CamWnd_registerCommands( CamWnd& camwnd ){
921         GlobalKeyEvents_insert( "CameraForward", Accelerator( GDK_KEY_Up ),
922                                                         ReferenceCaller<camera_t, Camera_MoveForward_KeyDown>( camwnd.getCamera() ),
923                                                         ReferenceCaller<camera_t, Camera_MoveForward_KeyUp>( camwnd.getCamera() )
924                                                         );
925         GlobalKeyEvents_insert( "CameraBack", Accelerator( GDK_KEY_Down ),
926                                                         ReferenceCaller<camera_t, Camera_MoveBack_KeyDown>( camwnd.getCamera() ),
927                                                         ReferenceCaller<camera_t, Camera_MoveBack_KeyUp>( camwnd.getCamera() )
928                                                         );
929         GlobalKeyEvents_insert( "CameraLeft", Accelerator( GDK_KEY_Left ),
930                                                         ReferenceCaller<camera_t, Camera_RotateLeft_KeyDown>( camwnd.getCamera() ),
931                                                         ReferenceCaller<camera_t, Camera_RotateLeft_KeyUp>( camwnd.getCamera() )
932                                                         );
933         GlobalKeyEvents_insert( "CameraRight", Accelerator( GDK_KEY_Right ),
934                                                         ReferenceCaller<camera_t, Camera_RotateRight_KeyDown>( camwnd.getCamera() ),
935                                                         ReferenceCaller<camera_t, Camera_RotateRight_KeyUp>( camwnd.getCamera() )
936                                                         );
937         GlobalKeyEvents_insert( "CameraStrafeRight", Accelerator( GDK_KEY_period ),
938                                                         ReferenceCaller<camera_t, Camera_MoveRight_KeyDown>( camwnd.getCamera() ),
939                                                         ReferenceCaller<camera_t, Camera_MoveRight_KeyUp>( camwnd.getCamera() )
940                                                         );
941         GlobalKeyEvents_insert( "CameraStrafeLeft", Accelerator( GDK_KEY_comma ),
942                                                         ReferenceCaller<camera_t, Camera_MoveLeft_KeyDown>( camwnd.getCamera() ),
943                                                         ReferenceCaller<camera_t, Camera_MoveLeft_KeyUp>( camwnd.getCamera() )
944                                                         );
945         GlobalKeyEvents_insert( "CameraUp", Accelerator( 'D' ),
946                                                         ReferenceCaller<camera_t, Camera_MoveUp_KeyDown>( camwnd.getCamera() ),
947                                                         ReferenceCaller<camera_t, Camera_MoveUp_KeyUp>( camwnd.getCamera() )
948                                                         );
949         GlobalKeyEvents_insert( "CameraDown", Accelerator( 'C' ),
950                                                         ReferenceCaller<camera_t, Camera_MoveDown_KeyDown>( camwnd.getCamera() ),
951                                                         ReferenceCaller<camera_t, Camera_MoveDown_KeyUp>( camwnd.getCamera() )
952                                                         );
953         GlobalKeyEvents_insert( "CameraAngleDown", Accelerator( 'A' ),
954                                                         ReferenceCaller<camera_t, Camera_PitchDown_KeyDown>( camwnd.getCamera() ),
955                                                         ReferenceCaller<camera_t, Camera_PitchDown_KeyUp>( camwnd.getCamera() )
956                                                         );
957         GlobalKeyEvents_insert( "CameraAngleUp", Accelerator( 'Z' ),
958                                                         ReferenceCaller<camera_t, Camera_PitchUp_KeyDown>( camwnd.getCamera() ),
959                                                         ReferenceCaller<camera_t, Camera_PitchUp_KeyUp>( camwnd.getCamera() )
960                                                         );
961
962         GlobalKeyEvents_insert( "CameraFreeMoveForward", Accelerator( GDK_KEY_Up ),
963                                                         FreeMoveCameraMoveForwardKeyDownCaller( camwnd.getCamera() ),
964                                                         FreeMoveCameraMoveForwardKeyUpCaller( camwnd.getCamera() )
965                                                         );
966         GlobalKeyEvents_insert( "CameraFreeMoveBack", Accelerator( GDK_KEY_Down ),
967                                                         FreeMoveCameraMoveBackKeyDownCaller( camwnd.getCamera() ),
968                                                         FreeMoveCameraMoveBackKeyUpCaller( camwnd.getCamera() )
969                                                         );
970         GlobalKeyEvents_insert( "CameraFreeMoveLeft", Accelerator( GDK_KEY_Left ),
971                                                         FreeMoveCameraMoveLeftKeyDownCaller( camwnd.getCamera() ),
972                                                         FreeMoveCameraMoveLeftKeyUpCaller( camwnd.getCamera() )
973                                                         );
974         GlobalKeyEvents_insert( "CameraFreeMoveRight", Accelerator( GDK_KEY_Right ),
975                                                         FreeMoveCameraMoveRightKeyDownCaller( camwnd.getCamera() ),
976                                                         FreeMoveCameraMoveRightKeyUpCaller( camwnd.getCamera() )
977                                                         );
978         GlobalKeyEvents_insert( "CameraFreeMoveUp", Accelerator( 'D' ),
979                                                         FreeMoveCameraMoveUpKeyDownCaller( camwnd.getCamera() ),
980                                                         FreeMoveCameraMoveUpKeyUpCaller( camwnd.getCamera() )
981                                                         );
982         GlobalKeyEvents_insert( "CameraFreeMoveDown", Accelerator( 'C' ),
983                                                         FreeMoveCameraMoveDownKeyDownCaller( camwnd.getCamera() ),
984                                                         FreeMoveCameraMoveDownKeyUpCaller( camwnd.getCamera() )
985                                                         );
986
987         GlobalCommands_insert( "CameraForward", ReferenceCaller<camera_t, Camera_MoveForward_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Up ) );
988         GlobalCommands_insert( "CameraBack", ReferenceCaller<camera_t, Camera_MoveBack_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Down ) );
989         GlobalCommands_insert( "CameraLeft", ReferenceCaller<camera_t, Camera_RotateLeft_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Left ) );
990         GlobalCommands_insert( "CameraRight", ReferenceCaller<camera_t, Camera_RotateRight_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_Right ) );
991         GlobalCommands_insert( "CameraStrafeRight", ReferenceCaller<camera_t, Camera_MoveRight_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_period ) );
992         GlobalCommands_insert( "CameraStrafeLeft", ReferenceCaller<camera_t, Camera_MoveLeft_Discrete>( camwnd.getCamera() ), Accelerator( GDK_KEY_comma ) );
993
994         GlobalCommands_insert( "CameraUp", ReferenceCaller<camera_t, Camera_MoveUp_Discrete>( camwnd.getCamera() ), Accelerator( 'D' ) );
995         GlobalCommands_insert( "CameraDown", ReferenceCaller<camera_t, Camera_MoveDown_Discrete>( camwnd.getCamera() ), Accelerator( 'C' ) );
996         GlobalCommands_insert( "CameraAngleUp", ReferenceCaller<camera_t, Camera_PitchUp_Discrete>( camwnd.getCamera() ), Accelerator( 'A' ) );
997         GlobalCommands_insert( "CameraAngleDown", ReferenceCaller<camera_t, Camera_PitchDown_Discrete>( camwnd.getCamera() ), Accelerator( 'Z' ) );
998 }
999
1000 void CamWnd_Move_Enable( CamWnd& camwnd ){
1001         KeyEvent_connect( "CameraForward" );
1002         KeyEvent_connect( "CameraBack" );
1003         KeyEvent_connect( "CameraLeft" );
1004         KeyEvent_connect( "CameraRight" );
1005         KeyEvent_connect( "CameraStrafeRight" );
1006         KeyEvent_connect( "CameraStrafeLeft" );
1007         KeyEvent_connect( "CameraUp" );
1008         KeyEvent_connect( "CameraDown" );
1009         KeyEvent_connect( "CameraAngleUp" );
1010         KeyEvent_connect( "CameraAngleDown" );
1011 }
1012
1013 void CamWnd_Move_Disable( CamWnd& camwnd ){
1014         KeyEvent_disconnect( "CameraForward" );
1015         KeyEvent_disconnect( "CameraBack" );
1016         KeyEvent_disconnect( "CameraLeft" );
1017         KeyEvent_disconnect( "CameraRight" );
1018         KeyEvent_disconnect( "CameraStrafeRight" );
1019         KeyEvent_disconnect( "CameraStrafeLeft" );
1020         KeyEvent_disconnect( "CameraUp" );
1021         KeyEvent_disconnect( "CameraDown" );
1022         KeyEvent_disconnect( "CameraAngleUp" );
1023         KeyEvent_disconnect( "CameraAngleDown" );
1024 }
1025
1026 void CamWnd_Move_Discrete_Enable( CamWnd& camwnd ){
1027         command_connect_accelerator( "CameraForward" );
1028         command_connect_accelerator( "CameraBack" );
1029         command_connect_accelerator( "CameraLeft" );
1030         command_connect_accelerator( "CameraRight" );
1031         command_connect_accelerator( "CameraStrafeRight" );
1032         command_connect_accelerator( "CameraStrafeLeft" );
1033         command_connect_accelerator( "CameraUp" );
1034         command_connect_accelerator( "CameraDown" );
1035         command_connect_accelerator( "CameraAngleUp" );
1036         command_connect_accelerator( "CameraAngleDown" );
1037 }
1038
1039 void CamWnd_Move_Discrete_Disable( CamWnd& camwnd ){
1040         command_disconnect_accelerator( "CameraForward" );
1041         command_disconnect_accelerator( "CameraBack" );
1042         command_disconnect_accelerator( "CameraLeft" );
1043         command_disconnect_accelerator( "CameraRight" );
1044         command_disconnect_accelerator( "CameraStrafeRight" );
1045         command_disconnect_accelerator( "CameraStrafeLeft" );
1046         command_disconnect_accelerator( "CameraUp" );
1047         command_disconnect_accelerator( "CameraDown" );
1048         command_disconnect_accelerator( "CameraAngleUp" );
1049         command_disconnect_accelerator( "CameraAngleDown" );
1050 }
1051
1052 void CamWnd_Move_Discrete_Import( CamWnd& camwnd, bool value ){
1053         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1054                 CamWnd_Move_Discrete_Disable( camwnd );
1055         }
1056         else
1057         {
1058                 CamWnd_Move_Disable( camwnd );
1059         }
1060
1061         g_camwindow_globals_private.m_bCamDiscrete = value;
1062
1063         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1064                 CamWnd_Move_Discrete_Enable( camwnd );
1065         }
1066         else
1067         {
1068                 CamWnd_Move_Enable( camwnd );
1069         }
1070 }
1071
1072 void CamWnd_Move_Discrete_Import( bool value ){
1073         if ( g_camwnd != 0 ) {
1074                 CamWnd_Move_Discrete_Import( *g_camwnd, value );
1075         }
1076         else
1077         {
1078                 g_camwindow_globals_private.m_bCamDiscrete = value;
1079         }
1080 }
1081
1082
1083
1084 void CamWnd_Add_Handlers_Move( CamWnd& camwnd ){
1085         camwnd.m_selection_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( selection_button_press ), camwnd.m_window_observer );
1086         camwnd.m_selection_button_release_handler = camwnd.m_gl_widget.connect( "button_release_event", G_CALLBACK( selection_button_release ), camwnd.m_window_observer );
1087         camwnd.m_selection_motion_handler = camwnd.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( DeferredMotion::gtk_motion ), &camwnd.m_deferred_motion );
1088
1089         camwnd.m_freelook_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( enable_freelook_button_press ), &camwnd );
1090
1091         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1092                 CamWnd_Move_Discrete_Enable( camwnd );
1093         }
1094         else
1095         {
1096                 CamWnd_Move_Enable( camwnd );
1097         }
1098 }
1099
1100 void CamWnd_Remove_Handlers_Move( CamWnd& camwnd ){
1101         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_press_handler );
1102         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_release_handler );
1103         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_motion_handler );
1104
1105         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_freelook_button_press_handler );
1106
1107         if ( g_camwindow_globals_private.m_bCamDiscrete ) {
1108                 CamWnd_Move_Discrete_Disable( camwnd );
1109         }
1110         else
1111         {
1112                 CamWnd_Move_Disable( camwnd );
1113         }
1114 }
1115
1116 void CamWnd_Add_Handlers_FreeMove( CamWnd& camwnd ){
1117         camwnd.m_selection_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( selection_button_press_freemove ), camwnd.m_window_observer );
1118         camwnd.m_selection_button_release_handler = camwnd.m_gl_widget.connect( "button_release_event", G_CALLBACK( selection_button_release_freemove ), camwnd.m_window_observer );
1119         camwnd.m_selection_motion_handler = camwnd.m_gl_widget.connect( "motion_notify_event", G_CALLBACK( selection_motion_freemove ), camwnd.m_window_observer );
1120
1121         camwnd.m_freelook_button_press_handler = camwnd.m_gl_widget.connect( "button_press_event", G_CALLBACK( disable_freelook_button_press ), &camwnd );
1122
1123         KeyEvent_connect( "CameraFreeMoveForward" );
1124         KeyEvent_connect( "CameraFreeMoveBack" );
1125         KeyEvent_connect( "CameraFreeMoveLeft" );
1126         KeyEvent_connect( "CameraFreeMoveRight" );
1127         KeyEvent_connect( "CameraFreeMoveUp" );
1128         KeyEvent_connect( "CameraFreeMoveDown" );
1129 }
1130
1131 void CamWnd_Remove_Handlers_FreeMove( CamWnd& camwnd ){
1132         KeyEvent_disconnect( "CameraFreeMoveForward" );
1133         KeyEvent_disconnect( "CameraFreeMoveBack" );
1134         KeyEvent_disconnect( "CameraFreeMoveLeft" );
1135         KeyEvent_disconnect( "CameraFreeMoveRight" );
1136         KeyEvent_disconnect( "CameraFreeMoveUp" );
1137         KeyEvent_disconnect( "CameraFreeMoveDown" );
1138
1139         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_press_handler );
1140         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_button_release_handler );
1141         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_selection_motion_handler );
1142
1143         g_signal_handler_disconnect( G_OBJECT( camwnd.m_gl_widget ), camwnd.m_freelook_button_press_handler );
1144 }
1145
1146 CamWnd::CamWnd() :
1147         m_view( true ),
1148         m_Camera( &m_view, CamWndQueueDraw( *this ) ),
1149         m_cameraview( m_Camera, &m_view, ReferenceCaller<CamWnd, CamWnd_Update>( *this ) ),
1150         m_gl_widget( glwidget_new( TRUE ) ),
1151         m_window_observer( NewWindowObserver() ),
1152         m_XORRectangle( m_gl_widget ),
1153         m_deferredDraw( WidgetQueueDrawCaller( m_gl_widget ) ),
1154         m_deferred_motion( selection_motion, m_window_observer ),
1155         m_selection_button_press_handler( 0 ),
1156         m_selection_button_release_handler( 0 ),
1157         m_selection_motion_handler( 0 ),
1158         m_freelook_button_press_handler( 0 ),
1159         m_drawing( false ){
1160         m_bFreeMove = false;
1161
1162         GlobalWindowObservers_add( m_window_observer );
1163         GlobalWindowObservers_connectWidget( m_gl_widget );
1164
1165         m_window_observer->setRectangleDrawCallback( ReferenceCaller1<CamWnd, rect_t, camwnd_update_xor_rectangle>( *this ) );
1166         m_window_observer->setView( m_view );
1167
1168         g_object_ref( m_gl_widget._handle );
1169
1170         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 );
1171         gtk_widget_set_can_focus( m_gl_widget, true );
1172
1173         m_sizeHandler = m_gl_widget.connect( "size_allocate", G_CALLBACK( camera_size_allocate ), this );
1174         m_exposeHandler = m_gl_widget.on_render( G_CALLBACK( camera_expose ), this );
1175
1176         Map_addValidCallback( g_map, DeferredDrawOnMapValidChangedCaller( m_deferredDraw ) );
1177
1178         CamWnd_registerCommands( *this );
1179
1180         CamWnd_Add_Handlers_Move( *this );
1181
1182         m_gl_widget.connect( "scroll_event", G_CALLBACK( wheelmove_scroll ), this );
1183
1184         AddSceneChangeCallback( ReferenceCaller<CamWnd, CamWnd_Update>( *this ) );
1185
1186         PressedButtons_connect( g_pressedButtons, m_gl_widget );
1187 }
1188
1189 CamWnd::~CamWnd(){
1190         if ( m_bFreeMove ) {
1191                 DisableFreeMove();
1192         }
1193
1194         CamWnd_Remove_Handlers_Move( *this );
1195
1196         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_sizeHandler );
1197         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_exposeHandler );
1198
1199         m_gl_widget.unref();
1200
1201         m_window_observer->release();
1202 }
1203
1204 class FloorHeightWalker : public scene::Graph::Walker
1205 {
1206 float m_current;
1207 float& m_bestUp;
1208 float& m_bestDown;
1209 public:
1210 FloorHeightWalker( float current, float& bestUp, float& bestDown ) :
1211         m_current( current ), m_bestUp( bestUp ), m_bestDown( bestDown ){
1212         bestUp = g_MaxWorldCoord;
1213         bestDown = -g_MaxWorldCoord;
1214 }
1215 bool pre( const scene::Path& path, scene::Instance& instance ) const {
1216         if ( path.top().get().visible()
1217                  && Node_isBrush( path.top() ) ) { // this node is a floor
1218                 const AABB& aabb = instance.worldAABB();
1219                 float floorHeight = aabb.origin.z() + aabb.extents.z();
1220                 if ( floorHeight > m_current && floorHeight < m_bestUp ) {
1221                         m_bestUp = floorHeight;
1222                 }
1223                 if ( floorHeight < m_current && floorHeight > m_bestDown ) {
1224                         m_bestDown = floorHeight;
1225                 }
1226         }
1227         return true;
1228 }
1229 };
1230
1231 void CamWnd::Cam_ChangeFloor( bool up ){
1232         float current = m_Camera.origin[2] - 48;
1233         float bestUp;
1234         float bestDown;
1235         GlobalSceneGraph().traverse( FloorHeightWalker( current, bestUp, bestDown ) );
1236
1237         if ( up && bestUp != g_MaxWorldCoord ) {
1238                 current = bestUp;
1239         }
1240         if ( !up && bestDown != -g_MaxWorldCoord ) {
1241                 current = bestDown;
1242         }
1243
1244         m_Camera.origin[2] = current + 48;
1245         Camera_updateModelview( getCamera() );
1246         CamWnd_Update( *this );
1247         CameraMovedNotify();
1248 }
1249
1250
1251 #if 0
1252
1253 // button_press
1254 Sys_GetCursorPos( &m_PositionDragCursorX, &m_PositionDragCursorY );
1255
1256 // motion
1257 if ( ( m_bFreeMove && ( buttons == ( RAD_CONTROL | RAD_SHIFT ) ) )
1258          || ( !m_bFreeMove && ( buttons == ( RAD_RBUTTON | RAD_CONTROL ) ) ) ) {
1259         Cam_PositionDrag();
1260         CamWnd_Update( camwnd );
1261         CameraMovedNotify();
1262         return;
1263 }
1264
1265 void CamWnd::Cam_PositionDrag(){
1266         int x, y;
1267
1268         Sys_GetCursorPos( GTK_WINDOW( m_gl_widget ), &x, &y );
1269         if ( x != m_PositionDragCursorX || y != m_PositionDragCursorY ) {
1270                 x -= m_PositionDragCursorX;
1271                 vector3_add( m_Camera.origin, vector3_scaled( m_Camera.vright, x ) );
1272                 y -= m_PositionDragCursorY;
1273                 m_Camera.origin[2] -= y;
1274                 Camera_updateModelview();
1275                 CamWnd_Update( camwnd );
1276                 CameraMovedNotify();
1277
1278                 Sys_SetCursorPos( GTK_WINDOW( m_parent ), m_PositionDragCursorX, m_PositionDragCursorY );
1279         }
1280 }
1281 #endif
1282
1283
1284 // NOTE TTimo if there's an OS-level focus out of the application
1285 //   then we can release the camera cursor grab
1286 static gboolean camwindow_freemove_focusout( ui::Widget widget, GdkEventFocus* event, gpointer data ){
1287         reinterpret_cast<CamWnd*>( data )->DisableFreeMove();
1288         return FALSE;
1289 }
1290
1291 void CamWnd::EnableFreeMove(){
1292         //globalOutputStream() << "EnableFreeMove\n";
1293
1294         ASSERT_MESSAGE( !m_bFreeMove, "EnableFreeMove: free-move was already enabled" );
1295         m_bFreeMove = true;
1296         Camera_clearMovementFlags( getCamera(), MOVE_ALL );
1297
1298         CamWnd_Remove_Handlers_Move( *this );
1299         CamWnd_Add_Handlers_FreeMove( *this );
1300
1301         gtk_window_set_focus( m_parent, m_gl_widget );
1302         m_freemove_handle_focusout = m_gl_widget.connect( "focus_out_event", G_CALLBACK( camwindow_freemove_focusout ), this );
1303         m_freezePointer.freeze_pointer( m_parent, Camera_motionDelta, &m_Camera );
1304
1305         CamWnd_Update( *this );
1306 }
1307
1308 void CamWnd::DisableFreeMove(){
1309         //globalOutputStream() << "DisableFreeMove\n";
1310
1311         ASSERT_MESSAGE( m_bFreeMove, "DisableFreeMove: free-move was not enabled" );
1312         m_bFreeMove = false;
1313         Camera_clearMovementFlags( getCamera(), MOVE_ALL );
1314
1315         CamWnd_Remove_Handlers_FreeMove( *this );
1316         CamWnd_Add_Handlers_Move( *this );
1317
1318         m_freezePointer.unfreeze_pointer( m_parent );
1319         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_freemove_handle_focusout );
1320
1321         CamWnd_Update( *this );
1322 }
1323
1324
1325 #include "renderer.h"
1326
1327 class CamRenderer : public Renderer
1328 {
1329 struct state_type
1330 {
1331         state_type() : m_highlight( 0 ), m_state( 0 ), m_lights( 0 ){
1332         }
1333         unsigned int m_highlight;
1334         Shader* m_state;
1335         const LightList* m_lights;
1336 };
1337
1338 std::vector<state_type> m_state_stack;
1339 RenderStateFlags m_globalstate;
1340 Shader* m_state_select0;
1341 Shader* m_state_select1;
1342 const Vector3& m_viewer;
1343
1344 public:
1345 CamRenderer( RenderStateFlags globalstate, Shader* select0, Shader* select1, const Vector3& viewer ) :
1346         m_globalstate( globalstate ),
1347         m_state_select0( select0 ),
1348         m_state_select1( select1 ),
1349         m_viewer( viewer ){
1350         ASSERT_NOTNULL( select0 );
1351         ASSERT_NOTNULL( select1 );
1352         m_state_stack.push_back( state_type() );
1353 }
1354
1355 void SetState( Shader* state, EStyle style ){
1356         ASSERT_NOTNULL( state );
1357         if ( style == eFullMaterials ) {
1358                 m_state_stack.back().m_state = state;
1359         }
1360 }
1361 const EStyle getStyle() const {
1362         return eFullMaterials;
1363 }
1364 void PushState(){
1365         m_state_stack.push_back( m_state_stack.back() );
1366 }
1367 void PopState(){
1368         ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" );
1369         m_state_stack.pop_back();
1370 }
1371 void Highlight( EHighlightMode mode, bool bEnable = true ){
1372         ( bEnable )
1373         ? m_state_stack.back().m_highlight |= mode
1374                                                                                   : m_state_stack.back().m_highlight &= ~mode;
1375 }
1376 void setLights( const LightList& lights ){
1377         m_state_stack.back().m_lights = &lights;
1378 }
1379 void addRenderable( const OpenGLRenderable& renderable, const Matrix4& world ){
1380         if ( m_state_stack.back().m_highlight & ePrimitive ) {
1381                 m_state_select0->addRenderable( renderable, world, m_state_stack.back().m_lights );
1382         }
1383         if ( m_state_stack.back().m_highlight & eFace ) {
1384                 m_state_select1->addRenderable( renderable, world, m_state_stack.back().m_lights );
1385         }
1386
1387         m_state_stack.back().m_state->addRenderable( renderable, world, m_state_stack.back().m_lights );
1388 }
1389
1390 void render( const Matrix4& modelview, const Matrix4& projection ){
1391         GlobalShaderCache().render( m_globalstate, modelview, projection, m_viewer );
1392 }
1393 };
1394
1395 /*
1396    ==============
1397    Cam_Draw
1398    ==============
1399  */
1400
1401 void ShowStatsToggle(){
1402         g_camwindow_globals_private.m_showStats ^= 1;
1403 }
1404 typedef FreeCaller<ShowStatsToggle> ShowStatsToggleCaller;
1405
1406 void ShowStatsExport( const BoolImportCallback& importer ){
1407         importer( g_camwindow_globals_private.m_showStats );
1408 }
1409 typedef FreeCaller1<const BoolImportCallback&, ShowStatsExport> ShowStatsExportCaller;
1410
1411 ShowStatsExportCaller g_show_stats_caller;
1412 BoolExportCallback g_show_stats_callback( g_show_stats_caller );
1413 ToggleItem g_show_stats( g_show_stats_callback );
1414
1415 void CamWnd::Cam_Draw(){
1416         glViewport( 0, 0, m_Camera.width, m_Camera.height );
1417 #if 0
1418         GLint viewprt[4];
1419         glGetIntegerv( GL_VIEWPORT, viewprt );
1420 #endif
1421
1422         // enable depth buffer writes
1423         glDepthMask( GL_TRUE );
1424         glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
1425
1426         Vector3 clearColour( 0, 0, 0 );
1427         if ( m_Camera.draw_mode != cd_lighting ) {
1428                 clearColour = g_camwindow_globals.color_cameraback;
1429         }
1430
1431         glClearColor( clearColour[0], clearColour[1], clearColour[2], 0 );
1432         glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
1433
1434         extern void Renderer_ResetStats();
1435         Renderer_ResetStats();
1436         extern void Cull_ResetStats();
1437         Cull_ResetStats();
1438
1439         glMatrixMode( GL_PROJECTION );
1440         glLoadMatrixf( reinterpret_cast<const float*>( &m_Camera.projection ) );
1441
1442         glMatrixMode( GL_MODELVIEW );
1443         glLoadMatrixf( reinterpret_cast<const float*>( &m_Camera.modelview ) );
1444
1445
1446         // one directional light source directly behind the viewer
1447         {
1448                 GLfloat inverse_cam_dir[4], ambient[4], diffuse[4]; //, material[4];
1449
1450                 ambient[0] = ambient[1] = ambient[2] = 0.4f;
1451                 ambient[3] = 1.0f;
1452                 diffuse[0] = diffuse[1] = diffuse[2] = 0.4f;
1453                 diffuse[3] = 1.0f;
1454                 //material[0] = material[1] = material[2] = 0.8f;
1455                 //material[3] = 1.0f;
1456
1457                 inverse_cam_dir[0] = m_Camera.vpn[0];
1458                 inverse_cam_dir[1] = m_Camera.vpn[1];
1459                 inverse_cam_dir[2] = m_Camera.vpn[2];
1460                 inverse_cam_dir[3] = 0;
1461
1462                 glLightfv( GL_LIGHT0, GL_POSITION, inverse_cam_dir );
1463
1464                 glLightfv( GL_LIGHT0, GL_AMBIENT, ambient );
1465                 glLightfv( GL_LIGHT0, GL_DIFFUSE, diffuse );
1466
1467                 glEnable( GL_LIGHT0 );
1468         }
1469
1470
1471         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;
1472         switch ( m_Camera.draw_mode )
1473         {
1474         case cd_wire:
1475                 break;
1476         case cd_solid:
1477                 globalstate |= RENDER_FILL
1478                                            | RENDER_LIGHTING
1479                                            | RENDER_SMOOTH
1480                                            | RENDER_SCALED;
1481                 break;
1482         case cd_texture:
1483                 globalstate |= RENDER_FILL
1484                                            | RENDER_LIGHTING
1485                                            | RENDER_TEXTURE
1486                                            | RENDER_SMOOTH
1487                                            | RENDER_SCALED;
1488                 break;
1489         case cd_lighting:
1490                 globalstate |= RENDER_FILL
1491                                            | RENDER_LIGHTING
1492                                            | RENDER_TEXTURE
1493                                            | RENDER_SMOOTH
1494                                            | RENDER_SCALED
1495                                            | RENDER_BUMP
1496                                            | RENDER_PROGRAM
1497                                            | RENDER_SCREEN;
1498                 break;
1499         default:
1500                 globalstate = 0;
1501                 break;
1502         }
1503
1504         if ( !g_xywindow_globals.m_bNoStipple ) {
1505                 globalstate |= RENDER_LINESTIPPLE | RENDER_POLYGONSTIPPLE;
1506         }
1507
1508         {
1509                 CamRenderer renderer( globalstate, m_state_select2, m_state_select1, m_view.getViewer() );
1510
1511                 Scene_Render( renderer, m_view );
1512
1513                 renderer.render( m_Camera.modelview, m_Camera.projection );
1514         }
1515
1516         // prepare for 2d stuff
1517         glColor4f( 1, 1, 1, 1 );
1518         glDisable( GL_BLEND );
1519         glMatrixMode( GL_PROJECTION );
1520         glLoadIdentity();
1521         glOrtho( 0, (float)m_Camera.width, 0, (float)m_Camera.height, -100, 100 );
1522         glScalef( 1, -1, 1 );
1523         glTranslatef( 0, -(float)m_Camera.height, 0 );
1524         glMatrixMode( GL_MODELVIEW );
1525         glLoadIdentity();
1526
1527         if ( GlobalOpenGL().GL_1_3() ) {
1528                 glClientActiveTexture( GL_TEXTURE0 );
1529                 glActiveTexture( GL_TEXTURE0 );
1530         }
1531
1532         glDisableClientState( GL_TEXTURE_COORD_ARRAY );
1533         glDisableClientState( GL_NORMAL_ARRAY );
1534         glDisableClientState( GL_COLOR_ARRAY );
1535
1536         glDisable( GL_TEXTURE_2D );
1537         glDisable( GL_LIGHTING );
1538         glDisable( GL_COLOR_MATERIAL );
1539         glDisable( GL_DEPTH_TEST );
1540         glColor3f( 1.f, 1.f, 1.f );
1541         glLineWidth( 1 );
1542
1543         // draw the crosshair
1544         if ( m_bFreeMove ) {
1545                 glBegin( GL_LINES );
1546                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 6 );
1547                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f + 2 );
1548                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 6 );
1549                 glVertex2f( (float)m_Camera.width / 2.f, (float)m_Camera.height / 2.f - 2 );
1550                 glVertex2f( (float)m_Camera.width / 2.f + 6, (float)m_Camera.height / 2.f );
1551                 glVertex2f( (float)m_Camera.width / 2.f + 2, (float)m_Camera.height / 2.f );
1552                 glVertex2f( (float)m_Camera.width / 2.f - 6, (float)m_Camera.height / 2.f );
1553                 glVertex2f( (float)m_Camera.width / 2.f - 2, (float)m_Camera.height / 2.f );
1554                 glEnd();
1555         }
1556
1557         if ( g_camwindow_globals_private.m_showStats ) {
1558                 glRasterPos3f( 1.0f, static_cast<float>( m_Camera.height ) - GlobalOpenGL().m_font->getPixelDescent(), 0.0f );
1559                 extern const char* Renderer_GetStats();
1560                 GlobalOpenGL().drawString( Renderer_GetStats() );
1561
1562                 glRasterPos3f( 1.0f, static_cast<float>( m_Camera.height ) - GlobalOpenGL().m_font->getPixelDescent() - GlobalOpenGL().m_font->getPixelHeight(), 0.0f );
1563                 extern const char* Cull_GetStats();
1564                 GlobalOpenGL().drawString( Cull_GetStats() );
1565         }
1566
1567         // bind back to the default texture so that we don't have problems
1568         // elsewhere using/modifying texture maps between contexts
1569         glBindTexture( GL_TEXTURE_2D, 0 );
1570 }
1571
1572 void CamWnd::draw(){
1573         m_drawing = true;
1574
1575         //globalOutputStream() << "draw...\n";
1576         if ( glwidget_make_current( m_gl_widget ) != FALSE ) {
1577                 if ( Map_Valid( g_map ) && ScreenUpdates_Enabled() ) {
1578                         GlobalOpenGL_debugAssertNoErrors();
1579                         Cam_Draw();
1580                         GlobalOpenGL_debugAssertNoErrors();
1581                         //qglFinish();
1582
1583                         m_XORRectangle.set( rectangle_t() );
1584                 }
1585
1586                 glwidget_swap_buffers( m_gl_widget );
1587         }
1588
1589         m_drawing = false;
1590 }
1591
1592 void CamWnd::BenchMark(){
1593         double dStart = Sys_DoubleTime();
1594         for ( int i = 0 ; i < 100 ; i++ )
1595         {
1596                 Vector3 angles;
1597                 angles[CAMERA_ROLL] = 0;
1598                 angles[CAMERA_PITCH] = 0;
1599                 angles[CAMERA_YAW] = static_cast<float>( i * ( 360.0 / 100.0 ) );
1600                 Camera_setAngles( *this, angles );
1601         }
1602         double dEnd = Sys_DoubleTime();
1603         globalOutputStream() << FloatFormat( dEnd - dStart, 5, 2 ) << " seconds\n";
1604 }
1605
1606
1607 void fill_view_camera_menu( ui::Menu menu ){
1608         create_check_menu_item_with_mnemonic( menu, "Camera View", "ToggleCamera" );
1609 }
1610
1611 void GlobalCamera_ResetAngles(){
1612         CamWnd& camwnd = *g_camwnd;
1613         Vector3 angles;
1614         angles[CAMERA_ROLL] = angles[CAMERA_PITCH] = 0;
1615         angles[CAMERA_YAW] = static_cast<float>( 22.5 * floor( ( Camera_getAngles( camwnd )[CAMERA_YAW] + 11 ) / 22.5 ) );
1616         Camera_setAngles( camwnd, angles );
1617 }
1618
1619 void Camera_ChangeFloorUp(){
1620         CamWnd& camwnd = *g_camwnd;
1621         camwnd.Cam_ChangeFloor( true );
1622 }
1623
1624 void Camera_ChangeFloorDown(){
1625         CamWnd& camwnd = *g_camwnd;
1626         camwnd.Cam_ChangeFloor( false );
1627 }
1628
1629 void Camera_CubeIn(){
1630         CamWnd& camwnd = *g_camwnd;
1631         g_camwindow_globals.m_nCubicScale--;
1632         if ( g_camwindow_globals.m_nCubicScale < 1 ) {
1633                 g_camwindow_globals.m_nCubicScale = 1;
1634         }
1635         Camera_updateProjection( camwnd.getCamera() );
1636         CamWnd_Update( camwnd );
1637         g_pParentWnd->SetGridStatus();
1638 }
1639
1640 void Camera_CubeOut(){
1641         CamWnd& camwnd = *g_camwnd;
1642         g_camwindow_globals.m_nCubicScale++;
1643         if ( g_camwindow_globals.m_nCubicScale > 23 ) {
1644                 g_camwindow_globals.m_nCubicScale = 23;
1645         }
1646         Camera_updateProjection( camwnd.getCamera() );
1647         CamWnd_Update( camwnd );
1648         g_pParentWnd->SetGridStatus();
1649 }
1650
1651 bool Camera_GetFarClip(){
1652         return g_camwindow_globals_private.m_bCubicClipping;
1653 }
1654
1655 BoolExportCaller g_getfarclip_caller( g_camwindow_globals_private.m_bCubicClipping );
1656 ToggleItem g_getfarclip_item( g_getfarclip_caller );
1657
1658 void Camera_SetFarClip( bool value ){
1659         CamWnd& camwnd = *g_camwnd;
1660         g_camwindow_globals_private.m_bCubicClipping = value;
1661         g_getfarclip_item.update();
1662         Camera_updateProjection( camwnd.getCamera() );
1663         CamWnd_Update( camwnd );
1664 }
1665
1666 void Camera_ToggleFarClip(){
1667         Camera_SetFarClip( !Camera_GetFarClip() );
1668 }
1669
1670
1671 void CamWnd_constructToolbar( ui::Toolbar toolbar ){
1672         toolbar_append_toggle_button( toolbar, "Cubic clip the camera view (\\)", "view_cubicclipping.png", "ToggleCubicClip" );
1673 }
1674
1675 void CamWnd_registerShortcuts(){
1676         toggle_add_accelerator( "ToggleCubicClip" );
1677
1678         if ( g_pGameDescription->mGameType == "doom3" ) {
1679                 command_connect_accelerator( "TogglePreview" );
1680         }
1681
1682         command_connect_accelerator( "CameraSpeedInc" );
1683         command_connect_accelerator( "CameraSpeedDec" );
1684 }
1685
1686
1687 void GlobalCamera_Benchmark(){
1688         CamWnd& camwnd = *g_camwnd;
1689         camwnd.BenchMark();
1690 }
1691
1692 void GlobalCamera_Update(){
1693         CamWnd& camwnd = *g_camwnd;
1694         CamWnd_Update( camwnd );
1695 }
1696
1697 camera_draw_mode CamWnd_GetMode(){
1698         return camera_t::draw_mode;
1699 }
1700 void CamWnd_SetMode( camera_draw_mode mode ){
1701         ShaderCache_setBumpEnabled( mode == cd_lighting );
1702         camera_t::draw_mode = mode;
1703         if ( g_camwnd != 0 ) {
1704                 CamWnd_Update( *g_camwnd );
1705         }
1706 }
1707
1708 void CamWnd_TogglePreview( void ){
1709         // gametype must be doom3 for this function to work
1710         // if the gametype is not doom3 something is wrong with the
1711         // global command list or somebody else calls this function.
1712         ASSERT_MESSAGE( g_pGameDescription->mGameType == "doom3", "CamWnd_TogglePreview called although mGameType is not doom3 compatible" );
1713
1714         // switch between textured and lighting mode
1715         CamWnd_SetMode( ( CamWnd_GetMode() == cd_lighting ) ? cd_texture : cd_lighting );
1716 }
1717
1718
1719 CameraModel* g_camera_model = 0;
1720
1721 void CamWnd_LookThroughCamera( CamWnd& camwnd ){
1722         if ( g_camera_model != 0 ) {
1723                 CamWnd_Add_Handlers_Move( camwnd );
1724                 g_camera_model->setCameraView( 0, Callback() );
1725                 g_camera_model = 0;
1726                 Camera_updateModelview( camwnd.getCamera() );
1727                 Camera_updateProjection( camwnd.getCamera() );
1728                 CamWnd_Update( camwnd );
1729         }
1730 }
1731
1732 inline CameraModel* Instance_getCameraModel( scene::Instance& instance ){
1733         return InstanceTypeCast<CameraModel>::cast( instance );
1734 }
1735
1736 void CamWnd_LookThroughSelected( CamWnd& camwnd ){
1737         if ( g_camera_model != 0 ) {
1738                 CamWnd_LookThroughCamera( camwnd );
1739         }
1740
1741         if ( GlobalSelectionSystem().countSelected() != 0 ) {
1742                 scene::Instance& instance = GlobalSelectionSystem().ultimateSelected();
1743                 CameraModel* cameraModel = Instance_getCameraModel( instance );
1744                 if ( cameraModel != 0 ) {
1745                         CamWnd_Remove_Handlers_Move( camwnd );
1746                         g_camera_model = cameraModel;
1747                         g_camera_model->setCameraView( &camwnd.getCameraView(), ReferenceCaller<CamWnd, CamWnd_LookThroughCamera>( camwnd ) );
1748                 }
1749         }
1750 }
1751
1752 void GlobalCamera_LookThroughSelected(){
1753         CamWnd_LookThroughSelected( *g_camwnd );
1754 }
1755
1756 void GlobalCamera_LookThroughCamera(){
1757         CamWnd_LookThroughCamera( *g_camwnd );
1758 }
1759
1760
1761 void RenderModeImport( int value ){
1762         switch ( value )
1763         {
1764         case 0:
1765                 CamWnd_SetMode( cd_wire );
1766                 break;
1767         case 1:
1768                 CamWnd_SetMode( cd_solid );
1769                 break;
1770         case 2:
1771                 CamWnd_SetMode( cd_texture );
1772                 break;
1773         case 3:
1774                 CamWnd_SetMode( cd_lighting );
1775                 break;
1776         default:
1777                 CamWnd_SetMode( cd_texture );
1778         }
1779 }
1780 typedef FreeCaller1<int, RenderModeImport> RenderModeImportCaller;
1781
1782 void RenderModeExport( const IntImportCallback& importer ){
1783         switch ( CamWnd_GetMode() )
1784         {
1785         case cd_wire:
1786                 importer( 0 );
1787                 break;
1788         case cd_solid:
1789                 importer( 1 );
1790                 break;
1791         case cd_texture:
1792                 importer( 2 );
1793                 break;
1794         case cd_lighting:
1795                 importer( 3 );
1796                 break;
1797         }
1798 }
1799 typedef FreeCaller1<const IntImportCallback&, RenderModeExport> RenderModeExportCaller;
1800
1801 void Camera_constructPreferences( PreferencesPage& page ){
1802         page.appendSlider( "Movement Speed", g_camwindow_globals_private.m_nMoveSpeed, TRUE, 0, 0, 100, MIN_CAM_SPEED, MAX_CAM_SPEED, 1, 10 );
1803         page.appendCheckBox( "", "Link strafe speed to movement speed", g_camwindow_globals_private.m_bCamLinkSpeed );
1804         page.appendSlider( "Rotation Speed", g_camwindow_globals_private.m_nAngleSpeed, TRUE, 0, 0, 3, 1, 180, 1, 10 );
1805         page.appendCheckBox( "", "Invert mouse vertical axis", g_camwindow_globals_private.m_bCamInverseMouse );
1806         page.appendCheckBox(
1807                 "", "Discrete movement",
1808                 FreeCaller1<bool, CamWnd_Move_Discrete_Import>(),
1809                 BoolExportCaller( g_camwindow_globals_private.m_bCamDiscrete )
1810                 );
1811         page.appendCheckBox(
1812                 "", "Enable far-clip plane",
1813                 FreeCaller1<bool, Camera_SetFarClip>(),
1814                 BoolExportCaller( g_camwindow_globals_private.m_bCubicClipping )
1815                 );
1816
1817         if ( g_pGameDescription->mGameType == "doom3" ) {
1818                 const char* render_mode[] = { "Wireframe", "Flatshade", "Textured", "Lighting" };
1819
1820                 page.appendCombo(
1821                         "Render Mode",
1822                         STRING_ARRAY_RANGE( render_mode ),
1823                         IntImportCallback( RenderModeImportCaller() ),
1824                         IntExportCallback( RenderModeExportCaller() )
1825                         );
1826         }
1827         else
1828         {
1829                 const char* render_mode[] = { "Wireframe", "Flatshade", "Textured" };
1830
1831                 page.appendCombo(
1832                         "Render Mode",
1833                         STRING_ARRAY_RANGE( render_mode ),
1834                         IntImportCallback( RenderModeImportCaller() ),
1835                         IntExportCallback( RenderModeExportCaller() )
1836                         );
1837         }
1838
1839         const char* strafe_mode[] = { "Both", "Forward", "Up" };
1840
1841         page.appendCombo(
1842                 "Strafe Mode",
1843                 g_camwindow_globals_private.m_nStrafeMode,
1844                 STRING_ARRAY_RANGE( strafe_mode )
1845                 );
1846 }
1847 void Camera_constructPage( PreferenceGroup& group ){
1848         PreferencesPage page( group.createPage( "Camera", "Camera View Preferences" ) );
1849         Camera_constructPreferences( page );
1850 }
1851 void Camera_registerPreferencesPage(){
1852         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Camera_constructPage>() );
1853 }
1854
1855 #include "preferencesystem.h"
1856 #include "stringio.h"
1857 #include "dialog.h"
1858
1859 typedef FreeCaller1<bool, CamWnd_Move_Discrete_Import> CamWndMoveDiscreteImportCaller;
1860
1861 void CameraSpeed_increase(){
1862         if ( g_camwindow_globals_private.m_nMoveSpeed <= ( MAX_CAM_SPEED - CAM_SPEED_STEP - 10 ) ) {
1863                 g_camwindow_globals_private.m_nMoveSpeed += CAM_SPEED_STEP;
1864         }
1865         else {
1866                 g_camwindow_globals_private.m_nMoveSpeed = MAX_CAM_SPEED - 10;
1867         }
1868 }
1869
1870 void CameraSpeed_decrease(){
1871         if ( g_camwindow_globals_private.m_nMoveSpeed >= ( MIN_CAM_SPEED + CAM_SPEED_STEP ) ) {
1872                 g_camwindow_globals_private.m_nMoveSpeed -= CAM_SPEED_STEP;
1873         }
1874         else {
1875                 g_camwindow_globals_private.m_nMoveSpeed = MIN_CAM_SPEED;
1876         }
1877 }
1878
1879 /// \brief Initialisation for things that have the same lifespan as this module.
1880 void CamWnd_Construct(){
1881         GlobalCommands_insert( "CenterView", FreeCaller<GlobalCamera_ResetAngles>(), Accelerator( GDK_KEY_End ) );
1882
1883         GlobalToggles_insert( "ToggleCubicClip", FreeCaller<Camera_ToggleFarClip>(), ToggleItem::AddCallbackCaller( g_getfarclip_item ), Accelerator( '\\', (GdkModifierType)GDK_CONTROL_MASK ) );
1884         GlobalCommands_insert( "CubicClipZoomIn", FreeCaller<Camera_CubeIn>(), Accelerator( '[', (GdkModifierType)GDK_CONTROL_MASK ) );
1885         GlobalCommands_insert( "CubicClipZoomOut", FreeCaller<Camera_CubeOut>(), Accelerator( ']', (GdkModifierType)GDK_CONTROL_MASK ) );
1886
1887         GlobalCommands_insert( "UpFloor", FreeCaller<Camera_ChangeFloorUp>(), Accelerator( GDK_KEY_Prior ) );
1888         GlobalCommands_insert( "DownFloor", FreeCaller<Camera_ChangeFloorDown>(), Accelerator( GDK_KEY_Next ) );
1889
1890         GlobalToggles_insert( "ToggleCamera", ToggleShown::ToggleCaller( g_camera_shown ), ToggleItem::AddCallbackCaller( g_camera_shown.m_item ), Accelerator( 'C', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
1891         GlobalCommands_insert( "LookThroughSelected", FreeCaller<GlobalCamera_LookThroughSelected>() );
1892         GlobalCommands_insert( "LookThroughCamera", FreeCaller<GlobalCamera_LookThroughCamera>() );
1893
1894         if ( g_pGameDescription->mGameType == "doom3" ) {
1895                 GlobalCommands_insert( "TogglePreview", FreeCaller<CamWnd_TogglePreview>(), Accelerator( GDK_KEY_F3 ) );
1896         }
1897
1898         GlobalCommands_insert( "CameraSpeedInc", FreeCaller<CameraSpeed_increase>(), Accelerator( GDK_KEY_KP_Add, (GdkModifierType)GDK_SHIFT_MASK ) );
1899         GlobalCommands_insert( "CameraSpeedDec", FreeCaller<CameraSpeed_decrease>(), Accelerator( GDK_KEY_KP_Subtract, (GdkModifierType)GDK_SHIFT_MASK ) );
1900
1901         GlobalShortcuts_insert( "CameraForward", Accelerator( GDK_KEY_Up ) );
1902         GlobalShortcuts_insert( "CameraBack", Accelerator( GDK_KEY_Down ) );
1903         GlobalShortcuts_insert( "CameraLeft", Accelerator( GDK_KEY_Left ) );
1904         GlobalShortcuts_insert( "CameraRight", Accelerator( GDK_KEY_Right ) );
1905         GlobalShortcuts_insert( "CameraStrafeRight", Accelerator( GDK_KEY_period ) );
1906         GlobalShortcuts_insert( "CameraStrafeLeft", Accelerator( GDK_KEY_comma ) );
1907
1908         GlobalShortcuts_insert( "CameraUp", Accelerator( 'D' ) );
1909         GlobalShortcuts_insert( "CameraDown", Accelerator( 'C' ) );
1910         GlobalShortcuts_insert( "CameraAngleUp", Accelerator( 'A' ) );
1911         GlobalShortcuts_insert( "CameraAngleDown", Accelerator( 'Z' ) );
1912
1913         GlobalShortcuts_insert( "CameraFreeMoveForward", Accelerator( GDK_KEY_Up ) );
1914         GlobalShortcuts_insert( "CameraFreeMoveBack", Accelerator( GDK_KEY_Down ) );
1915         GlobalShortcuts_insert( "CameraFreeMoveLeft", Accelerator( GDK_KEY_Left ) );
1916         GlobalShortcuts_insert( "CameraFreeMoveRight", Accelerator( GDK_KEY_Right ) );
1917
1918         GlobalToggles_insert( "ShowStats", ShowStatsToggleCaller(), ToggleItem::AddCallbackCaller( g_show_stats ) );
1919
1920         GlobalPreferenceSystem().registerPreference( "ShowStats", BoolImportStringCaller( g_camwindow_globals_private.m_showStats ), BoolExportStringCaller( g_camwindow_globals_private.m_showStats ) );
1921         GlobalPreferenceSystem().registerPreference( "MoveSpeed", IntImportStringCaller( g_camwindow_globals_private.m_nMoveSpeed ), IntExportStringCaller( g_camwindow_globals_private.m_nMoveSpeed ) );
1922         GlobalPreferenceSystem().registerPreference( "CamLinkSpeed", BoolImportStringCaller( g_camwindow_globals_private.m_bCamLinkSpeed ), BoolExportStringCaller( g_camwindow_globals_private.m_bCamLinkSpeed ) );
1923         GlobalPreferenceSystem().registerPreference( "AngleSpeed", IntImportStringCaller( g_camwindow_globals_private.m_nAngleSpeed ), IntExportStringCaller( g_camwindow_globals_private.m_nAngleSpeed ) );
1924         GlobalPreferenceSystem().registerPreference( "CamInverseMouse", BoolImportStringCaller( g_camwindow_globals_private.m_bCamInverseMouse ), BoolExportStringCaller( g_camwindow_globals_private.m_bCamInverseMouse ) );
1925         GlobalPreferenceSystem().registerPreference( "CamDiscrete", makeBoolStringImportCallback( CamWndMoveDiscreteImportCaller() ), BoolExportStringCaller( g_camwindow_globals_private.m_bCamDiscrete ) );
1926         GlobalPreferenceSystem().registerPreference( "CubicClipping", BoolImportStringCaller( g_camwindow_globals_private.m_bCubicClipping ), BoolExportStringCaller( g_camwindow_globals_private.m_bCubicClipping ) );
1927         GlobalPreferenceSystem().registerPreference( "CubicScale", IntImportStringCaller( g_camwindow_globals.m_nCubicScale ), IntExportStringCaller( g_camwindow_globals.m_nCubicScale ) );
1928         GlobalPreferenceSystem().registerPreference( "SI_Colors4", Vector3ImportStringCaller( g_camwindow_globals.color_cameraback ), Vector3ExportStringCaller( g_camwindow_globals.color_cameraback ) );
1929         GlobalPreferenceSystem().registerPreference( "SI_Colors12", Vector3ImportStringCaller( g_camwindow_globals.color_selbrushes3d ), Vector3ExportStringCaller( g_camwindow_globals.color_selbrushes3d ) );
1930         GlobalPreferenceSystem().registerPreference( "CameraRenderMode", makeIntStringImportCallback( RenderModeImportCaller() ), makeIntStringExportCallback( RenderModeExportCaller() ) );
1931         GlobalPreferenceSystem().registerPreference( "StrafeMode", IntImportStringCaller( g_camwindow_globals_private.m_nStrafeMode ), IntExportStringCaller( g_camwindow_globals_private.m_nStrafeMode ) );
1932
1933         CamWnd_constructStatic();
1934
1935         Camera_registerPreferencesPage();
1936 }
1937 void CamWnd_Destroy(){
1938         CamWnd_destroyStatic();
1939 }