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