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