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