]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/xywindow.cpp
Q3map2:
[xonotic/netradiant.git] / radiant / xywindow.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 // XY Window
24 //
25 // Leonardo Zide (leo@lokigames.com)
26 //
27
28 #include "xywindow.h"
29
30 #include "debugging/debugging.h"
31
32 #include "ientity.h"
33 #include "igl.h"
34 #include "ibrush.h"
35 #include "iundo.h"
36 #include "iimage.h"
37 #include "ifilesystem.h"
38 #include "os/path.h"
39 #include "image.h"
40 #include "gtkutil/messagebox.h"
41
42 #include <gtk/gtklabel.h>
43 #include <gtk/gtkmenuitem.h>
44
45 #include "generic/callback.h"
46 #include "string/string.h"
47 #include "stream/stringstream.h"
48
49 #include "scenelib.h"
50 #include "eclasslib.h"
51 #include "renderer.h"
52 #include "moduleobserver.h"
53
54 #include "gtkutil/menu.h"
55 #include "gtkutil/container.h"
56 #include "gtkutil/widget.h"
57 #include "gtkutil/glwidget.h"
58 #include "gtkutil/filechooser.h"
59 #include "gtkmisc.h"
60 #include "select.h"
61 #include "csg.h"
62 #include "brushmanip.h"
63 #include "selection.h"
64 #include "entity.h"
65 #include "camwindow.h"
66 #include "texwindow.h"
67 #include "mainframe.h"
68 #include "preferences.h"
69 #include "commands.h"
70 #include "feedback.h"
71 #include "grid.h"
72 #include "windowobservers.h"
73
74 void LoadTextureRGBA( qtexture_t* q, unsigned char* pPixels, int nWidth, int nHeight );
75
76 // d1223m
77 extern bool g_brush_always_caulk;
78
79 //!\todo Rewrite.
80 class ClipPoint
81 {
82 public:
83 Vector3 m_ptClip;        // the 3d point
84 bool m_bSet;
85
86 ClipPoint(){
87         Reset();
88 };
89 void Reset(){
90         m_ptClip[0] = m_ptClip[1] = m_ptClip[2] = 0.0;
91         m_bSet = false;
92 }
93 bool Set(){
94         return m_bSet;
95 }
96 void Set( bool b ){
97         m_bSet = b;
98 }
99 operator Vector3&()
100 {
101         return m_ptClip;
102 };
103
104 /*! Draw clip/path point with rasterized number label */
105 void Draw( int num, float scale );
106 /*! Draw clip/path point with rasterized string label */
107 void Draw( const char *label, float scale );
108 };
109
110 VIEWTYPE g_clip_viewtype;
111 bool g_bSwitch = true;
112 bool g_clip_useCaulk = false;
113 bool g_quick_clipper = false;
114 ClipPoint g_Clip1;
115 ClipPoint g_Clip2;
116 ClipPoint g_Clip3;
117 ClipPoint* g_pMovingClip = 0;
118
119 /* Drawing clip points */
120 void ClipPoint::Draw( int num, float scale ){
121         StringOutputStream label( 4 );
122         label << num;
123         Draw( label.c_str(), scale );
124 }
125
126 void ClipPoint::Draw( const char *label, float scale ){
127         // draw point
128         glPointSize( 4 );
129         glColor3fv( vector3_to_array( g_xywindow_globals.color_clipper ) );
130         glBegin( GL_POINTS );
131         glVertex3fv( vector3_to_array( m_ptClip ) );
132         glEnd();
133         glPointSize( 1 );
134
135         float offset = 2.0f / scale;
136
137         // draw label
138         glRasterPos3f( m_ptClip[0] + offset, m_ptClip[1] + offset, m_ptClip[2] + offset );
139         glCallLists( GLsizei( strlen( label ) ), GL_UNSIGNED_BYTE, label );
140 }
141
142 float fDiff( float f1, float f2 ){
143         if ( f1 > f2 ) {
144                 return f1 - f2;
145         }
146         else{
147                 return f2 - f1;
148         }
149 }
150
151 inline double ClipPoint_Intersect( const ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale ){
152         int nDim1 = ( viewtype == YZ ) ? 1 : 0;
153         int nDim2 = ( viewtype == XY ) ? 1 : 2;
154         double screenDistanceSquared( vector2_length_squared( Vector2( fDiff( clip.m_ptClip[nDim1], point[nDim1] ) * scale, fDiff( clip.m_ptClip[nDim2], point[nDim2] )  * scale ) ) );
155         if ( screenDistanceSquared < 8 * 8 ) {
156                 return screenDistanceSquared;
157         }
158         return FLT_MAX;
159 }
160
161 inline void ClipPoint_testSelect( ClipPoint& clip, const Vector3& point, VIEWTYPE viewtype, float scale, double& bestDistance, ClipPoint*& bestClip ){
162         if ( clip.Set() ) {
163                 double distance = ClipPoint_Intersect( clip, point, viewtype, scale );
164                 if ( distance < bestDistance ) {
165                         bestDistance = distance;
166                         bestClip = &clip;
167                 }
168         }
169 }
170
171 inline ClipPoint* GlobalClipPoints_Find( const Vector3& point, VIEWTYPE viewtype, float scale ){
172         double bestDistance = FLT_MAX;
173         ClipPoint* bestClip = 0;
174         ClipPoint_testSelect( g_Clip1, point, viewtype, scale, bestDistance, bestClip );
175         ClipPoint_testSelect( g_Clip2, point, viewtype, scale, bestDistance, bestClip );
176         ClipPoint_testSelect( g_Clip3, point, viewtype, scale, bestDistance, bestClip );
177         return bestClip;
178 }
179
180 inline void GlobalClipPoints_Draw( float scale ){
181         // Draw clip points
182         if ( g_Clip1.Set() ) {
183                 g_Clip1.Draw( 1, scale );
184         }
185         if ( g_Clip2.Set() ) {
186                 g_Clip2.Draw( 2, scale );
187         }
188         if ( g_Clip3.Set() ) {
189                 g_Clip3.Draw( 3, scale );
190         }
191 }
192
193 inline bool GlobalClipPoints_valid(){
194         return g_Clip1.Set() && g_Clip2.Set();
195 }
196
197 void PlanePointsFromClipPoints( Vector3 planepts[3], const AABB& bounds, int viewtype ){
198         ASSERT_MESSAGE( GlobalClipPoints_valid(), "clipper points not initialised" );
199         planepts[0] = g_Clip1.m_ptClip;
200         planepts[1] = g_Clip2.m_ptClip;
201         planepts[2] = g_Clip3.m_ptClip;
202         Vector3 maxs( vector3_added( bounds.origin, bounds.extents ) );
203         Vector3 mins( vector3_subtracted( bounds.origin, bounds.extents ) );
204         if ( !g_Clip3.Set() ) {
205                 int n = ( viewtype == XY ) ? 2 : ( viewtype == YZ ) ? 0 : 1;
206                 int x = ( n == 0 ) ? 1 : 0;
207                 int y = ( n == 2 ) ? 1 : 2;
208
209                 if ( n == 1 ) { // on viewtype XZ, flip clip points
210                         planepts[0][n] = maxs[n];
211                         planepts[1][n] = maxs[n];
212                         planepts[2][x] = g_Clip1.m_ptClip[x];
213                         planepts[2][y] = g_Clip1.m_ptClip[y];
214                         planepts[2][n] = mins[n];
215                 }
216                 else
217                 {
218                         planepts[0][n] = mins[n];
219                         planepts[1][n] = mins[n];
220                         planepts[2][x] = g_Clip1.m_ptClip[x];
221                         planepts[2][y] = g_Clip1.m_ptClip[y];
222                         planepts[2][n] = maxs[n];
223                 }
224         }
225 }
226
227 void Clip_Update(){
228         Vector3 planepts[3];
229         if ( !GlobalClipPoints_valid() ) {
230                 planepts[0] = Vector3( 0, 0, 0 );
231                 planepts[1] = Vector3( 0, 0, 0 );
232                 planepts[2] = Vector3( 0, 0, 0 );
233                 Scene_BrushSetClipPlane( GlobalSceneGraph(), Plane3( 0, 0, 0, 0 ) );
234         }
235         else
236         {
237                 AABB bounds( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
238                 PlanePointsFromClipPoints( planepts, bounds, g_clip_viewtype );
239                 if ( g_bSwitch ) {
240                         std::swap( planepts[0], planepts[1] );
241                 }
242                 Scene_BrushSetClipPlane( GlobalSceneGraph(), plane3_for_points( planepts[0], planepts[1], planepts[2] ) );
243         }
244         ClipperChangeNotify();
245 }
246
247 const char* Clip_getShader(){
248         return g_clip_useCaulk ? "textures/common/caulk" : TextureBrowser_GetSelectedShader( GlobalTextureBrowser() );
249 }
250
251 void Clip(){
252         if ( ClipMode() && GlobalClipPoints_valid() ) {
253                 Vector3 planepts[3];
254                 AABB bounds( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
255                 PlanePointsFromClipPoints( planepts, bounds, g_clip_viewtype );
256                 Scene_BrushSplitByPlane( GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), ( !g_bSwitch ) ? eFront : eBack );
257                 g_Clip1.Reset();
258                 g_Clip2.Reset();
259                 g_Clip3.Reset();
260                 Clip_Update();
261                 ClipperChangeNotify();
262                 if( g_quick_clipper ){
263                         g_quick_clipper = false;
264                         ClipperMode();
265                 }
266         }
267 }
268
269 void SplitClip(){
270         if ( ClipMode() && GlobalClipPoints_valid() ) {
271                 Vector3 planepts[3];
272                 AABB bounds( Vector3( 0, 0, 0 ), Vector3( 64, 64, 64 ) );
273                 PlanePointsFromClipPoints( planepts, bounds, g_clip_viewtype );
274                 Scene_BrushSplitByPlane( GlobalSceneGraph(), planepts[0], planepts[1], planepts[2], Clip_getShader(), eFrontAndBack );
275                 g_Clip1.Reset();
276                 g_Clip2.Reset();
277                 g_Clip3.Reset();
278                 Clip_Update();
279                 ClipperChangeNotify();
280                 if( g_quick_clipper ){
281                         g_quick_clipper = false;
282                         ClipperMode();
283                 }
284         }
285 }
286
287 void FlipClip(){
288         g_bSwitch = !g_bSwitch;
289         Clip_Update();
290         ClipperChangeNotify();
291 }
292
293 void OnClipMode( bool enabled ){
294         g_Clip1.Reset();
295         g_Clip2.Reset();
296         g_Clip3.Reset();
297
298         if ( !enabled && g_pMovingClip ) {
299                 g_pMovingClip = 0;
300         }
301
302         Clip_Update();
303         ClipperChangeNotify();
304 }
305
306 bool ClipMode(){
307         return GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip;
308 }
309
310 void NewClipPoint( const Vector3& point ){
311         if ( g_Clip1.Set() == false ) {
312                 g_Clip1.m_ptClip = point;
313                 g_Clip1.Set( true );
314         }
315         else if ( g_Clip2.Set() == false ) {
316                 g_Clip2.m_ptClip = point;
317                 g_Clip2.Set( true );
318         }
319         else if ( g_Clip3.Set() == false ) {
320                 g_Clip3.m_ptClip = point;
321                 g_Clip3.Set( true );
322         }
323         else
324         {
325                 g_Clip1.Reset();
326                 g_Clip2.Reset();
327                 g_Clip3.Reset();
328                 g_Clip1.m_ptClip = point;
329                 g_Clip1.Set( true );
330         }
331
332         Clip_Update();
333         ClipperChangeNotify();
334 }
335
336
337
338 struct xywindow_globals_private_t
339 {
340         bool d_showgrid;
341
342         // these are in the View > Show menu with Show coordinates
343         bool show_names;
344         bool show_coordinates;
345         bool show_angles;
346         bool show_outline;
347         bool show_axis;
348
349         bool d_show_work;
350
351         bool show_blocks;
352         int blockSize;
353
354         bool m_bCamXYUpdate;
355         bool m_bChaseMouse;
356         bool m_bSizePaint;
357
358         xywindow_globals_private_t() :
359                 d_showgrid( true ),
360
361                 show_names( false ),
362                 show_coordinates( true ),
363                 show_angles( true ),
364                 show_outline( false ),
365                 show_axis( true ),
366
367                 d_show_work( false ),
368
369                 show_blocks( false ),
370
371                 m_bCamXYUpdate( true ),
372                 m_bChaseMouse( true ),
373                 m_bSizePaint( true ){
374         }
375
376 };
377
378 xywindow_globals_t g_xywindow_globals;
379 xywindow_globals_private_t g_xywindow_globals_private;
380
381 const unsigned int RAD_NONE =    0x00;
382 const unsigned int RAD_SHIFT =   0x01;
383 const unsigned int RAD_ALT =     0x02;
384 const unsigned int RAD_CONTROL = 0x04;
385 const unsigned int RAD_PRESS   = 0x08;
386 const unsigned int RAD_LBUTTON = 0x10;
387 const unsigned int RAD_MBUTTON = 0x20;
388 const unsigned int RAD_RBUTTON = 0x40;
389
390 inline ButtonIdentifier button_for_flags( unsigned int flags ){
391         if ( flags & RAD_LBUTTON ) {
392                 return c_buttonLeft;
393         }
394         if ( flags & RAD_RBUTTON ) {
395                 return c_buttonRight;
396         }
397         if ( flags & RAD_MBUTTON ) {
398                 return c_buttonMiddle;
399         }
400         return c_buttonInvalid;
401 }
402
403 inline ModifierFlags modifiers_for_flags( unsigned int flags ){
404         ModifierFlags modifiers = c_modifierNone;
405         if ( flags & RAD_SHIFT ) {
406                 modifiers |= c_modifierShift;
407         }
408         if ( flags & RAD_CONTROL ) {
409                 modifiers |= c_modifierControl;
410         }
411         if ( flags & RAD_ALT ) {
412                 modifiers |= c_modifierAlt;
413         }
414         return modifiers;
415 }
416
417 inline unsigned int buttons_for_button_and_modifiers( ButtonIdentifier button, ModifierFlags flags ){
418         unsigned int buttons = 0;
419
420         switch ( button.get() )
421         {
422         case ButtonEnumeration::LEFT: buttons |= RAD_LBUTTON; break;
423         case ButtonEnumeration::MIDDLE: buttons |= RAD_MBUTTON; break;
424         case ButtonEnumeration::RIGHT: buttons |= RAD_RBUTTON; break;
425         }
426
427         if ( bitfield_enabled( flags, c_modifierControl ) ) {
428                 buttons |= RAD_CONTROL;
429         }
430
431         if ( bitfield_enabled( flags, c_modifierShift ) ) {
432                 buttons |= RAD_SHIFT;
433         }
434
435         if ( bitfield_enabled( flags, c_modifierAlt ) ) {
436                 buttons |= RAD_ALT;
437         }
438
439         return buttons;
440 }
441
442 inline unsigned int buttons_for_event_button( GdkEventButton* event ){
443         unsigned int flags = 0;
444
445         switch ( event->button )
446         {
447         case 1: flags |= RAD_LBUTTON; break;
448         case 2: flags |= RAD_MBUTTON; break;
449         case 3: flags |= RAD_RBUTTON; break;
450         }
451
452         if ( ( event->state & GDK_CONTROL_MASK ) != 0 ) {
453                 flags |= RAD_CONTROL;
454         }
455
456         if ( ( event->state & GDK_SHIFT_MASK ) != 0 ) {
457                 flags |= RAD_SHIFT;
458         }
459
460         if ( ( event->state & GDK_MOD1_MASK ) != 0 ) {
461                 flags |= RAD_ALT;
462         }
463
464         return flags;
465 }
466
467 inline unsigned int buttons_for_state( guint state ){
468         unsigned int flags = 0;
469
470         if ( ( state & GDK_BUTTON1_MASK ) != 0 ) {
471                 flags |= RAD_LBUTTON;
472         }
473
474         if ( ( state & GDK_BUTTON2_MASK ) != 0 ) {
475                 flags |= RAD_MBUTTON;
476         }
477
478         if ( ( state & GDK_BUTTON3_MASK ) != 0 ) {
479                 flags |= RAD_RBUTTON;
480         }
481
482         if ( ( state & GDK_CONTROL_MASK ) != 0 ) {
483                 flags |= RAD_CONTROL;
484         }
485
486         if ( ( state & GDK_SHIFT_MASK ) != 0 ) {
487                 flags |= RAD_SHIFT;
488         }
489
490         if ( ( state & GDK_MOD1_MASK ) != 0 ) {
491                 flags |= RAD_ALT;
492         }
493
494         return flags;
495 }
496
497
498 void XYWnd::SetScale( float f ){
499         m_fScale = f;
500         updateProjection();
501         updateModelview();
502         XYWnd_Update( *this );
503 }
504
505 void XYWnd::ZoomIn(){
506         float max_scale = 64;
507         float scale = Scale() * 5.0f / 4.0f;
508         if ( scale > max_scale ) {
509                 if ( Scale() != max_scale ) {
510                         SetScale( max_scale );
511                 }
512         }
513         else
514         {
515                 SetScale( scale );
516         }
517 }
518
519
520 // NOTE: the zoom out factor is 4/5, we could think about customizing it
521 //  we don't go below a zoom factor corresponding to 10% of the max world size
522 //  (this has to be computed against the window size)
523 void XYWnd::ZoomOut(){
524         float min_scale = MIN( Width(), Height() ) / ( 1.1f * ( g_MaxWorldCoord - g_MinWorldCoord ) );
525         float scale = Scale() * 4.0f / 5.0f;
526         if ( scale < min_scale ) {
527                 if ( Scale() != min_scale ) {
528                         SetScale( min_scale );
529                 }
530         }
531         else
532         {
533                 SetScale( scale );
534         }
535 }
536
537 void XYWnd::ZoomInWithMouse( int pointx, int pointy ){
538         float old_scale = Scale();
539         ZoomIn();
540         if ( g_xywindow_globals.m_bImprovedWheelZoom ) {
541                 float scale_diff = 1.0 / old_scale - 1.0 / Scale();
542                 int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
543                 int nDim2 = ( m_viewType == XY ) ? 1 : 2;
544                 Vector3 origin = GetOrigin();
545                 origin[nDim1] += scale_diff * (pointx - 0.5 * Width());
546                 origin[nDim2] -= scale_diff * (pointy - 0.5 * Height());
547                 SetOrigin( origin );
548         }
549 }
550
551 VIEWTYPE GlobalXYWnd_getCurrentViewType(){
552         ASSERT_NOTNULL( g_pParentWnd );
553         ASSERT_NOTNULL( g_pParentWnd->ActiveXY() );
554         return g_pParentWnd->ActiveXY()->GetViewType();
555 }
556
557 // =============================================================================
558 // variables
559
560 bool g_bCrossHairs = false;
561
562 GtkMenu* XYWnd::m_mnuDrop = 0;
563
564 // this is disabled, and broken
565 // http://zerowing.idsoftware.com/bugzilla/show_bug.cgi?id=394
566 #if 0
567 void WXY_Print(){
568         long width, height;
569         width = g_pParentWnd->ActiveXY()->Width();
570         height = g_pParentWnd->ActiveXY()->Height();
571         unsigned char* img;
572         const char* filename;
573
574         filename = file_dialog( GTK_WIDGET( MainFrame_getWindow() ), FALSE, "Save Image", 0, FILTER_BMP );
575         if ( !filename ) {
576                 return;
577         }
578
579         g_pParentWnd->ActiveXY()->MakeCurrent();
580         img = (unsigned char*)malloc( width * height * 3 );
581         glReadPixels( 0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,img );
582
583         FILE *fp;
584         fp = fopen( filename, "wb" );
585         if ( fp ) {
586                 unsigned short bits;
587                 unsigned long cmap, bfSize;
588
589                 bits = 24;
590                 cmap = 0;
591                 bfSize = 54 + width * height * 3;
592
593                 long byteswritten = 0;
594                 long pixoff = 54 + cmap * 4;
595                 short res = 0;
596                 char m1 = 'B', m2 = 'M';
597                 fwrite( &m1, 1, 1, fp );      byteswritten++; // B
598                 fwrite( &m2, 1, 1, fp );      byteswritten++; // M
599                 fwrite( &bfSize, 4, 1, fp );  byteswritten += 4; // bfSize
600                 fwrite( &res, 2, 1, fp );     byteswritten += 2; // bfReserved1
601                 fwrite( &res, 2, 1, fp );     byteswritten += 2; // bfReserved2
602                 fwrite( &pixoff, 4, 1, fp );  byteswritten += 4; // bfOffBits
603
604                 unsigned long biSize = 40, compress = 0, size = 0;
605                 long pixels = 0;
606                 unsigned short planes = 1;
607                 fwrite( &biSize, 4, 1, fp );  byteswritten += 4; // biSize
608                 fwrite( &width, 4, 1, fp );   byteswritten += 4; // biWidth
609                 fwrite( &height, 4, 1, fp );  byteswritten += 4; // biHeight
610                 fwrite( &planes, 2, 1, fp );  byteswritten += 2; // biPlanes
611                 fwrite( &bits, 2, 1, fp );    byteswritten += 2; // biBitCount
612                 fwrite( &compress, 4, 1, fp ); byteswritten += 4; // biCompression
613                 fwrite( &size, 4, 1, fp );    byteswritten += 4; // biSizeImage
614                 fwrite( &pixels, 4, 1, fp );  byteswritten += 4; // biXPelsPerMeter
615                 fwrite( &pixels, 4, 1, fp );  byteswritten += 4; // biYPelsPerMeter
616                 fwrite( &cmap, 4, 1, fp );    byteswritten += 4; // biClrUsed
617                 fwrite( &cmap, 4, 1, fp );    byteswritten += 4; // biClrImportant
618
619                 unsigned long widthDW = ( ( ( width * 24 ) + 31 ) / 32 * 4 );
620                 long row, row_size = width * 3;
621                 for ( row = 0; row < height; row++ )
622                 {
623                         unsigned char* buf = img + row * row_size;
624
625                         // write a row
626                         int col;
627                         for ( col = 0; col < row_size; col += 3 )
628                         {
629                                 putc( buf[col + 2], fp );
630                                 putc( buf[col + 1], fp );
631                                 putc( buf[col], fp );
632                         }
633                         byteswritten += row_size;
634
635                         unsigned long count;
636                         for ( count = row_size; count < widthDW; count++ )
637                         {
638                                 putc( 0, fp ); // dummy
639                                 byteswritten++;
640                         }
641                 }
642
643                 fclose( fp );
644         }
645
646         free( img );
647 }
648 #endif
649
650
651 #include "timer.h"
652
653 Timer g_chasemouse_timer;
654
655 void XYWnd::ChaseMouse(){
656         float multiplier = g_chasemouse_timer.elapsed_msec() / 10.0f;
657         Scroll( float_to_integer( multiplier * m_chasemouse_delta_x ), float_to_integer( multiplier * -m_chasemouse_delta_y ) );
658
659         //globalOutputStream() << "chasemouse: multiplier=" << multiplier << " x=" << m_chasemouse_delta_x << " y=" << m_chasemouse_delta_y << '\n';
660
661         XY_MouseMoved( m_chasemouse_current_x, m_chasemouse_current_y, getButtonState() );
662         g_chasemouse_timer.start();
663 }
664
665 gboolean xywnd_chasemouse( gpointer data ){
666         reinterpret_cast<XYWnd*>( data )->ChaseMouse();
667         return TRUE;
668 }
669
670 inline const int& min_int( const int& left, const int& right ){
671         return std::min( left, right );
672 }
673
674 bool XYWnd::chaseMouseMotion( int pointx, int pointy ){
675         m_chasemouse_delta_x = 0;
676         m_chasemouse_delta_y = 0;
677
678         if ( g_xywindow_globals_private.m_bChaseMouse && getButtonState() == RAD_LBUTTON ) {
679                 const int epsilon = 16;
680
681                 if ( pointx < epsilon ) {
682                         m_chasemouse_delta_x = std::max( pointx, 0 ) - epsilon;
683                 }
684                 else if ( ( pointx - m_nWidth ) > -epsilon ) {
685                         m_chasemouse_delta_x = min_int( ( pointx - m_nWidth ), 0 ) + epsilon;
686                 }
687
688                 if ( pointy < epsilon ) {
689                         m_chasemouse_delta_y = std::max( pointy, 0 ) - epsilon;
690                 }
691                 else if ( ( pointy - m_nHeight ) > -epsilon ) {
692                         m_chasemouse_delta_y = min_int( ( pointy - m_nHeight ), 0 ) + epsilon;
693                 }
694
695                 if ( m_chasemouse_delta_y != 0 || m_chasemouse_delta_x != 0 ) {
696                         //globalOutputStream() << "chasemouse motion: x=" << pointx << " y=" << pointy << "... ";
697                         m_chasemouse_current_x = pointx;
698                         m_chasemouse_current_y = pointy;
699                         if ( m_chasemouse_handler == 0 ) {
700                                 //globalOutputStream() << "chasemouse timer start... ";
701                                 g_chasemouse_timer.start();
702                                 m_chasemouse_handler = g_idle_add( xywnd_chasemouse, this );
703                         }
704                         return true;
705                 }
706                 else
707                 {
708                         if ( m_chasemouse_handler != 0 ) {
709                                 //globalOutputStream() << "chasemouse cancel\n";
710                                 g_source_remove( m_chasemouse_handler );
711                                 m_chasemouse_handler = 0;
712                         }
713                 }
714         }
715         else
716         {
717                 if ( m_chasemouse_handler != 0 ) {
718                         //globalOutputStream() << "chasemouse cancel\n";
719                         g_source_remove( m_chasemouse_handler );
720                         m_chasemouse_handler = 0;
721                 }
722         }
723         return false;
724 }
725
726 // =============================================================================
727 // XYWnd class
728 Shader* XYWnd::m_state_selected = 0;
729
730 void xy_update_xor_rectangle( XYWnd& self, rect_t area ){
731         if ( GTK_WIDGET_VISIBLE( self.GetWidget() ) ) {
732                 rectangle_t rect = rectangle_from_area( area.min, area.max, self.Width(), self.Height() );
733                 int nDim1 = ( self.GetViewType() == YZ ) ? 1 : 0;
734                 int nDim2 = ( self.GetViewType() == XY ) ? 1 : 2;
735                 rect.x /= self.Scale();
736                 rect.y /= self.Scale();
737                 rect.w /= self.Scale();
738                 rect.h /= self.Scale();
739                 rect.x += self.GetOrigin()[nDim1];
740                 rect.y += self.GetOrigin()[nDim2];
741                 self.m_XORRectangle.set( rect );
742         }
743 }
744
745 gboolean xywnd_button_press( GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd ){
746         if ( event->type == GDK_BUTTON_PRESS ) {
747                 g_pParentWnd->SetActiveXY( xywnd );
748
749                 xywnd->ButtonState_onMouseDown( buttons_for_event_button( event ) );
750
751                 xywnd->onMouseDown( WindowVector( event->x, event->y ), button_for_button( event->button ), modifiers_for_state( event->state ) );
752         }
753         return FALSE;
754 }
755
756 gboolean xywnd_button_release( GtkWidget* widget, GdkEventButton* event, XYWnd* xywnd ){
757         if ( event->type == GDK_BUTTON_RELEASE ) {
758                 xywnd->XY_MouseUp( static_cast<int>( event->x ), static_cast<int>( event->y ), buttons_for_event_button( event ) );
759
760                 xywnd->ButtonState_onMouseUp( buttons_for_event_button( event ) );
761         }
762         return FALSE;
763 }
764
765 gboolean xywnd_focus_in( GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd ){
766         if ( event->type == GDK_FOCUS_CHANGE ) {
767                 if ( event->in ) {
768                         g_pParentWnd->SetActiveXY( xywnd );
769                 }
770         }
771         return FALSE;
772 }
773
774 void xywnd_motion( gdouble x, gdouble y, guint state, void* data ){
775         if ( reinterpret_cast<XYWnd*>( data )->chaseMouseMotion( static_cast<int>( x ), static_cast<int>( y ) ) ) {
776                 return;
777         }
778         reinterpret_cast<XYWnd*>( data )->XY_MouseMoved( static_cast<int>( x ), static_cast<int>( y ), buttons_for_state( state ) );
779 }
780
781 gboolean xywnd_wheel_scroll( GtkWidget* widget, GdkEventScroll* event, XYWnd* xywnd ){
782         if ( event->direction == GDK_SCROLL_UP ) {
783                 xywnd->ZoomInWithMouse( (int)event->x, (int)event->y );
784         }
785         else if ( event->direction == GDK_SCROLL_DOWN ) {
786                 xywnd->ZoomOut();
787         }
788         return FALSE;
789 }
790
791 gboolean xywnd_size_allocate( GtkWidget* widget, GtkAllocation* allocation, XYWnd* xywnd ){
792         xywnd->m_nWidth = allocation->width;
793         xywnd->m_nHeight = allocation->height;
794         xywnd->updateProjection();
795         xywnd->m_window_observer->onSizeChanged( xywnd->Width(), xywnd->Height() );
796         return FALSE;
797 }
798
799 gboolean xywnd_expose( GtkWidget* widget, GdkEventExpose* event, XYWnd* xywnd ){
800         if ( glwidget_make_current( xywnd->GetWidget() ) != FALSE ) {
801                 if ( Map_Valid( g_map ) && ScreenUpdates_Enabled() ) {
802                         GlobalOpenGL_debugAssertNoErrors();
803                         xywnd->XY_Draw();
804                         GlobalOpenGL_debugAssertNoErrors();
805
806                         xywnd->m_XORRectangle.set( rectangle_t() );
807                 }
808                 glwidget_swap_buffers( xywnd->GetWidget() );
809         }
810         return FALSE;
811 }
812
813
814 void XYWnd_CameraMoved( XYWnd& xywnd ){
815         if ( g_xywindow_globals_private.m_bCamXYUpdate ) {
816                 XYWnd_Update( xywnd );
817         }
818 }
819
820 XYWnd::XYWnd() :
821         m_gl_widget( glwidget_new( FALSE ) ),
822         m_deferredDraw( WidgetQueueDrawCaller( *m_gl_widget ) ),
823         m_deferred_motion( xywnd_motion, this ),
824         m_parent( 0 ),
825         m_window_observer( NewWindowObserver() ),
826         m_XORRectangle( m_gl_widget ),
827         m_chasemouse_handler( 0 ){
828         m_bActive = false;
829         m_buttonstate = 0;
830
831         m_bNewBrushDrag = false;
832         m_move_started = false;
833         m_zoom_started = false;
834
835         m_nWidth = 0;
836         m_nHeight = 0;
837
838         m_vOrigin[0] = 0;
839         m_vOrigin[1] = 20;
840         m_vOrigin[2] = 46;
841         m_fScale = 1;
842         m_viewType = XY;
843
844         m_backgroundActivated = false;
845         m_alpha = 1.0f;
846         m_xmin = 0.0f;
847         m_ymin = 0.0f;
848         m_xmax = 0.0f;
849         m_ymax = 0.0f;
850
851         m_entityCreate = false;
852
853         m_mnuDrop = 0;
854
855         GlobalWindowObservers_add( m_window_observer );
856         GlobalWindowObservers_connectWidget( m_gl_widget );
857
858         m_window_observer->setRectangleDrawCallback( ReferenceCaller1<XYWnd, rect_t, xy_update_xor_rectangle>( *this ) );
859         m_window_observer->setView( m_view );
860
861         gtk_widget_ref( m_gl_widget );
862
863         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 );
864         GTK_WIDGET_SET_FLAGS( m_gl_widget, GTK_CAN_FOCUS );
865
866         m_sizeHandler = g_signal_connect( G_OBJECT( m_gl_widget ), "size_allocate", G_CALLBACK( xywnd_size_allocate ), this );
867         m_exposeHandler = g_signal_connect( G_OBJECT( m_gl_widget ), "expose_event", G_CALLBACK( xywnd_expose ), this );
868
869         g_signal_connect( G_OBJECT( m_gl_widget ), "button_press_event", G_CALLBACK( xywnd_button_press ), this );
870         g_signal_connect( G_OBJECT( m_gl_widget ), "button_release_event", G_CALLBACK( xywnd_button_release ), this );
871         g_signal_connect( G_OBJECT( m_gl_widget ), "focus_in_event", G_CALLBACK( xywnd_focus_in ), this );
872         g_signal_connect( G_OBJECT( m_gl_widget ), "motion_notify_event", G_CALLBACK( DeferredMotion::gtk_motion ), &m_deferred_motion );
873
874         g_signal_connect( G_OBJECT( m_gl_widget ), "scroll_event", G_CALLBACK( xywnd_wheel_scroll ), this );
875
876         Map_addValidCallback( g_map, DeferredDrawOnMapValidChangedCaller( m_deferredDraw ) );
877
878         updateProjection();
879         updateModelview();
880
881         AddSceneChangeCallback( ReferenceCaller<XYWnd, &XYWnd_Update>( *this ) );
882         AddCameraMovedCallback( ReferenceCaller<XYWnd, &XYWnd_CameraMoved>( *this ) );
883
884         PressedButtons_connect( g_pressedButtons, m_gl_widget );
885
886         onMouseDown.connectLast( makeSignalHandler3( MouseDownCaller(), *this ) );
887 }
888
889 XYWnd::~XYWnd(){
890         onDestroyed();
891
892         if ( m_mnuDrop != 0 ) {
893                 gtk_widget_destroy( GTK_WIDGET( m_mnuDrop ) );
894                 m_mnuDrop = 0;
895         }
896
897         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_sizeHandler );
898         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_exposeHandler );
899
900         gtk_widget_unref( m_gl_widget );
901
902         m_window_observer->release();
903 }
904
905 void XYWnd::captureStates(){
906         m_state_selected = GlobalShaderCache().capture( "$XY_OVERLAY" );
907 }
908
909 void XYWnd::releaseStates(){
910         GlobalShaderCache().release( "$XY_OVERLAY" );
911 }
912
913 const Vector3& XYWnd::GetOrigin(){
914         return m_vOrigin;
915 }
916
917 void XYWnd::SetOrigin( const Vector3& origin ){
918         m_vOrigin = origin;
919         updateModelview();
920 }
921
922 void XYWnd::Scroll( int x, int y ){
923         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
924         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
925         m_vOrigin[nDim1] += x / m_fScale;
926         m_vOrigin[nDim2] += y / m_fScale;
927         updateModelview();
928         queueDraw();
929 }
930
931 unsigned int Clipper_buttons(){
932         return RAD_LBUTTON;
933 }
934
935 unsigned int Clipper_quick_buttons(){
936         return RAD_LBUTTON | RAD_CONTROL;
937 }
938
939 void XYWnd::DropClipPoint( int pointx, int pointy ){
940         Vector3 point;
941
942         XY_ToPoint( pointx, pointy, point );
943
944         Vector3 mid;
945         Select_GetMid( mid );
946         g_clip_viewtype = static_cast<VIEWTYPE>( GetViewType() );
947         const int nDim = ( g_clip_viewtype == YZ ) ? 0 : ( ( g_clip_viewtype == XZ ) ? 1 : 2 );
948         point[nDim] = mid[nDim];
949         vector3_snap( point, GetSnapGridSize() );
950         NewClipPoint( point );
951 }
952
953 void XYWnd::Clipper_OnLButtonDown( int x, int y ){
954         Vector3 mousePosition;
955         XY_ToPoint( x, y, mousePosition );
956         g_pMovingClip = GlobalClipPoints_Find( mousePosition, (VIEWTYPE)m_viewType, m_fScale );
957         if ( !g_pMovingClip ) {
958                 DropClipPoint( x, y );
959         }
960 }
961
962 void XYWnd::Clipper_OnLButtonUp( int x, int y ){
963         if ( g_pMovingClip ) {
964                 g_pMovingClip = 0;
965         }
966 }
967
968 void XYWnd::Clipper_OnMouseMoved( int x, int y ){
969         if ( g_pMovingClip ) {
970                 XY_ToPoint( x, y, g_pMovingClip->m_ptClip );
971                 XY_SnapToGrid( g_pMovingClip->m_ptClip );
972                 Clip_Update();
973                 ClipperChangeNotify();
974         }
975 }
976
977 void XYWnd::Clipper_Crosshair_OnMouseMoved( int x, int y ){
978         Vector3 mousePosition;
979         XY_ToPoint( x, y, mousePosition );
980         if ( ClipMode() && GlobalClipPoints_Find( mousePosition, (VIEWTYPE)m_viewType, m_fScale ) != 0 ) {
981                 GdkCursor *cursor;
982                 cursor = gdk_cursor_new( GDK_CROSSHAIR );
983                 gdk_window_set_cursor( m_gl_widget->window, cursor );
984                 gdk_cursor_unref( cursor );
985         }
986         else
987         {
988                 gdk_window_set_cursor( m_gl_widget->window, 0 );
989         }
990 }
991
992 void XYWnd::SetCustomPivotOrigin( int pointx, int pointy ){
993         Vector3 point;
994         XY_ToPoint( pointx, pointy, point );
995         VIEWTYPE viewtype = static_cast<VIEWTYPE>( GetViewType() );
996         const int nDim = ( viewtype == YZ ) ? 0 : ( ( viewtype == XZ ) ? 1 : 2 );
997         //vector3_snap( point, GetSnapGridSize() );
998         point[nDim] = 999999;
999
1000         GlobalSelectionSystem().setCustomPivotOrigin( point );
1001         SceneChangeNotify();
1002 }
1003
1004 unsigned int MoveCamera_buttons(){
1005         return RAD_CONTROL | ( g_glwindow_globals.m_nMouseType == ETwoButton ? RAD_RBUTTON : RAD_MBUTTON );
1006 }
1007
1008 void XYWnd_PositionCamera( XYWnd* xywnd, int x, int y, CamWnd& camwnd ){
1009         Vector3 origin( Camera_getOrigin( camwnd ) );
1010         xywnd->XY_ToPoint( x, y, origin );
1011         xywnd->XY_SnapToGrid( origin );
1012         Camera_setOrigin( camwnd, origin );
1013 }
1014
1015 unsigned int OrientCamera_buttons(){
1016         if ( g_glwindow_globals.m_nMouseType == ETwoButton ) {
1017                 return RAD_RBUTTON | RAD_SHIFT | RAD_CONTROL;
1018         }
1019         return RAD_MBUTTON;
1020 }
1021
1022 void XYWnd_OrientCamera( XYWnd* xywnd, int x, int y, CamWnd& camwnd ){
1023         Vector3 point = g_vector3_identity;
1024         xywnd->XY_ToPoint( x, y, point );
1025         xywnd->XY_SnapToGrid( point );
1026         vector3_subtract( point, Camera_getOrigin( camwnd ) );
1027
1028         int n1 = ( xywnd->GetViewType() == XY ) ? 1 : 2;
1029         int n2 = ( xywnd->GetViewType() == YZ ) ? 1 : 0;
1030         int nAngle = ( xywnd->GetViewType() == XY ) ? CAMERA_YAW : CAMERA_PITCH;
1031         if ( point[n1] || point[n2] ) {
1032                 Vector3 angles( Camera_getAngles( camwnd ) );
1033                 angles[nAngle] = static_cast<float>( radians_to_degrees( atan2( point[n1], point[n2] ) ) );
1034                 Camera_setAngles( camwnd, angles );
1035         }
1036 }
1037
1038 unsigned int SetCustomPivotOrigin_buttons(){
1039         return RAD_MBUTTON | RAD_SHIFT;
1040 }
1041
1042 /*
1043    ==============
1044    NewBrushDrag
1045    ==============
1046  */
1047 unsigned int NewBrushDrag_buttons(){
1048         return RAD_LBUTTON;
1049 }
1050
1051 void XYWnd::NewBrushDrag_Begin( int x, int y ){
1052         m_NewBrushDrag = 0;
1053         m_nNewBrushPressx = x;
1054         m_nNewBrushPressy = y;
1055
1056         m_bNewBrushDrag = true;
1057         GlobalUndoSystem().start();
1058 }
1059
1060 void XYWnd::NewBrushDrag_End( int x, int y ){
1061         if ( m_NewBrushDrag != 0 ) {
1062                 GlobalUndoSystem().finish( "brushDragNew" );
1063         }
1064 }
1065
1066 void XYWnd::NewBrushDrag( int x, int y ){
1067         Vector3 mins, maxs;
1068         XY_ToPoint( m_nNewBrushPressx, m_nNewBrushPressy, mins );
1069         XY_SnapToGrid( mins );
1070         XY_ToPoint( x, y, maxs );
1071         XY_SnapToGrid( maxs );
1072
1073         int nDim = ( m_viewType == XY ) ? 2 : ( m_viewType == YZ ) ? 0 : 1;
1074
1075         mins[nDim] = float_snapped( Select_getWorkZone().d_work_min[nDim], GetSnapGridSize() );
1076         maxs[nDim] = float_snapped( Select_getWorkZone().d_work_max[nDim], GetSnapGridSize() );
1077
1078         if ( maxs[nDim] <= mins[nDim] ) {
1079                 maxs[nDim] = mins[nDim] + GetGridSize();
1080         }
1081
1082         for ( int i = 0 ; i < 3 ; i++ )
1083         {
1084                 if ( mins[i] == maxs[i] ) {
1085                         return; // don't create a degenerate brush
1086                 }
1087                 if ( mins[i] > maxs[i] ) {
1088                         float temp = mins[i];
1089                         mins[i] = maxs[i];
1090                         maxs[i] = temp;
1091                 }
1092         }
1093
1094         if ( m_NewBrushDrag == 0 ) {
1095                 NodeSmartReference node( GlobalBrushCreator().createBrush() );
1096                 Node_getTraversable( Map_FindOrInsertWorldspawn( g_map ) )->insert( node );
1097
1098                 scene::Path brushpath( makeReference( GlobalSceneGraph().root() ) );
1099                 brushpath.push( makeReference( *Map_GetWorldspawn( g_map ) ) );
1100                 brushpath.push( makeReference( node.get() ) );
1101                 selectPath( brushpath, true );
1102
1103                 m_NewBrushDrag = node.get_pointer();
1104         }
1105
1106         // d1223m
1107         //Scene_BrushResize_Selected(GlobalSceneGraph(), aabb_for_minmax(mins, maxs), TextureBrowser_GetSelectedShader(GlobalTextureBrowser()));
1108         Scene_BrushResize_Selected( GlobalSceneGraph(), aabb_for_minmax( mins, maxs ),
1109                                                                 g_brush_always_caulk ?
1110                                                                 "textures/common/caulk" : TextureBrowser_GetSelectedShader( GlobalTextureBrowser() ) );
1111 }
1112
1113 void entitycreate_activated( GtkWidget* item ){
1114         scene::Node* world_node = Map_FindWorldspawn( g_map );
1115         const char* entity_name = gtk_label_get_text( GTK_LABEL( GTK_BIN( item )->child ) );
1116
1117         if ( !( world_node && string_equal( entity_name, "worldspawn" ) ) ) {
1118                 g_pParentWnd->ActiveXY()->OnEntityCreate( entity_name );
1119         }
1120         else {
1121                 GlobalRadiant().m_pfnMessageBox( GTK_WIDGET( MainFrame_getWindow() ), "There's already a worldspawn in your map!"
1122                                                                                                                                                           "",
1123                                                                                  "Info",
1124                                                                                  eMB_OK,
1125                                                                                  eMB_ICONDEFAULT );
1126         }
1127 }
1128
1129 void EntityClassMenu_addItem( GtkMenu* menu, const char* name ){
1130         GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_label( name ) );
1131         g_signal_connect( G_OBJECT( item ), "activate", G_CALLBACK( entitycreate_activated ), item );
1132         gtk_widget_show( GTK_WIDGET( item ) );
1133         menu_add_item( menu, item );
1134 }
1135
1136 class EntityClassMenuInserter : public EntityClassVisitor
1137 {
1138 typedef std::pair<GtkMenu*, CopiedString> MenuPair;
1139 typedef std::vector<MenuPair> MenuStack;
1140 MenuStack m_stack;
1141 CopiedString m_previous;
1142 public:
1143 EntityClassMenuInserter( GtkMenu* menu ){
1144         m_stack.reserve( 2 );
1145         m_stack.push_back( MenuPair( menu, "" ) );
1146 }
1147 ~EntityClassMenuInserter(){
1148         if ( !string_empty( m_previous.c_str() ) ) {
1149                 addItem( m_previous.c_str(), "" );
1150         }
1151 }
1152 void visit( EntityClass* e ){
1153         ASSERT_MESSAGE( !string_empty( e->name() ), "entity-class has no name" );
1154         if ( !string_empty( m_previous.c_str() ) ) {
1155                 addItem( m_previous.c_str(), e->name() );
1156         }
1157         m_previous = e->name();
1158 }
1159 void pushMenu( const CopiedString& name ){
1160         GtkMenuItem* item = GTK_MENU_ITEM( gtk_menu_item_new_with_label( name.c_str() ) );
1161         gtk_widget_show( GTK_WIDGET( item ) );
1162         container_add_widget( GTK_CONTAINER( m_stack.back().first ), GTK_WIDGET( item ) );
1163
1164         GtkMenu* submenu = GTK_MENU( gtk_menu_new() );
1165         gtk_menu_item_set_submenu( item, GTK_WIDGET( submenu ) );
1166
1167         m_stack.push_back( MenuPair( submenu, name ) );
1168 }
1169 void popMenu(){
1170         m_stack.pop_back();
1171 }
1172 void addItem( const char* name, const char* next ){
1173         const char* underscore = strchr( name, '_' );
1174
1175         if ( underscore != 0 && underscore != name ) {
1176                 bool nextEqual = string_equal_n( name, next, ( underscore + 1 ) - name );
1177                 const char* parent = m_stack.back().second.c_str();
1178
1179                 if ( !string_empty( parent )
1180                          && string_length( parent ) == std::size_t( underscore - name )
1181                          && string_equal_n( name, parent, underscore - name ) ) { // this is a child
1182                 }
1183                 else if ( nextEqual ) {
1184                         if ( m_stack.size() == 2 ) {
1185                                 popMenu();
1186                         }
1187                         pushMenu( CopiedString( StringRange( name, underscore ) ) );
1188                 }
1189                 else if ( m_stack.size() == 2 ) {
1190                         popMenu();
1191                 }
1192         }
1193         else if ( m_stack.size() == 2 ) {
1194                 popMenu();
1195         }
1196
1197         EntityClassMenu_addItem( m_stack.back().first, name );
1198 }
1199 };
1200
1201 void XYWnd::OnContextMenu(){
1202         if ( g_xywindow_globals.m_bRightClick == false ) {
1203                 return;
1204         }
1205
1206         if ( m_mnuDrop == 0 ) { // first time, load it up
1207                 GtkMenu* menu = m_mnuDrop = GTK_MENU( gtk_menu_new() );
1208
1209                 EntityClassMenuInserter inserter( menu );
1210                 GlobalEntityClassManager().forEach( inserter );
1211         }
1212
1213         gtk_menu_popup( m_mnuDrop, 0, 0, 0, 0, 1, GDK_CURRENT_TIME );
1214 }
1215
1216 FreezePointer g_xywnd_freezePointer;
1217
1218 unsigned int Move_buttons(){
1219         return RAD_RBUTTON;
1220 }
1221
1222 void XYWnd_moveDelta( int x, int y, unsigned int state, void* data ){
1223         reinterpret_cast<XYWnd*>( data )->EntityCreate_MouseMove( x, y );
1224         reinterpret_cast<XYWnd*>( data )->Scroll( -x, y );
1225 }
1226
1227 gboolean XYWnd_Move_focusOut( GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd ){
1228         xywnd->Move_End();
1229         return FALSE;
1230 }
1231
1232 void XYWnd::Move_Begin(){
1233         if ( m_move_started ) {
1234                 Move_End();
1235         }
1236         m_move_started = true;
1237         g_xywnd_freezePointer.freeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), m_gl_widget, XYWnd_moveDelta, this );
1238         m_move_focusOut = g_signal_connect( G_OBJECT( m_gl_widget ), "focus_out_event", G_CALLBACK( XYWnd_Move_focusOut ), this );
1239 }
1240
1241 void XYWnd::Move_End(){
1242         m_move_started = false;
1243         g_xywnd_freezePointer.unfreeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), false );
1244         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_move_focusOut );
1245 }
1246
1247 unsigned int Zoom_buttons(){
1248         return RAD_RBUTTON | RAD_ALT;
1249 }
1250
1251 int g_dragZoom = 0;
1252
1253 void XYWnd_zoomDelta( int x, int y, unsigned int state, void* data ){
1254         if ( y != 0 ) {
1255                 g_dragZoom += y;
1256                 while ( abs( g_dragZoom ) > 8 )
1257                 {
1258                         if ( g_dragZoom > 0 ) {
1259                                 reinterpret_cast<XYWnd*>( data )->ZoomOut();
1260                                 g_dragZoom -= 8;
1261                         }
1262                         else
1263                         {
1264                                 reinterpret_cast<XYWnd*>( data )->ZoomIn();
1265                                 g_dragZoom += 8;
1266                         }
1267                 }
1268         }
1269 }
1270
1271 gboolean XYWnd_Zoom_focusOut( GtkWidget* widget, GdkEventFocus* event, XYWnd* xywnd ){
1272         xywnd->Zoom_End();
1273         return FALSE;
1274 }
1275
1276 void XYWnd::Zoom_Begin(){
1277         if ( m_zoom_started ) {
1278                 Zoom_End();
1279         }
1280         m_zoom_started = true;
1281         g_dragZoom = 0;
1282         g_xywnd_freezePointer.freeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), m_gl_widget, XYWnd_zoomDelta, this );
1283         m_zoom_focusOut = g_signal_connect( G_OBJECT( m_gl_widget ), "focus_out_event", G_CALLBACK( XYWnd_Zoom_focusOut ), this );
1284 }
1285
1286 void XYWnd::Zoom_End(){
1287         m_zoom_started = false;
1288         g_xywnd_freezePointer.unfreeze_pointer( m_parent != 0 ? m_parent : MainFrame_getWindow(), false );
1289         g_signal_handler_disconnect( G_OBJECT( m_gl_widget ), m_zoom_focusOut );
1290 }
1291
1292 // makes sure the selected brush or camera is in view
1293 void XYWnd::PositionView( const Vector3& position ){
1294         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1295         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1296
1297         m_vOrigin[nDim1] = position[nDim1];
1298         m_vOrigin[nDim2] = position[nDim2];
1299
1300         updateModelview();
1301
1302         XYWnd_Update( *this );
1303 }
1304
1305 void XYWnd::SetViewType( VIEWTYPE viewType ){
1306         m_viewType = viewType;
1307         updateModelview();
1308
1309         if ( m_parent != 0 ) {
1310                 gtk_window_set_title( m_parent, ViewType_getTitle( m_viewType ) );
1311         }
1312 }
1313
1314
1315 inline WindowVector WindowVector_forInteger( int x, int y ){
1316         return WindowVector( static_cast<float>( x ), static_cast<float>( y ) );
1317 }
1318
1319 void XYWnd::mouseDown( const WindowVector& position, ButtonIdentifier button, ModifierFlags modifiers ){
1320         XY_MouseDown( static_cast<int>( position.x() ), static_cast<int>( position.y() ), buttons_for_button_and_modifiers( button, modifiers ) );
1321 }
1322 void XYWnd::XY_MouseDown( int x, int y, unsigned int buttons ){
1323         if ( buttons == Move_buttons() ) {
1324                 Move_Begin();
1325                 EntityCreate_MouseDown( x, y );
1326         }
1327         else if ( buttons == Zoom_buttons() ) {
1328                 Zoom_Begin();
1329         }
1330         else if ( ClipMode() && ( buttons == Clipper_buttons() || buttons == Clipper_quick_buttons() ) ) {
1331                 Clipper_OnLButtonDown( x, y );
1332         }
1333         else if ( !ClipMode() && buttons == Clipper_quick_buttons() ) {
1334                 ClipperMode();
1335                 g_quick_clipper = true;
1336                 Clipper_OnLButtonDown( x, y );
1337         }
1338         else if ( buttons == NewBrushDrag_buttons() && GlobalSelectionSystem().countSelected() == 0 ) {
1339                 NewBrushDrag_Begin( x, y );
1340         }
1341         // control mbutton = move camera
1342         else if ( buttons == MoveCamera_buttons() ) {
1343                 XYWnd_PositionCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1344         }
1345         // mbutton = angle camera
1346         else if ( buttons == OrientCamera_buttons() ) {
1347                 XYWnd_OrientCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1348         }
1349         else if ( buttons == SetCustomPivotOrigin_buttons() ) {
1350                 SetCustomPivotOrigin( x, y );
1351         }
1352         else
1353         {
1354                 m_window_observer->onMouseDown( WindowVector_forInteger( x, y ), button_for_flags( buttons ), modifiers_for_flags( buttons ) );
1355         }
1356 }
1357
1358 void XYWnd::XY_MouseUp( int x, int y, unsigned int buttons ){
1359         if ( m_move_started ) {
1360                 Move_End();
1361                 EntityCreate_MouseUp( x, y );
1362         }
1363         else if ( m_zoom_started ) {
1364                 Zoom_End();
1365         }
1366         else if ( ClipMode() && ( buttons == Clipper_buttons() || buttons == Clipper_quick_buttons() ) ) {
1367                 Clipper_OnLButtonUp( x, y );
1368         }
1369         else if ( m_bNewBrushDrag ) {
1370                 m_bNewBrushDrag = false;
1371                 NewBrushDrag_End( x, y );
1372                 if ( m_NewBrushDrag == 0 ) {
1373                         //L button w/o created brush = tunnel selection
1374                         m_window_observer->onMouseUp( WindowVector_forInteger( x, y ), button_for_flags( buttons ), modifiers_for_flags( buttons ) );
1375                 }
1376         }
1377         else
1378         {
1379                 m_window_observer->onMouseUp( WindowVector_forInteger( x, y ), button_for_flags( buttons ), modifiers_for_flags( buttons ) );
1380         }
1381 }
1382
1383 void XYWnd::XY_MouseMoved( int x, int y, unsigned int buttons ){
1384         // rbutton = drag xy origin
1385         if ( m_move_started ) {
1386         }
1387         // zoom in/out
1388         else if ( m_zoom_started ) {
1389         }
1390
1391         else if ( ClipMode() && g_pMovingClip != 0 ) {
1392                 Clipper_OnMouseMoved( x, y );
1393         }
1394         // lbutton without selection = drag new brush
1395         else if ( m_bNewBrushDrag ) {
1396                 NewBrushDrag( x, y );
1397         }
1398
1399         // control mbutton = move camera
1400         else if ( getButtonState() == MoveCamera_buttons() ) {
1401                 XYWnd_PositionCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1402         }
1403
1404         // mbutton = angle camera
1405         else if ( getButtonState() == OrientCamera_buttons() ) {
1406                 XYWnd_OrientCamera( this, x, y, *g_pParentWnd->GetCamWnd() );
1407         }
1408
1409         else if ( buttons == SetCustomPivotOrigin_buttons() ) {
1410                 SetCustomPivotOrigin( x, y );
1411         }
1412
1413         else
1414         {
1415                 m_window_observer->onMouseMotion( WindowVector_forInteger( x, y ), modifiers_for_flags( buttons ) );
1416
1417                 m_mousePosition[0] = m_mousePosition[1] = m_mousePosition[2] = 0.0;
1418                 XY_ToPoint( x, y, m_mousePosition );
1419                 XY_SnapToGrid( m_mousePosition );
1420
1421                 StringOutputStream status( 64 );
1422                 status << "x:: " << FloatFormat( m_mousePosition[0], 6, 1 )
1423                            << "  y:: " << FloatFormat( m_mousePosition[1], 6, 1 )
1424                            << "  z:: " << FloatFormat( m_mousePosition[2], 6, 1 );
1425                 g_pParentWnd->SetStatusText( g_pParentWnd->m_position_status, status.c_str() );
1426
1427                 if ( g_bCrossHairs ) {
1428                         XYWnd_Update( *this );
1429                 }
1430
1431                 Clipper_Crosshair_OnMouseMoved( x, y );
1432         }
1433 }
1434
1435 void XYWnd::EntityCreate_MouseDown( int x, int y ){
1436         m_entityCreate = true;
1437         m_entityCreate_x = x;
1438         m_entityCreate_y = y;
1439 }
1440
1441 void XYWnd::EntityCreate_MouseMove( int x, int y ){
1442         if ( m_entityCreate && ( m_entityCreate_x != x || m_entityCreate_y != y ) ) {
1443                 m_entityCreate = false;
1444         }
1445 }
1446
1447 void XYWnd::EntityCreate_MouseUp( int x, int y ){
1448         if ( m_entityCreate ) {
1449                 m_entityCreate = false;
1450                 OnContextMenu();
1451         }
1452 }
1453
1454 inline float screen_normalised( int pos, unsigned int size ){
1455         return ( ( 2.0f * pos ) / size ) - 1.0f;
1456 }
1457
1458 inline float normalised_to_world( float normalised, float world_origin, float normalised2world_scale ){
1459         return world_origin + normalised * normalised2world_scale;
1460 }
1461
1462
1463 // TTimo: watch it, this doesn't init one of the 3 coords
1464 void XYWnd::XY_ToPoint( int x, int y, Vector3& point ){
1465         float normalised2world_scale_x = m_nWidth / 2 / m_fScale;
1466         float normalised2world_scale_y = m_nHeight / 2 / m_fScale;
1467         if ( m_viewType == XY ) {
1468                 point[0] = normalised_to_world( screen_normalised( x, m_nWidth ), m_vOrigin[0], normalised2world_scale_x );
1469                 point[1] = normalised_to_world( -screen_normalised( y, m_nHeight ), m_vOrigin[1], normalised2world_scale_y );
1470         }
1471         else if ( m_viewType == YZ ) {
1472                 point[1] = normalised_to_world( screen_normalised( x, m_nWidth ), m_vOrigin[1], normalised2world_scale_x );
1473                 point[2] = normalised_to_world( -screen_normalised( y, m_nHeight ), m_vOrigin[2], normalised2world_scale_y );
1474         }
1475         else
1476         {
1477                 point[0] = normalised_to_world( screen_normalised( x, m_nWidth ), m_vOrigin[0], normalised2world_scale_x );
1478                 point[2] = normalised_to_world( -screen_normalised( y, m_nHeight ), m_vOrigin[2], normalised2world_scale_y );
1479         }
1480 }
1481
1482 void XYWnd::XY_SnapToGrid( Vector3& point ){
1483         if ( m_viewType == XY ) {
1484                 point[0] = float_snapped( point[0], GetSnapGridSize() );
1485                 point[1] = float_snapped( point[1], GetSnapGridSize() );
1486         }
1487         else if ( m_viewType == YZ ) {
1488                 point[1] = float_snapped( point[1], GetSnapGridSize() );
1489                 point[2] = float_snapped( point[2], GetSnapGridSize() );
1490         }
1491         else
1492         {
1493                 point[0] = float_snapped( point[0], GetSnapGridSize() );
1494                 point[2] = float_snapped( point[2], GetSnapGridSize() );
1495         }
1496 }
1497
1498 void XYWnd::XY_LoadBackgroundImage( const char *name ){
1499         const char* relative = path_make_relative( name, GlobalFileSystem().findRoot( name ) );
1500         if ( relative == name ) {
1501                 globalOutputStream() << "WARNING: could not extract the relative path, using full path instead\n";
1502         }
1503
1504         char fileNameWithoutExt[512];
1505         strncpy( fileNameWithoutExt, relative, sizeof( fileNameWithoutExt ) - 1 );
1506         fileNameWithoutExt[512 - 1] = '\0';
1507         fileNameWithoutExt[strlen( fileNameWithoutExt ) - 4] = '\0';
1508
1509         Image *image = QERApp_LoadImage( 0, fileNameWithoutExt );
1510         if ( !image ) {
1511                 globalOutputStream() << "Could not load texture " << fileNameWithoutExt << "\n";
1512                 return;
1513         }
1514         g_pParentWnd->ActiveXY()->m_tex = (qtexture_t*)malloc( sizeof( qtexture_t ) );
1515         LoadTextureRGBA( g_pParentWnd->ActiveXY()->XYWnd::m_tex, image->getRGBAPixels(), image->getWidth(), image->getHeight() );
1516         globalOutputStream() << "Loaded background texture " << relative << "\n";
1517         g_pParentWnd->ActiveXY()->m_backgroundActivated = true;
1518
1519         int m_ix, m_iy;
1520         switch ( g_pParentWnd->ActiveXY()->m_viewType )
1521         {
1522         case XY:
1523                 m_ix = 0;
1524                 m_iy = 1;
1525                 break;
1526         case XZ:
1527                 m_ix = 0;
1528                 m_iy = 2;
1529                 break;
1530         case YZ:
1531                 m_ix = 1;
1532                 m_iy = 2;
1533                 break;
1534         }
1535
1536         Vector3 min, max;
1537         Select_GetBounds( min, max );
1538         g_pParentWnd->ActiveXY()->m_xmin = min[m_ix];
1539         g_pParentWnd->ActiveXY()->m_ymin = min[m_iy];
1540         g_pParentWnd->ActiveXY()->m_xmax = max[m_ix];
1541         g_pParentWnd->ActiveXY()->m_ymax = max[m_iy];
1542 }
1543
1544 void XYWnd::XY_DisableBackground( void ){
1545         g_pParentWnd->ActiveXY()->m_backgroundActivated = false;
1546         if ( g_pParentWnd->ActiveXY()->m_tex ) {
1547                 free( g_pParentWnd->ActiveXY()->m_tex );
1548         }
1549         g_pParentWnd->ActiveXY()->m_tex = NULL;
1550 }
1551
1552 void WXY_BackgroundSelect( void ){
1553         bool brushesSelected = Scene_countSelectedBrushes( GlobalSceneGraph() ) != 0;
1554         if ( !brushesSelected ) {
1555                 gtk_MessageBox( 0, "You have to select some brushes to get the bounding box for.\n",
1556                                                 "No selection", eMB_OK, eMB_ICONERROR );
1557                 return;
1558         }
1559
1560         const char *filename = file_dialog( GTK_WIDGET( MainFrame_getWindow() ), TRUE, "Background Image", NULL, NULL );
1561         g_pParentWnd->ActiveXY()->XY_DisableBackground();
1562         if ( filename ) {
1563                 g_pParentWnd->ActiveXY()->XY_LoadBackgroundImage( filename );
1564         }
1565 }
1566
1567 /*
1568    ============================================================================
1569
1570    DRAWING
1571
1572    ============================================================================
1573  */
1574
1575 /*
1576    ==============
1577    XY_DrawGrid
1578    ==============
1579  */
1580
1581 double two_to_the_power( int power ){
1582         return pow( 2.0f, power );
1583 }
1584
1585 void XYWnd::XY_DrawAxis( void ){
1586         if ( g_xywindow_globals_private.show_axis ) {
1587                 const char g_AxisName[3] = { 'X', 'Y', 'Z' };
1588                 const int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1589                 const int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1590                 const int w = ( m_nWidth / 2 / m_fScale );
1591                 const int h = ( m_nHeight / 2 / m_fScale );
1592
1593                 const Vector3& colourX = ( m_viewType == YZ ) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorX;
1594                 const Vector3& colourY = ( m_viewType == XY ) ? g_xywindow_globals.AxisColorY : g_xywindow_globals.AxisColorZ;
1595
1596                 // draw two lines with corresponding axis colors to highlight current view
1597                 // horizontal line: nDim1 color
1598                 glLineWidth( 2 );
1599                 glBegin( GL_LINES );
1600                 glColor3fv( vector3_to_array( colourX ) );
1601                 glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1602                 glVertex2f( m_vOrigin[nDim1] - w + 65 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1603                 glVertex2f( 0, 0 );
1604                 glVertex2f( 32 / m_fScale, 0 );
1605                 glColor3fv( vector3_to_array( colourY ) );
1606                 glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 45 / m_fScale );
1607                 glVertex2f( m_vOrigin[nDim1] - w + 40 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale );
1608                 glVertex2f( 0, 0 );
1609                 glVertex2f( 0, 32 / m_fScale );
1610                 glEnd();
1611                 glLineWidth( 1 );
1612                 // now print axis symbols
1613                 glColor3fv( vector3_to_array( colourX ) );
1614                 glRasterPos2f( m_vOrigin[nDim1] - w + 55 / m_fScale, m_vOrigin[nDim2] + h - 55 / m_fScale );
1615                 GlobalOpenGL().drawChar( g_AxisName[nDim1] );
1616                 glRasterPos2f( 28 / m_fScale, -10 / m_fScale );
1617                 GlobalOpenGL().drawChar( g_AxisName[nDim1] );
1618                 glColor3fv( vector3_to_array( colourY ) );
1619                 glRasterPos2f( m_vOrigin[nDim1] - w + 25 / m_fScale, m_vOrigin[nDim2] + h - 30 / m_fScale );
1620                 GlobalOpenGL().drawChar( g_AxisName[nDim2] );
1621                 glRasterPos2f( -10 / m_fScale, 28 / m_fScale );
1622                 GlobalOpenGL().drawChar( g_AxisName[nDim2] );
1623         }
1624 }
1625
1626 void XYWnd::XY_DrawBackground( void ){
1627         glPushAttrib( GL_ALL_ATTRIB_BITS );
1628
1629         glEnable( GL_TEXTURE_2D );
1630         glEnable( GL_BLEND );
1631         glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
1632         glTexEnvf( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
1633         glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP );
1634         glTexParameterf( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP );
1635
1636         glPolygonMode( GL_FRONT, GL_FILL );
1637
1638         glBindTexture( GL_TEXTURE_2D, m_tex->texture_number );
1639         glBegin( GL_QUADS );
1640
1641         glColor4f( 1.0, 1.0, 1.0, m_alpha );
1642         glTexCoord2f( 0.0, 1.0 );
1643         glVertex2f( m_xmin, m_ymin );
1644
1645         glTexCoord2f( 1.0, 1.0 );
1646         glVertex2f( m_xmax, m_ymin );
1647
1648         glTexCoord2f( 1.0, 0.0 );
1649         glVertex2f( m_xmax, m_ymax );
1650
1651         glTexCoord2f( 0.0, 0.0 );
1652         glVertex2f( m_xmin, m_ymax );
1653
1654         glEnd();
1655         glBindTexture( GL_TEXTURE_2D, 0 );
1656
1657         glPopAttrib();
1658 }
1659
1660 void XYWnd::XY_DrawGrid( void ) {
1661         float x, y, xb, xe, yb, ye;
1662         float w, h, a;
1663         char text[32];
1664         float step, minor_step, stepx, stepy;
1665         step = minor_step = stepx = stepy = GetGridSize();
1666
1667         int minor_power = Grid_getPower();
1668         int mask;
1669
1670         while ( ( minor_step * m_fScale ) <= 4.0f ) { // make sure minor grid spacing is at least 4 pixels on the screen
1671                 ++minor_power;
1672                 minor_step *= 2;
1673         }
1674         int power = minor_power;
1675         while ( ( power % 3 ) != 0 || ( step * m_fScale ) <= 32.0f ) { // make sure major grid spacing is at least 32 pixels on the screen
1676                 ++power;
1677                 step = float(two_to_the_power( power ) );
1678         }
1679         mask = ( 1 << ( power - minor_power ) ) - 1;
1680         while ( ( stepx * m_fScale ) <= 32.0f ) // text step x must be at least 32
1681                 stepx *= 2;
1682         while ( ( stepy * m_fScale ) <= 32.0f ) // text step y must be at least 32
1683                 stepy *= 2;
1684
1685         a = ( ( GetSnapGridSize() > 0.0f ) ? 1.0f : 0.3f );
1686
1687         glDisable( GL_TEXTURE_2D );
1688         glDisable( GL_TEXTURE_1D );
1689         glDisable( GL_DEPTH_TEST );
1690         glDisable( GL_BLEND );
1691         glLineWidth( 1 );
1692
1693         w = ( m_nWidth / 2 / m_fScale );
1694         h = ( m_nHeight / 2 / m_fScale );
1695
1696         const int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1697         const int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1698
1699         xb = m_vOrigin[nDim1] - w;
1700         if ( xb < region_mins[nDim1] ) {
1701                 xb = region_mins[nDim1];
1702         }
1703         xb = step * floor( xb / step );
1704
1705         xe = m_vOrigin[nDim1] + w;
1706         if ( xe > region_maxs[nDim1] ) {
1707                 xe = region_maxs[nDim1];
1708         }
1709         xe = step * ceil( xe / step );
1710
1711         yb = m_vOrigin[nDim2] - h;
1712         if ( yb < region_mins[nDim2] ) {
1713                 yb = region_mins[nDim2];
1714         }
1715         yb = step * floor( yb / step );
1716
1717         ye = m_vOrigin[nDim2] + h;
1718         if ( ye > region_maxs[nDim2] ) {
1719                 ye = region_maxs[nDim2];
1720         }
1721         ye = step * ceil( ye / step );
1722
1723 #define COLORS_DIFFER( a,b ) \
1724         ( ( a )[0] != ( b )[0] || \
1725           ( a )[1] != ( b )[1] || \
1726           ( a )[2] != ( b )[2] )
1727
1728         // djbob
1729         // draw minor blocks
1730         if ( g_xywindow_globals_private.d_showgrid || a < 1.0f ) {
1731                 if ( a < 1.0f ) {
1732                         glEnable( GL_BLEND );
1733                 }
1734
1735                 if ( COLORS_DIFFER( g_xywindow_globals.color_gridminor, g_xywindow_globals.color_gridback ) ) {
1736                         glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridminor, a ) ) );
1737
1738                         glBegin( GL_LINES );
1739                         int i = 0;
1740                         for ( x = xb ; x < xe ; x += minor_step, ++i ) {
1741                                 if ( ( i & mask ) != 0 ) {
1742                                         glVertex2f( x, yb );
1743                                         glVertex2f( x, ye );
1744                                 }
1745                         }
1746                         i = 0;
1747                         for ( y = yb ; y < ye ; y += minor_step, ++i ) {
1748                                 if ( ( i & mask ) != 0 ) {
1749                                         glVertex2f( xb, y );
1750                                         glVertex2f( xe, y );
1751                                 }
1752                         }
1753                         glEnd();
1754                 }
1755
1756                 // draw major blocks
1757                 if ( COLORS_DIFFER( g_xywindow_globals.color_gridmajor, g_xywindow_globals.color_gridminor ) ) {
1758                         glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridmajor, a ) ) );
1759
1760                         glBegin( GL_LINES );
1761                         for ( x = xb ; x <= xe ; x += step ) {
1762                                 glVertex2f( x, yb );
1763                                 glVertex2f( x, ye );
1764                         }
1765                         for ( y = yb ; y <= ye ; y += step ) {
1766                                 glVertex2f( xb, y );
1767                                 glVertex2f( xe, y );
1768                         }
1769                         glEnd();
1770                 }
1771
1772                 if ( a < 1.0f ) {
1773                         glDisable( GL_BLEND );
1774                 }
1775         }
1776
1777         // draw coordinate text if needed
1778         if ( g_xywindow_globals_private.show_coordinates ) {
1779                 glColor4fv( vector4_to_array( Vector4( g_xywindow_globals.color_gridtext, 1.0f ) ) );
1780                 float offx = m_vOrigin[nDim2] + h - ( 4 + GlobalOpenGL().m_font->getPixelAscent() ) / m_fScale;
1781                 float offy = m_vOrigin[nDim1] - w +  4                                            / m_fScale;
1782                 for ( x = xb - fmod( xb, stepx ); x <= xe ; x += stepx ) {
1783                         glRasterPos2f( x, offx );
1784                         sprintf( text, "%g", x );
1785                         GlobalOpenGL().drawString( text );
1786                 }
1787                 for ( y = yb - fmod( yb, stepy ); y <= ye ; y += stepy ) {
1788                         glRasterPos2f( offy, y );
1789                         sprintf( text, "%g", y );
1790                         GlobalOpenGL().drawString( text );
1791                 }
1792
1793                 if ( Active() ) {
1794                         glColor3fv( vector3_to_array( g_xywindow_globals.color_viewname ) );
1795                 }
1796
1797                 // we do this part (the old way) only if show_axis is disabled
1798                 if ( !g_xywindow_globals_private.show_axis ) {
1799                         glRasterPos2f( m_vOrigin[nDim1] - w + 35 / m_fScale, m_vOrigin[nDim2] + h - 20 / m_fScale );
1800
1801                         GlobalOpenGL().drawString( ViewType_getTitle( m_viewType ) );
1802                 }
1803         }
1804
1805         XYWnd::XY_DrawAxis();
1806
1807         // show current work zone?
1808         // the work zone is used to place dropped points and brushes
1809         if ( g_xywindow_globals_private.d_show_work ) {
1810                 glColor4f( 1.0f, 0.0f, 0.0f, 1.0f );
1811                 glBegin( GL_LINES );
1812                 glVertex2f( xb, Select_getWorkZone().d_work_min[nDim2] );
1813                 glVertex2f( xe, Select_getWorkZone().d_work_min[nDim2] );
1814                 glVertex2f( xb, Select_getWorkZone().d_work_max[nDim2] );
1815                 glVertex2f( xe, Select_getWorkZone().d_work_max[nDim2] );
1816                 glVertex2f( Select_getWorkZone().d_work_min[nDim1], yb );
1817                 glVertex2f( Select_getWorkZone().d_work_min[nDim1], ye );
1818                 glVertex2f( Select_getWorkZone().d_work_max[nDim1], yb );
1819                 glVertex2f( Select_getWorkZone().d_work_max[nDim1], ye );
1820                 glEnd();
1821         }
1822 }
1823
1824 /*
1825    ==============
1826    XY_DrawBlockGrid
1827    ==============
1828  */
1829 void XYWnd::XY_DrawBlockGrid(){
1830         if ( Map_FindWorldspawn( g_map ) == 0 ) {
1831                 return;
1832         }
1833         const char *value = Node_getEntity( *Map_GetWorldspawn( g_map ) )->getKeyValue( "_blocksize" );
1834         if ( strlen( value ) ) {
1835                 sscanf( value, "%i", &g_xywindow_globals_private.blockSize );
1836         }
1837
1838         if ( !g_xywindow_globals_private.blockSize || g_xywindow_globals_private.blockSize > 65536 || g_xywindow_globals_private.blockSize < 1024 ) {
1839                 // don't use custom blocksize if it is less than the default, or greater than the maximum world coordinate
1840                 g_xywindow_globals_private.blockSize = 1024;
1841         }
1842
1843         float x, y, xb, xe, yb, ye;
1844         float w, h;
1845         char text[32];
1846
1847         glDisable( GL_TEXTURE_2D );
1848         glDisable( GL_TEXTURE_1D );
1849         glDisable( GL_DEPTH_TEST );
1850         glDisable( GL_BLEND );
1851
1852         w = ( m_nWidth / 2 / m_fScale );
1853         h = ( m_nHeight / 2 / m_fScale );
1854
1855         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
1856         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
1857
1858         xb = m_vOrigin[nDim1] - w;
1859         if ( xb < region_mins[nDim1] ) {
1860                 xb = region_mins[nDim1];
1861         }
1862         xb = static_cast<float>( g_xywindow_globals_private.blockSize * floor( xb / g_xywindow_globals_private.blockSize ) );
1863
1864         xe = m_vOrigin[nDim1] + w;
1865         if ( xe > region_maxs[nDim1] ) {
1866                 xe = region_maxs[nDim1];
1867         }
1868         xe = static_cast<float>( g_xywindow_globals_private.blockSize * ceil( xe / g_xywindow_globals_private.blockSize ) );
1869
1870         yb = m_vOrigin[nDim2] - h;
1871         if ( yb < region_mins[nDim2] ) {
1872                 yb = region_mins[nDim2];
1873         }
1874         yb = static_cast<float>( g_xywindow_globals_private.blockSize * floor( yb / g_xywindow_globals_private.blockSize ) );
1875
1876         ye = m_vOrigin[nDim2] + h;
1877         if ( ye > region_maxs[nDim2] ) {
1878                 ye = region_maxs[nDim2];
1879         }
1880         ye = static_cast<float>( g_xywindow_globals_private.blockSize * ceil( ye / g_xywindow_globals_private.blockSize ) );
1881
1882         // draw major blocks
1883
1884         glColor3fv( vector3_to_array( g_xywindow_globals.color_gridblock ) );
1885         glLineWidth( 2 );
1886
1887         glBegin( GL_LINES );
1888
1889         for ( x = xb ; x <= xe ; x += g_xywindow_globals_private.blockSize )
1890         {
1891                 glVertex2f( x, yb );
1892                 glVertex2f( x, ye );
1893         }
1894
1895         if ( m_viewType == XY ) {
1896                 for ( y = yb ; y <= ye ; y += g_xywindow_globals_private.blockSize )
1897                 {
1898                         glVertex2f( xb, y );
1899                         glVertex2f( xe, y );
1900                 }
1901         }
1902
1903         glEnd();
1904         glLineWidth( 1 );
1905
1906         // draw coordinate text if needed
1907
1908         if ( m_viewType == XY && m_fScale > .1 ) {
1909                 for ( x = xb ; x < xe ; x += g_xywindow_globals_private.blockSize )
1910                         for ( y = yb ; y < ye ; y += g_xywindow_globals_private.blockSize )
1911                         {
1912                                 glRasterPos2f( x + ( g_xywindow_globals_private.blockSize / 2 ), y + ( g_xywindow_globals_private.blockSize / 2 ) );
1913                                 sprintf( text, "%i,%i",(int)floor( x / g_xywindow_globals_private.blockSize ), (int)floor( y / g_xywindow_globals_private.blockSize ) );
1914                                 GlobalOpenGL().drawString( text );
1915                         }
1916         }
1917
1918         glColor4f( 0, 0, 0, 0 );
1919 }
1920
1921 void XYWnd::DrawCameraIcon( const Vector3& origin, const Vector3& angles ){
1922         float x, y, fov, box;
1923         double a;
1924
1925         fov = 48 / m_fScale;
1926         box = 16 / m_fScale;
1927
1928         if ( m_viewType == XY ) {
1929                 x = origin[0];
1930                 y = origin[1];
1931                 a = degrees_to_radians( angles[CAMERA_YAW] );
1932         }
1933         else if ( m_viewType == YZ ) {
1934                 x = origin[1];
1935                 y = origin[2];
1936                 a = degrees_to_radians( angles[CAMERA_PITCH] );
1937         }
1938         else
1939         {
1940                 x = origin[0];
1941                 y = origin[2];
1942                 a = degrees_to_radians( angles[CAMERA_PITCH] );
1943         }
1944
1945         glColor3f( 0.0, 0.0, 1.0 );
1946         glBegin( GL_LINE_STRIP );
1947         glVertex3f( x - box,y,0 );
1948         glVertex3f( x,y + ( box / 2 ),0 );
1949         glVertex3f( x + box,y,0 );
1950         glVertex3f( x,y - ( box / 2 ),0 );
1951         glVertex3f( x - box,y,0 );
1952         glVertex3f( x + box,y,0 );
1953         glEnd();
1954
1955         glBegin( GL_LINE_STRIP );
1956         glVertex3f( x + static_cast<float>( fov * cos( a + c_pi / 4 ) ), y + static_cast<float>( fov * sin( a + c_pi / 4 ) ), 0 );
1957         glVertex3f( x, y, 0 );
1958         glVertex3f( x + static_cast<float>( fov * cos( a - c_pi / 4 ) ), y + static_cast<float>( fov * sin( a - c_pi / 4 ) ), 0 );
1959         glEnd();
1960
1961 }
1962
1963
1964 float Betwixt( float f1, float f2 ){
1965         if ( f1 > f2 ) {
1966                 return f2 + ( ( f1 - f2 ) / 2 );
1967         }
1968         else{
1969                 return f1 + ( ( f2 - f1 ) / 2 );
1970         }
1971 }
1972
1973
1974 // can be greatly simplified but per usual i am in a hurry
1975 // which is not an excuse, just a fact
1976 void XYWnd::PaintSizeInfo( int nDim1, int nDim2, Vector3& vMinBounds, Vector3& vMaxBounds ){
1977         if ( vector3_equal( vMinBounds, vMaxBounds ) ) {
1978                 return;
1979         }
1980         const char* g_pDimStrings[] = {"x:", "y:", "z:"};
1981         typedef const char* OrgStrings[2];
1982         const OrgStrings g_pOrgStrings[] = { { "x:", "y:", }, { "x:", "z:", }, { "y:", "z:", } };
1983
1984         Vector3 vSize( vector3_subtracted( vMaxBounds, vMinBounds ) );
1985
1986         glColor3f( g_xywindow_globals.color_selbrushes[0] * .65f,
1987                            g_xywindow_globals.color_selbrushes[1] * .65f,
1988                            g_xywindow_globals.color_selbrushes[2] * .65f );
1989
1990         StringOutputStream dimensions( 16 );
1991
1992         if ( m_viewType == XY ) {
1993                 glBegin( GL_LINES );
1994
1995                 glVertex3f( vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale, 0.0f );
1996                 glVertex3f( vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f );
1997
1998                 glVertex3f( vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale, 0.0f );
1999                 glVertex3f( vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale, 0.0f );
2000
2001                 glVertex3f( vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale, 0.0f );
2002                 glVertex3f( vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale, 0.0f );
2003
2004
2005                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, vMinBounds[nDim2], 0.0f );
2006                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2], 0.0f );
2007
2008                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2], 0.0f );
2009                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2], 0.0f );
2010
2011                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, vMaxBounds[nDim2], 0.0f );
2012                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2], 0.0f );
2013
2014                 glEnd();
2015
2016                 glRasterPos3f( Betwixt( vMinBounds[nDim1], vMaxBounds[nDim1] ),  vMinBounds[nDim2] - 20.0f  / m_fScale, 0.0f );
2017                 dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2018                 GlobalOpenGL().drawString( dimensions.c_str() );
2019                 dimensions.clear();
2020
2021                 glRasterPos3f( vMaxBounds[nDim1] + 16.0f  / m_fScale, Betwixt( vMinBounds[nDim2], vMaxBounds[nDim2] ), 0.0f );
2022                 dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2023                 GlobalOpenGL().drawString( dimensions.c_str() );
2024                 dimensions.clear();
2025
2026                 glRasterPos3f( vMinBounds[nDim1] + 4, vMaxBounds[nDim2] + 8 / m_fScale, 0.0f );
2027                 dimensions << "(" << g_pOrgStrings[0][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[0][1] << vMaxBounds[nDim2] << ")";
2028                 GlobalOpenGL().drawString( dimensions.c_str() );
2029         }
2030         else if ( m_viewType == XZ ) {
2031                 glBegin( GL_LINES );
2032
2033                 glVertex3f( vMinBounds[nDim1], 0, vMinBounds[nDim2] - 6.0f  / m_fScale );
2034                 glVertex3f( vMinBounds[nDim1], 0, vMinBounds[nDim2] - 10.0f / m_fScale );
2035
2036                 glVertex3f( vMinBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f  / m_fScale );
2037                 glVertex3f( vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f  / m_fScale );
2038
2039                 glVertex3f( vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 6.0f  / m_fScale );
2040                 glVertex3f( vMaxBounds[nDim1], 0,vMinBounds[nDim2] - 10.0f / m_fScale );
2041
2042
2043                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, 0,vMinBounds[nDim2] );
2044                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMinBounds[nDim2] );
2045
2046                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMinBounds[nDim2] );
2047                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMaxBounds[nDim2] );
2048
2049                 glVertex3f( vMaxBounds[nDim1] + 6.0f  / m_fScale, 0,vMaxBounds[nDim2] );
2050                 glVertex3f( vMaxBounds[nDim1] + 10.0f  / m_fScale, 0,vMaxBounds[nDim2] );
2051
2052                 glEnd();
2053
2054                 glRasterPos3f( Betwixt( vMinBounds[nDim1], vMaxBounds[nDim1] ), 0, vMinBounds[nDim2] - 20.0f  / m_fScale );
2055                 dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2056                 GlobalOpenGL().drawString( dimensions.c_str() );
2057                 dimensions.clear();
2058
2059                 glRasterPos3f( vMaxBounds[nDim1] + 16.0f  / m_fScale, 0, Betwixt( vMinBounds[nDim2], vMaxBounds[nDim2] ) );
2060                 dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2061                 GlobalOpenGL().drawString( dimensions.c_str() );
2062                 dimensions.clear();
2063
2064                 glRasterPos3f( vMinBounds[nDim1] + 4, 0, vMaxBounds[nDim2] + 8 / m_fScale );
2065                 dimensions << "(" << g_pOrgStrings[1][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[1][1] << vMaxBounds[nDim2] << ")";
2066                 GlobalOpenGL().drawString( dimensions.c_str() );
2067         }
2068         else
2069         {
2070                 glBegin( GL_LINES );
2071
2072                 glVertex3f( 0, vMinBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale );
2073                 glVertex3f( 0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale );
2074
2075                 glVertex3f( 0, vMinBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale );
2076                 glVertex3f( 0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f  / m_fScale );
2077
2078                 glVertex3f( 0, vMaxBounds[nDim1], vMinBounds[nDim2] - 6.0f  / m_fScale );
2079                 glVertex3f( 0, vMaxBounds[nDim1], vMinBounds[nDim2] - 10.0f / m_fScale );
2080
2081
2082                 glVertex3f( 0, vMaxBounds[nDim1] + 6.0f  / m_fScale, vMinBounds[nDim2] );
2083                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2] );
2084
2085                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMinBounds[nDim2] );
2086                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2] );
2087
2088                 glVertex3f( 0, vMaxBounds[nDim1] + 6.0f  / m_fScale, vMaxBounds[nDim2] );
2089                 glVertex3f( 0, vMaxBounds[nDim1] + 10.0f  / m_fScale, vMaxBounds[nDim2] );
2090
2091                 glEnd();
2092
2093                 glRasterPos3f( 0, Betwixt( vMinBounds[nDim1], vMaxBounds[nDim1] ),  vMinBounds[nDim2] - 20.0f  / m_fScale );
2094                 dimensions << g_pDimStrings[nDim1] << vSize[nDim1];
2095                 GlobalOpenGL().drawString( dimensions.c_str() );
2096                 dimensions.clear();
2097
2098                 glRasterPos3f( 0, vMaxBounds[nDim1] + 16.0f  / m_fScale, Betwixt( vMinBounds[nDim2], vMaxBounds[nDim2] ) );
2099                 dimensions << g_pDimStrings[nDim2] << vSize[nDim2];
2100                 GlobalOpenGL().drawString( dimensions.c_str() );
2101                 dimensions.clear();
2102
2103                 glRasterPos3f( 0, vMinBounds[nDim1] + 4.0f, vMaxBounds[nDim2] + 8 / m_fScale );
2104                 dimensions << "(" << g_pOrgStrings[2][0] << vMinBounds[nDim1] << "  " << g_pOrgStrings[2][1] << vMaxBounds[nDim2] << ")";
2105                 GlobalOpenGL().drawString( dimensions.c_str() );
2106         }
2107 }
2108
2109 class XYRenderer : public Renderer
2110 {
2111 struct state_type
2112 {
2113         state_type() :
2114                 m_highlight( 0 ),
2115                 m_state( 0 ){
2116         }
2117         unsigned int m_highlight;
2118         Shader* m_state;
2119 };
2120 public:
2121 XYRenderer( RenderStateFlags globalstate, Shader* selected ) :
2122         m_globalstate( globalstate ),
2123         m_state_selected( selected ){
2124         ASSERT_NOTNULL( selected );
2125         m_state_stack.push_back( state_type() );
2126 }
2127
2128 void SetState( Shader* state, EStyle style ){
2129         ASSERT_NOTNULL( state );
2130         if ( style == eWireframeOnly ) {
2131                 m_state_stack.back().m_state = state;
2132         }
2133 }
2134 const EStyle getStyle() const {
2135         return eWireframeOnly;
2136 }
2137 void PushState(){
2138         m_state_stack.push_back( m_state_stack.back() );
2139 }
2140 void PopState(){
2141         ASSERT_MESSAGE( !m_state_stack.empty(), "popping empty stack" );
2142         m_state_stack.pop_back();
2143 }
2144 void Highlight( EHighlightMode mode, bool bEnable = true ){
2145         ( bEnable )
2146         ? m_state_stack.back().m_highlight |= mode
2147                                                                                   : m_state_stack.back().m_highlight &= ~mode;
2148 }
2149 void addRenderable( const OpenGLRenderable& renderable, const Matrix4& localToWorld ){
2150         if ( m_state_stack.back().m_highlight & ePrimitive ) {
2151                 m_state_selected->addRenderable( renderable, localToWorld );
2152         }
2153         else
2154         {
2155                 m_state_stack.back().m_state->addRenderable( renderable, localToWorld );
2156         }
2157 }
2158
2159 void render( const Matrix4& modelview, const Matrix4& projection ){
2160         GlobalShaderCache().render( m_globalstate, modelview, projection );
2161 }
2162 private:
2163 std::vector<state_type> m_state_stack;
2164 RenderStateFlags m_globalstate;
2165 Shader* m_state_selected;
2166 };
2167
2168 void XYWnd::updateProjection(){
2169         m_projection[0] = 1.0f / static_cast<float>( m_nWidth / 2 );
2170         m_projection[5] = 1.0f / static_cast<float>( m_nHeight / 2 );
2171         m_projection[10] = 1.0f / ( g_MaxWorldCoord * m_fScale );
2172
2173         m_projection[12] = 0.0f;
2174         m_projection[13] = 0.0f;
2175         m_projection[14] = -1.0f;
2176
2177         m_projection[1] =
2178                 m_projection[2] =
2179                         m_projection[3] =
2180
2181                                 m_projection[4] =
2182                                         m_projection[6] =
2183                                                 m_projection[7] =
2184
2185                                                         m_projection[8] =
2186                                                                 m_projection[9] =
2187                                                                         m_projection[11] = 0.0f;
2188
2189         m_projection[15] = 1.0f;
2190
2191         m_view.Construct( m_projection, m_modelview, m_nWidth, m_nHeight );
2192 }
2193
2194 // note: modelview matrix must have a uniform scale, otherwise strange things happen when rendering the rotation manipulator.
2195 void XYWnd::updateModelview(){
2196         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
2197         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
2198
2199         // translation
2200         m_modelview[12] = -m_vOrigin[nDim1] * m_fScale;
2201         m_modelview[13] = -m_vOrigin[nDim2] * m_fScale;
2202         m_modelview[14] = g_MaxWorldCoord * m_fScale;
2203
2204         // axis base
2205         switch ( m_viewType )
2206         {
2207         case XY:
2208                 m_modelview[0]  =  m_fScale;
2209                 m_modelview[1]  =  0;
2210                 m_modelview[2]  =  0;
2211
2212                 m_modelview[4]  =  0;
2213                 m_modelview[5]  =  m_fScale;
2214                 m_modelview[6]  =  0;
2215
2216                 m_modelview[8]  =  0;
2217                 m_modelview[9]  =  0;
2218                 m_modelview[10] = -m_fScale;
2219                 break;
2220         case XZ:
2221                 m_modelview[0]  =  m_fScale;
2222                 m_modelview[1]  =  0;
2223                 m_modelview[2]  =  0;
2224
2225                 m_modelview[4]  =  0;
2226                 m_modelview[5]  =  0;
2227                 m_modelview[6]  =  m_fScale;
2228
2229                 m_modelview[8]  =  0;
2230                 m_modelview[9]  =  m_fScale;
2231                 m_modelview[10] =  0;
2232                 break;
2233         case YZ:
2234                 m_modelview[0]  =  0;
2235                 m_modelview[1]  =  0;
2236                 m_modelview[2]  = -m_fScale;
2237
2238                 m_modelview[4]  =  m_fScale;
2239                 m_modelview[5]  =  0;
2240                 m_modelview[6]  =  0;
2241
2242                 m_modelview[8]  =  0;
2243                 m_modelview[9]  =  m_fScale;
2244                 m_modelview[10] =  0;
2245                 break;
2246         }
2247
2248         m_modelview[3] = m_modelview[7] = m_modelview[11] = 0;
2249         m_modelview[15] = 1;
2250
2251         m_view.Construct( m_projection, m_modelview, m_nWidth, m_nHeight );
2252 }
2253
2254 /*
2255    ==============
2256    XY_Draw
2257    ==============
2258  */
2259
2260 //#define DBG_SCENEDUMP
2261
2262 void XYWnd::XY_Draw(){
2263         //
2264         // clear
2265         //
2266         glViewport( 0, 0, m_nWidth, m_nHeight );
2267         glClearColor( g_xywindow_globals.color_gridback[0],
2268                                   g_xywindow_globals.color_gridback[1],
2269                                   g_xywindow_globals.color_gridback[2],0 );
2270
2271         glClear( GL_COLOR_BUFFER_BIT );
2272
2273         //
2274         // set up viewpoint
2275         //
2276
2277         glMatrixMode( GL_PROJECTION );
2278         glLoadMatrixf( reinterpret_cast<const float*>( &m_projection ) );
2279
2280         glMatrixMode( GL_MODELVIEW );
2281         glLoadIdentity();
2282         glScalef( m_fScale, m_fScale, 1 );
2283         int nDim1 = ( m_viewType == YZ ) ? 1 : 0;
2284         int nDim2 = ( m_viewType == XY ) ? 1 : 2;
2285         glTranslatef( -m_vOrigin[nDim1], -m_vOrigin[nDim2], 0 );
2286
2287         glDisable( GL_LINE_STIPPLE );
2288         glLineWidth( 1 );
2289         glDisableClientState( GL_TEXTURE_COORD_ARRAY );
2290         glDisableClientState( GL_NORMAL_ARRAY );
2291         glDisableClientState( GL_COLOR_ARRAY );
2292         glDisable( GL_TEXTURE_2D );
2293         glDisable( GL_LIGHTING );
2294         glDisable( GL_COLOR_MATERIAL );
2295         glDisable( GL_DEPTH_TEST );
2296
2297         if ( m_backgroundActivated ) {
2298                 XY_DrawBackground();
2299         }
2300         XY_DrawGrid();
2301
2302         if ( g_xywindow_globals_private.show_blocks ) {
2303                 XY_DrawBlockGrid();
2304         }
2305
2306         glLoadMatrixf( reinterpret_cast<const float*>( &m_modelview ) );
2307
2308         unsigned int globalstate = RENDER_COLOURARRAY | RENDER_COLOURWRITE | RENDER_POLYGONSMOOTH | RENDER_LINESMOOTH;
2309         if ( !g_xywindow_globals.m_bNoStipple ) {
2310                 globalstate |= RENDER_LINESTIPPLE;
2311         }
2312
2313         {
2314                 XYRenderer renderer( globalstate, m_state_selected );
2315
2316                 Scene_Render( renderer, m_view );
2317
2318                 GlobalOpenGL_debugAssertNoErrors();
2319                 renderer.render( m_modelview, m_projection );
2320                 GlobalOpenGL_debugAssertNoErrors();
2321         }
2322
2323         glDepthMask( GL_FALSE );
2324
2325         GlobalOpenGL_debugAssertNoErrors();
2326
2327         glLoadMatrixf( reinterpret_cast<const float*>( &m_modelview ) );
2328
2329         GlobalOpenGL_debugAssertNoErrors();
2330         glDisable( GL_LINE_STIPPLE );
2331         GlobalOpenGL_debugAssertNoErrors();
2332         glLineWidth( 1 );
2333         GlobalOpenGL_debugAssertNoErrors();
2334         if ( GlobalOpenGL().GL_1_3() ) {
2335                 glActiveTexture( GL_TEXTURE0 );
2336                 glClientActiveTexture( GL_TEXTURE0 );
2337         }
2338         glDisableClientState( GL_TEXTURE_COORD_ARRAY );
2339         GlobalOpenGL_debugAssertNoErrors();
2340         glDisableClientState( GL_NORMAL_ARRAY );
2341         GlobalOpenGL_debugAssertNoErrors();
2342         glDisableClientState( GL_COLOR_ARRAY );
2343         GlobalOpenGL_debugAssertNoErrors();
2344         glDisable( GL_TEXTURE_2D );
2345         GlobalOpenGL_debugAssertNoErrors();
2346         glDisable( GL_LIGHTING );
2347         GlobalOpenGL_debugAssertNoErrors();
2348         glDisable( GL_COLOR_MATERIAL );
2349         GlobalOpenGL_debugAssertNoErrors();
2350
2351         GlobalOpenGL_debugAssertNoErrors();
2352
2353
2354         // size info
2355         if ( g_xywindow_globals_private.m_bSizePaint && GlobalSelectionSystem().countSelected() != 0 ) {
2356                 Vector3 min, max;
2357                 Select_GetBounds( min, max );
2358                 PaintSizeInfo( nDim1, nDim2, min, max );
2359         }
2360
2361         if ( g_bCrossHairs ) {
2362                 glColor4f( 0.2f, 0.9f, 0.2f, 0.8f );
2363                 glBegin( GL_LINES );
2364                 if ( m_viewType == XY ) {
2365                         glVertex2f( 2.0f * g_MinWorldCoord, m_mousePosition[1] );
2366                         glVertex2f( 2.0f * g_MaxWorldCoord, m_mousePosition[1] );
2367                         glVertex2f( m_mousePosition[0], 2.0f * g_MinWorldCoord );
2368                         glVertex2f( m_mousePosition[0], 2.0f * g_MaxWorldCoord );
2369                 }
2370                 else if ( m_viewType == YZ ) {
2371                         glVertex3f( m_mousePosition[0], 2.0f * g_MinWorldCoord, m_mousePosition[2] );
2372                         glVertex3f( m_mousePosition[0], 2.0f * g_MaxWorldCoord, m_mousePosition[2] );
2373                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord );
2374                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord );
2375                 }
2376                 else
2377                 {
2378                         glVertex3f( 2.0f * g_MinWorldCoord, m_mousePosition[1], m_mousePosition[2] );
2379                         glVertex3f( 2.0f * g_MaxWorldCoord, m_mousePosition[1], m_mousePosition[2] );
2380                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MinWorldCoord );
2381                         glVertex3f( m_mousePosition[0], m_mousePosition[1], 2.0f * g_MaxWorldCoord );
2382                 }
2383                 glEnd();
2384         }
2385
2386         if ( ClipMode() ) {
2387                 GlobalClipPoints_Draw( m_fScale );
2388         }
2389
2390         GlobalOpenGL_debugAssertNoErrors();
2391
2392         // reset modelview
2393         glLoadIdentity();
2394         glScalef( m_fScale, m_fScale, 1 );
2395         glTranslatef( -m_vOrigin[nDim1], -m_vOrigin[nDim2], 0 );
2396
2397         DrawCameraIcon( Camera_getOrigin( *g_pParentWnd->GetCamWnd() ), Camera_getAngles( *g_pParentWnd->GetCamWnd() ) );
2398
2399         Feedback_draw2D( m_viewType );
2400
2401         if ( g_xywindow_globals_private.show_outline ) {
2402                 if ( Active() ) {
2403                         glMatrixMode( GL_PROJECTION );
2404                         glLoadIdentity();
2405                         glOrtho( 0, m_nWidth, 0, m_nHeight, 0, 1 );
2406
2407                         glMatrixMode( GL_MODELVIEW );
2408                         glLoadIdentity();
2409
2410                         // four view mode doesn't colorize
2411                         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit ) {
2412                                 glColor3fv( vector3_to_array( g_xywindow_globals.color_viewname ) );
2413                         }
2414                         else
2415                         {
2416                                 switch ( m_viewType )
2417                                 {
2418                                 case YZ:
2419                                         glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorX ) );
2420                                         break;
2421                                 case XZ:
2422                                         glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorY ) );
2423                                         break;
2424                                 case XY:
2425                                         glColor3fv( vector3_to_array( g_xywindow_globals.AxisColorZ ) );
2426                                         break;
2427                                 }
2428                         }
2429                         glBegin( GL_LINE_LOOP );
2430                         glVertex2f( 0.5, 0.5 );
2431                         glVertex2f( m_nWidth - 0.5, 1 );
2432                         glVertex2f( m_nWidth - 0.5, m_nHeight - 0.5 );
2433                         glVertex2f( 0.5, m_nHeight - 0.5 );
2434                         glEnd();
2435                 }
2436         }
2437
2438         GlobalOpenGL_debugAssertNoErrors();
2439
2440         glFinish();
2441 }
2442
2443 void XYWnd_MouseToPoint( XYWnd* xywnd, int x, int y, Vector3& point ){
2444         xywnd->XY_ToPoint( x, y, point );
2445         xywnd->XY_SnapToGrid( point );
2446
2447         int nDim = ( xywnd->GetViewType() == XY ) ? 2 : ( xywnd->GetViewType() == YZ ) ? 0 : 1;
2448         float fWorkMid = float_mid( Select_getWorkZone().d_work_min[nDim], Select_getWorkZone().d_work_max[nDim] );
2449         point[nDim] = float_snapped( fWorkMid, GetGridSize() );
2450 }
2451
2452 void XYWnd::OnEntityCreate( const char* item ){
2453         StringOutputStream command;
2454         command << "entityCreate -class " << item;
2455         UndoableCommand undo( command.c_str() );
2456         Vector3 point;
2457         XYWnd_MouseToPoint( this, m_entityCreate_x, m_entityCreate_y, point );
2458         Entity_createFromSelection( item, point );
2459 }
2460
2461
2462
2463 void GetFocusPosition( Vector3& position ){
2464         if ( GlobalSelectionSystem().countSelected() != 0 ) {
2465                 Select_GetMid( position );
2466         }
2467         else
2468         {
2469                 position = Camera_getOrigin( *g_pParentWnd->GetCamWnd() );
2470         }
2471 }
2472
2473 void XYWnd_Focus( XYWnd* xywnd ){
2474         Vector3 position;
2475         GetFocusPosition( position );
2476         xywnd->PositionView( position );
2477 }
2478
2479 void XY_Split_Focus(){
2480         Vector3 position;
2481         GetFocusPosition( position );
2482         if ( g_pParentWnd->GetXYWnd() ) {
2483                 g_pParentWnd->GetXYWnd()->PositionView( position );
2484         }
2485         if ( g_pParentWnd->GetXZWnd() ) {
2486                 g_pParentWnd->GetXZWnd()->PositionView( position );
2487         }
2488         if ( g_pParentWnd->GetYZWnd() ) {
2489                 g_pParentWnd->GetYZWnd()->PositionView( position );
2490         }
2491 }
2492
2493 void XY_Focus(){
2494         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit ) {
2495                 // cannot do this in a split window
2496                 // do something else that the user may want here
2497                 XY_Split_Focus();
2498                 return;
2499         }
2500
2501         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2502         XYWnd_Focus( xywnd );
2503 }
2504
2505 void XY_Top(){
2506         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2507                 // cannot do this in a split window
2508                 // do something else that the user may want here
2509                 XY_Split_Focus();
2510                 return;
2511         }
2512
2513         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2514         xywnd->SetViewType( XY );
2515         XYWnd_Focus( xywnd );
2516 }
2517
2518 void XY_Side(){
2519         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2520                 // cannot do this in a split window
2521                 // do something else that the user may want here
2522                 XY_Split_Focus();
2523                 return;
2524         }
2525
2526         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2527         xywnd->SetViewType( XZ );
2528         XYWnd_Focus( xywnd );
2529 }
2530
2531 void XY_Front(){
2532         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2533                 // cannot do this in a split window
2534                 // do something else that the user may want here
2535                 XY_Split_Focus();
2536                 return;
2537         }
2538
2539         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2540         xywnd->SetViewType( YZ );
2541         XYWnd_Focus( xywnd );
2542 }
2543
2544 void XY_Next(){
2545         if ( g_pParentWnd->CurrentStyle() == MainFrame::eSplit || g_pParentWnd->CurrentStyle() == MainFrame::eFloating ) {
2546                 // cannot do this in a split window
2547                 // do something else that the user may want here
2548                 XY_Split_Focus();
2549                 return;
2550         }
2551
2552         XYWnd* xywnd = g_pParentWnd->GetXYWnd();
2553         if ( xywnd->GetViewType() == XY ) {
2554                 xywnd->SetViewType( XZ );
2555         }
2556         else if ( xywnd->GetViewType() ==  XZ ) {
2557                 xywnd->SetViewType( YZ );
2558         }
2559         else{
2560                 xywnd->SetViewType( XY );
2561         }
2562         XYWnd_Focus( xywnd );
2563 }
2564
2565 void XY_Zoom100(){
2566         if ( g_pParentWnd->GetXYWnd() ) {
2567                 g_pParentWnd->GetXYWnd()->SetScale( 1 );
2568         }
2569         if ( g_pParentWnd->GetXZWnd() ) {
2570                 g_pParentWnd->GetXZWnd()->SetScale( 1 );
2571         }
2572         if ( g_pParentWnd->GetYZWnd() ) {
2573                 g_pParentWnd->GetYZWnd()->SetScale( 1 );
2574         }
2575 }
2576
2577 void XY_ZoomIn(){
2578         g_pParentWnd->ActiveXY()->ZoomIn();
2579 }
2580
2581 // NOTE: the zoom out factor is 4/5, we could think about customizing it
2582 //  we don't go below a zoom factor corresponding to 10% of the max world size
2583 //  (this has to be computed against the window size)
2584 void XY_ZoomOut(){
2585         g_pParentWnd->ActiveXY()->ZoomOut();
2586 }
2587
2588
2589
2590 void ToggleShowCrosshair(){
2591         g_bCrossHairs ^= 1;
2592         XY_UpdateAllWindows();
2593 }
2594
2595 void ToggleShowSizeInfo(){
2596         g_xywindow_globals_private.m_bSizePaint = !g_xywindow_globals_private.m_bSizePaint;
2597         XY_UpdateAllWindows();
2598 }
2599
2600 void ToggleShowGrid(){
2601         g_xywindow_globals_private.d_showgrid = !g_xywindow_globals_private.d_showgrid;
2602         XY_UpdateAllWindows();
2603 }
2604
2605 ToggleShown g_xy_top_shown( true );
2606
2607 void XY_Top_Shown_Construct( GtkWindow* parent ){
2608         g_xy_top_shown.connect( GTK_WIDGET( parent ) );
2609 }
2610
2611 ToggleShown g_yz_side_shown( false );
2612
2613 void YZ_Side_Shown_Construct( GtkWindow* parent ){
2614         g_yz_side_shown.connect( GTK_WIDGET( parent ) );
2615 }
2616
2617 ToggleShown g_xz_front_shown( false );
2618
2619 void XZ_Front_Shown_Construct( GtkWindow* parent ){
2620         g_xz_front_shown.connect( GTK_WIDGET( parent ) );
2621 }
2622
2623
2624 class EntityClassMenu : public ModuleObserver
2625 {
2626 std::size_t m_unrealised;
2627 public:
2628 EntityClassMenu() : m_unrealised( 1 ){
2629 }
2630 void realise(){
2631         if ( --m_unrealised == 0 ) {
2632         }
2633 }
2634 void unrealise(){
2635         if ( ++m_unrealised == 1 ) {
2636                 if ( XYWnd::m_mnuDrop != 0 ) {
2637                         gtk_widget_destroy( GTK_WIDGET( XYWnd::m_mnuDrop ) );
2638                         XYWnd::m_mnuDrop = 0;
2639                 }
2640         }
2641 }
2642 };
2643
2644 EntityClassMenu g_EntityClassMenu;
2645
2646
2647
2648
2649 void ShowNamesToggle(){
2650         GlobalEntityCreator().setShowNames( !GlobalEntityCreator().getShowNames() );
2651         XY_UpdateAllWindows();
2652 }
2653 typedef FreeCaller<ShowNamesToggle> ShowNamesToggleCaller;
2654 void ShowNamesExport( const BoolImportCallback& importer ){
2655         importer( GlobalEntityCreator().getShowNames() );
2656 }
2657 typedef FreeCaller1<const BoolImportCallback&, ShowNamesExport> ShowNamesExportCaller;
2658
2659 void ShowAnglesToggle(){
2660         GlobalEntityCreator().setShowAngles( !GlobalEntityCreator().getShowAngles() );
2661         XY_UpdateAllWindows();
2662 }
2663 typedef FreeCaller<ShowAnglesToggle> ShowAnglesToggleCaller;
2664 void ShowAnglesExport( const BoolImportCallback& importer ){
2665         importer( GlobalEntityCreator().getShowAngles() );
2666 }
2667 typedef FreeCaller1<const BoolImportCallback&, ShowAnglesExport> ShowAnglesExportCaller;
2668
2669 void ShowBlocksToggle(){
2670         g_xywindow_globals_private.show_blocks ^= 1;
2671         XY_UpdateAllWindows();
2672 }
2673 typedef FreeCaller<ShowBlocksToggle> ShowBlocksToggleCaller;
2674 void ShowBlocksExport( const BoolImportCallback& importer ){
2675         importer( g_xywindow_globals_private.show_blocks );
2676 }
2677 typedef FreeCaller1<const BoolImportCallback&, ShowBlocksExport> ShowBlocksExportCaller;
2678
2679 void ShowCoordinatesToggle(){
2680         g_xywindow_globals_private.show_coordinates ^= 1;
2681         XY_UpdateAllWindows();
2682 }
2683 typedef FreeCaller<ShowCoordinatesToggle> ShowCoordinatesToggleCaller;
2684 void ShowCoordinatesExport( const BoolImportCallback& importer ){
2685         importer( g_xywindow_globals_private.show_coordinates );
2686 }
2687 typedef FreeCaller1<const BoolImportCallback&, ShowCoordinatesExport> ShowCoordinatesExportCaller;
2688
2689 void ShowOutlineToggle(){
2690         g_xywindow_globals_private.show_outline ^= 1;
2691         XY_UpdateAllWindows();
2692 }
2693 typedef FreeCaller<ShowOutlineToggle> ShowOutlineToggleCaller;
2694 void ShowOutlineExport( const BoolImportCallback& importer ){
2695         importer( g_xywindow_globals_private.show_outline );
2696 }
2697 typedef FreeCaller1<const BoolImportCallback&, ShowOutlineExport> ShowOutlineExportCaller;
2698
2699 void ShowAxesToggle(){
2700         g_xywindow_globals_private.show_axis ^= 1;
2701         XY_UpdateAllWindows();
2702 }
2703 typedef FreeCaller<ShowAxesToggle> ShowAxesToggleCaller;
2704 void ShowAxesExport( const BoolImportCallback& importer ){
2705         importer( g_xywindow_globals_private.show_axis );
2706 }
2707 typedef FreeCaller1<const BoolImportCallback&, ShowAxesExport> ShowAxesExportCaller;
2708
2709 void ShowWorkzoneToggle(){
2710         g_xywindow_globals_private.d_show_work ^= 1;
2711         XY_UpdateAllWindows();
2712 }
2713 typedef FreeCaller<ShowWorkzoneToggle> ShowWorkzoneToggleCaller;
2714 void ShowWorkzoneExport( const BoolImportCallback& importer ){
2715         importer( g_xywindow_globals_private.d_show_work );
2716 }
2717 typedef FreeCaller1<const BoolImportCallback&, ShowWorkzoneExport> ShowWorkzoneExportCaller;
2718
2719 ShowNamesExportCaller g_show_names_caller;
2720 BoolExportCallback g_show_names_callback( g_show_names_caller );
2721 ToggleItem g_show_names( g_show_names_callback );
2722
2723 ShowAnglesExportCaller g_show_angles_caller;
2724 BoolExportCallback g_show_angles_callback( g_show_angles_caller );
2725 ToggleItem g_show_angles( g_show_angles_callback );
2726
2727 ShowBlocksExportCaller g_show_blocks_caller;
2728 BoolExportCallback g_show_blocks_callback( g_show_blocks_caller );
2729 ToggleItem g_show_blocks( g_show_blocks_callback );
2730
2731 ShowCoordinatesExportCaller g_show_coordinates_caller;
2732 BoolExportCallback g_show_coordinates_callback( g_show_coordinates_caller );
2733 ToggleItem g_show_coordinates( g_show_coordinates_callback );
2734
2735 ShowOutlineExportCaller g_show_outline_caller;
2736 BoolExportCallback g_show_outline_callback( g_show_outline_caller );
2737 ToggleItem g_show_outline( g_show_outline_callback );
2738
2739 ShowAxesExportCaller g_show_axes_caller;
2740 BoolExportCallback g_show_axes_callback( g_show_axes_caller );
2741 ToggleItem g_show_axes( g_show_axes_callback );
2742
2743 ShowWorkzoneExportCaller g_show_workzone_caller;
2744 BoolExportCallback g_show_workzone_callback( g_show_workzone_caller );
2745 ToggleItem g_show_workzone( g_show_workzone_callback );
2746
2747 void XYShow_registerCommands(){
2748         GlobalToggles_insert( "ShowAngles", ShowAnglesToggleCaller(), ToggleItem::AddCallbackCaller( g_show_angles ) );
2749         GlobalToggles_insert( "ShowNames", ShowNamesToggleCaller(), ToggleItem::AddCallbackCaller( g_show_names ) );
2750         GlobalToggles_insert( "ShowBlocks", ShowBlocksToggleCaller(), ToggleItem::AddCallbackCaller( g_show_blocks ) );
2751         GlobalToggles_insert( "ShowCoordinates", ShowCoordinatesToggleCaller(), ToggleItem::AddCallbackCaller( g_show_coordinates ) );
2752         GlobalToggles_insert( "ShowWindowOutline", ShowOutlineToggleCaller(), ToggleItem::AddCallbackCaller( g_show_outline ) );
2753         GlobalToggles_insert( "ShowAxes", ShowAxesToggleCaller(), ToggleItem::AddCallbackCaller( g_show_axes ) );
2754         GlobalToggles_insert( "ShowWorkzone", ShowWorkzoneToggleCaller(), ToggleItem::AddCallbackCaller( g_show_workzone ) );
2755 }
2756
2757 void XYWnd_registerShortcuts(){
2758         command_connect_accelerator( "ToggleCrosshairs" );
2759         command_connect_accelerator( "ToggleSizePaint" );
2760 }
2761
2762
2763
2764 void Orthographic_constructPreferences( PreferencesPage& page ){
2765         page.appendCheckBox( "", "Solid selection boxes", g_xywindow_globals.m_bNoStipple );
2766         page.appendCheckBox( "", "Display size info", g_xywindow_globals_private.m_bSizePaint );
2767         page.appendCheckBox( "", "Chase mouse during drags", g_xywindow_globals_private.m_bChaseMouse );
2768         page.appendCheckBox( "", "Update views on camera move", g_xywindow_globals_private.m_bCamXYUpdate );
2769 }
2770 void Orthographic_constructPage( PreferenceGroup& group ){
2771         PreferencesPage page( group.createPage( "Orthographic", "Orthographic View Preferences" ) );
2772         Orthographic_constructPreferences( page );
2773 }
2774 void Orthographic_registerPreferencesPage(){
2775         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Orthographic_constructPage>() );
2776 }
2777
2778 void Clipper_constructPreferences( PreferencesPage& page ){
2779         page.appendCheckBox( "", "Clipper tool uses caulk", g_clip_useCaulk );
2780 }
2781 void Clipper_constructPage( PreferenceGroup& group ){
2782         PreferencesPage page( group.createPage( "Clipper", "Clipper Tool Settings" ) );
2783         Clipper_constructPreferences( page );
2784 }
2785 void Clipper_registerPreferencesPage(){
2786         PreferencesDialog_addSettingsPage( FreeCaller1<PreferenceGroup&, Clipper_constructPage>() );
2787 }
2788
2789
2790 #include "preferencesystem.h"
2791 #include "stringio.h"
2792
2793
2794
2795
2796 void ToggleShown_importBool( ToggleShown& self, bool value ){
2797         self.set( value );
2798 }
2799 typedef ReferenceCaller1<ToggleShown, bool, ToggleShown_importBool> ToggleShownImportBoolCaller;
2800 void ToggleShown_exportBool( const ToggleShown& self, const BoolImportCallback& importer ){
2801         importer( self.active() );
2802 }
2803 typedef ConstReferenceCaller1<ToggleShown, const BoolImportCallback&, ToggleShown_exportBool> ToggleShownExportBoolCaller;
2804
2805
2806 void XYWindow_Construct(){
2807         GlobalCommands_insert( "ToggleCrosshairs", FreeCaller<ToggleShowCrosshair>(), Accelerator( 'X', (GdkModifierType)GDK_SHIFT_MASK ) );
2808         GlobalCommands_insert( "ToggleSizePaint", FreeCaller<ToggleShowSizeInfo>(), Accelerator( 'J' ) );
2809         GlobalCommands_insert( "ToggleGrid", FreeCaller<ToggleShowGrid>(), Accelerator( '0' ) );
2810
2811         GlobalToggles_insert( "ToggleView", ToggleShown::ToggleCaller( g_xy_top_shown ), ToggleItem::AddCallbackCaller( g_xy_top_shown.m_item ), Accelerator( 'V', (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
2812         GlobalToggles_insert( "ToggleSideView", ToggleShown::ToggleCaller( g_yz_side_shown ), ToggleItem::AddCallbackCaller( g_yz_side_shown.m_item ) );
2813         GlobalToggles_insert( "ToggleFrontView", ToggleShown::ToggleCaller( g_xz_front_shown ), ToggleItem::AddCallbackCaller( g_xz_front_shown.m_item ) );
2814         GlobalCommands_insert( "NextView", FreeCaller<XY_Next>(), Accelerator( GDK_Tab, (GdkModifierType)GDK_CONTROL_MASK ) );
2815         GlobalCommands_insert( "ZoomIn", FreeCaller<XY_ZoomIn>(), Accelerator( GDK_Delete ) );
2816         GlobalCommands_insert( "ZoomOut", FreeCaller<XY_ZoomOut>(), Accelerator( GDK_Insert ) );
2817         GlobalCommands_insert( "ViewTop", FreeCaller<XY_Top>(), Accelerator( GDK_KP_Home ) );
2818         GlobalCommands_insert( "ViewSide", FreeCaller<XY_Side>(), Accelerator( GDK_KP_Page_Down ) );
2819         GlobalCommands_insert( "ViewFront", FreeCaller<XY_Front>(), Accelerator( GDK_KP_End ) );
2820         GlobalCommands_insert( "Zoom100", FreeCaller<XY_Zoom100>() );
2821         GlobalCommands_insert( "CenterXYView", FreeCaller<XY_Focus>(), Accelerator( GDK_Tab, (GdkModifierType)( GDK_SHIFT_MASK | GDK_CONTROL_MASK ) ) );
2822
2823         GlobalPreferenceSystem().registerPreference( "ClipCaulk", BoolImportStringCaller( g_clip_useCaulk ), BoolExportStringCaller( g_clip_useCaulk ) );
2824
2825         GlobalPreferenceSystem().registerPreference( "NewRightClick", BoolImportStringCaller( g_xywindow_globals.m_bRightClick ), BoolExportStringCaller( g_xywindow_globals.m_bRightClick ) );
2826         GlobalPreferenceSystem().registerPreference( "ImprovedWheelZoom", BoolImportStringCaller( g_xywindow_globals.m_bImprovedWheelZoom ), BoolExportStringCaller( g_xywindow_globals.m_bImprovedWheelZoom ) );
2827         GlobalPreferenceSystem().registerPreference( "ChaseMouse", BoolImportStringCaller( g_xywindow_globals_private.m_bChaseMouse ), BoolExportStringCaller( g_xywindow_globals_private.m_bChaseMouse ) );
2828         GlobalPreferenceSystem().registerPreference( "SizePainting", BoolImportStringCaller( g_xywindow_globals_private.m_bSizePaint ), BoolExportStringCaller( g_xywindow_globals_private.m_bSizePaint ) );
2829         GlobalPreferenceSystem().registerPreference( "ShowCrosshair", BoolImportStringCaller( g_bCrossHairs ), BoolExportStringCaller( g_bCrossHairs ) );
2830         GlobalPreferenceSystem().registerPreference( "NoStipple", BoolImportStringCaller( g_xywindow_globals.m_bNoStipple ), BoolExportStringCaller( g_xywindow_globals.m_bNoStipple ) );
2831         GlobalPreferenceSystem().registerPreference( "SI_ShowCoords", BoolImportStringCaller( g_xywindow_globals_private.show_coordinates ), BoolExportStringCaller( g_xywindow_globals_private.show_coordinates ) );
2832         GlobalPreferenceSystem().registerPreference( "SI_ShowOutlines", BoolImportStringCaller( g_xywindow_globals_private.show_outline ), BoolExportStringCaller( g_xywindow_globals_private.show_outline ) );
2833         GlobalPreferenceSystem().registerPreference( "SI_ShowAxis", BoolImportStringCaller( g_xywindow_globals_private.show_axis ), BoolExportStringCaller( g_xywindow_globals_private.show_axis ) );
2834         GlobalPreferenceSystem().registerPreference( "CamXYUpdate", BoolImportStringCaller( g_xywindow_globals_private.m_bCamXYUpdate ), BoolExportStringCaller( g_xywindow_globals_private.m_bCamXYUpdate ) );
2835         GlobalPreferenceSystem().registerPreference( "ShowWorkzone", BoolImportStringCaller( g_xywindow_globals_private.d_show_work ), BoolExportStringCaller( g_xywindow_globals_private.d_show_work ) );
2836
2837         GlobalPreferenceSystem().registerPreference( "SI_AxisColors0", Vector3ImportStringCaller( g_xywindow_globals.AxisColorX ), Vector3ExportStringCaller( g_xywindow_globals.AxisColorX ) );
2838         GlobalPreferenceSystem().registerPreference( "SI_AxisColors1", Vector3ImportStringCaller( g_xywindow_globals.AxisColorY ), Vector3ExportStringCaller( g_xywindow_globals.AxisColorY ) );
2839         GlobalPreferenceSystem().registerPreference( "SI_AxisColors2", Vector3ImportStringCaller( g_xywindow_globals.AxisColorZ ), Vector3ExportStringCaller( g_xywindow_globals.AxisColorZ ) );
2840         GlobalPreferenceSystem().registerPreference( "SI_Colors1", Vector3ImportStringCaller( g_xywindow_globals.color_gridback ), Vector3ExportStringCaller( g_xywindow_globals.color_gridback ) );
2841         GlobalPreferenceSystem().registerPreference( "SI_Colors2", Vector3ImportStringCaller( g_xywindow_globals.color_gridminor ), Vector3ExportStringCaller( g_xywindow_globals.color_gridminor ) );
2842         GlobalPreferenceSystem().registerPreference( "SI_Colors3", Vector3ImportStringCaller( g_xywindow_globals.color_gridmajor ), Vector3ExportStringCaller( g_xywindow_globals.color_gridmajor ) );
2843         GlobalPreferenceSystem().registerPreference( "SI_Colors6", Vector3ImportStringCaller( g_xywindow_globals.color_gridblock ), Vector3ExportStringCaller( g_xywindow_globals.color_gridblock ) );
2844         GlobalPreferenceSystem().registerPreference( "SI_Colors7", Vector3ImportStringCaller( g_xywindow_globals.color_gridtext ), Vector3ExportStringCaller( g_xywindow_globals.color_gridtext ) );
2845         GlobalPreferenceSystem().registerPreference( "SI_Colors8", Vector3ImportStringCaller( g_xywindow_globals.color_brushes ), Vector3ExportStringCaller( g_xywindow_globals.color_brushes ) );
2846         GlobalPreferenceSystem().registerPreference( "SI_Colors14", Vector3ImportStringCaller( g_xywindow_globals.color_gridmajor_alt ), Vector3ExportStringCaller( g_xywindow_globals.color_gridmajor_alt ) );
2847
2848
2849         GlobalPreferenceSystem().registerPreference( "XZVIS", makeBoolStringImportCallback( ToggleShownImportBoolCaller( g_xz_front_shown ) ), makeBoolStringExportCallback( ToggleShownExportBoolCaller( g_xz_front_shown ) ) );
2850         GlobalPreferenceSystem().registerPreference( "YZVIS", makeBoolStringImportCallback( ToggleShownImportBoolCaller( g_yz_side_shown ) ), makeBoolStringExportCallback( ToggleShownExportBoolCaller( g_yz_side_shown ) ) );
2851
2852         Orthographic_registerPreferencesPage();
2853         Clipper_registerPreferencesPage();
2854
2855         XYWnd::captureStates();
2856         GlobalEntityClassManager().attach( g_EntityClassMenu );
2857 }
2858
2859 void XYWindow_Destroy(){
2860         GlobalEntityClassManager().detach( g_EntityClassMenu );
2861         XYWnd::releaseStates();
2862 }