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