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