]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/brush.h
cleaned up duplicated doom3 light_radius default value
[xonotic/netradiant.git] / radiant / brush.h
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 #if !defined(INCLUDED_BRUSH_H)
23 #define INCLUDED_BRUSH_H
24
25 /// \file
26 /// \brief The brush primitive.
27 ///
28 /// A collection of planes that define a convex polyhedron.
29 /// The Boundary-Representation of this primitive is a manifold polygonal mesh.
30 /// Each face polygon is represented by a list of vertices in a \c Winding.
31 /// Each vertex is associated with another face that is adjacent to the edge
32 /// formed by itself and the next vertex in the winding. This information can
33 /// be used to find edge-pairs and vertex-rings.
34
35
36 #include "debugging/debugging.h"
37
38 #include "itexdef.h"
39 #include "iundo.h"
40 #include "iselection.h"
41 #include "irender.h"
42 #include "imap.h"
43 #include "ibrush.h"
44 #include "igl.h"
45 #include "ifilter.h"
46 #include "nameable.h"
47 #include "moduleobserver.h"
48
49 #include <set>
50
51 #include "cullable.h"
52 #include "renderable.h"
53 #include "selectable.h"
54 #include "editable.h"
55 #include "mapfile.h"
56
57 #include "math/frustum.h"
58 #include "selectionlib.h"
59 #include "render.h"
60 #include "texturelib.h"
61 #include "container/container.h"
62 #include "generic/bitfield.h"
63 #include "signal/signalfwd.h"
64
65 #include "winding.h"
66 #include "brush_primit.h"
67
68 #define CONTENTS_DETAIL 0x8000000
69
70
71 enum EBrushType
72 {
73   eBrushTypeQuake,
74   eBrushTypeQuake2,
75   eBrushTypeQuake3,
76   eBrushTypeQuake3BP,
77   eBrushTypeDoom3,
78   eBrushTypeQuake4,
79   eBrushTypeHalfLife,
80 };
81
82
83 #define BRUSH_CONNECTIVITY_DEBUG 0
84 #define BRUSH_DEGENERATE_DEBUG 0
85
86 template<typename TextOuputStreamType>
87 inline TextOuputStreamType& ostream_write(TextOuputStreamType& ostream, const Matrix4& m)
88 {
89   return ostream << "(" << m[0] << " " << m[1] << " " << m[2] << " " << m[3] << ", "
90     << m[4] << " " << m[5] << " " << m[6] << " " << m[7] << ", "
91     << m[8] << " " << m[9] << " " << m[10] << " " << m[11] << ", "
92     << m[12] << " " << m[13] << " " << m[14] << " " << m[15] << ")";
93 }
94
95 inline void print_vector3(const Vector3& v)
96 {
97   globalOutputStream() << "( " << v.x() << " " << v.y() << " " << v.z() << " )\n";
98 }
99
100 inline void print_3x3(const Matrix4& m)
101 {
102   globalOutputStream() << "( " << m.xx() << " " << m.xy() << " " << m.xz() << " ) "
103     << "( " << m.yx() << " " << m.yy() << " " << m.yz() << " ) "
104     << "( " << m.zx() << " " << m.zy() << " " << m.zz() << " )\n";
105 }
106
107
108
109 inline bool texdef_sane(const texdef_t& texdef)
110 {
111   return fabs(texdef.shift[0]) < (1 << 16)
112     && fabs(texdef.shift[1]) < (1 << 16);
113 }
114
115 inline void Winding_DrawWireframe(const Winding& winding)
116 {
117   glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex);
118   glDrawArrays(GL_LINE_LOOP, 0, GLsizei(winding.numpoints));
119 }
120
121 inline void Winding_Draw(const Winding& winding, const Vector3& normal, RenderStateFlags state)
122 {
123   glVertexPointer(3, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->vertex);
124
125   if((state & RENDER_BUMP) != 0)
126   {
127     Vector3 normals[c_brush_maxFaces];
128     typedef Vector3* Vector3Iter;
129     for(Vector3Iter i = normals, end = normals + winding.numpoints; i != end; ++i)
130     {
131       *i = normal;
132     }
133     if(GlobalShaderCache().useShaderLanguage())
134     {
135       glNormalPointer(GL_FLOAT, sizeof(Vector3), normals);
136       glVertexAttribPointerARB(c_attr_TexCoord0, 2, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->texcoord);
137       glVertexAttribPointerARB(c_attr_Tangent, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->tangent);
138       glVertexAttribPointerARB(c_attr_Binormal, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->bitangent);
139     }
140     else
141     {
142       glVertexAttribPointerARB(11, 3, GL_FLOAT, 0, sizeof(Vector3), normals);
143       glVertexAttribPointerARB(8, 2, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->texcoord);
144       glVertexAttribPointerARB(9, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->tangent);
145       glVertexAttribPointerARB(10, 3, GL_FLOAT, 0, sizeof(WindingVertex), &winding.points.data()->bitangent);
146     }
147   }
148   else
149   {
150     if (state & RENDER_LIGHTING)
151     {
152       Vector3 normals[c_brush_maxFaces];
153       typedef Vector3* Vector3Iter;
154       for(Vector3Iter i = normals, last = normals + winding.numpoints; i != last; ++i)
155       {
156         *i = normal;
157       }
158       glNormalPointer(GL_FLOAT, sizeof(Vector3), normals);
159     }
160
161     if (state & RENDER_TEXTURE)
162     {
163       glTexCoordPointer(2, GL_FLOAT, sizeof(WindingVertex), &winding.points.data()->texcoord);
164     }
165   }
166 #if 0
167   if (state & RENDER_FILL)
168   {
169     glDrawArrays(GL_TRIANGLE_FAN, 0, GLsizei(winding.numpoints));
170   }
171   else
172   {
173     glDrawArrays(GL_LINE_LOOP, 0, GLsizei(winding.numpoints));
174   }
175 #else
176   glDrawArrays(GL_POLYGON, 0, GLsizei(winding.numpoints));
177 #endif
178
179 #if 0
180   const Winding& winding = winding;
181
182   if(state & RENDER_FILL)
183   {
184     glBegin(GL_POLYGON);
185   }
186   else
187   {
188     glBegin(GL_LINE_LOOP);
189   }
190
191   if (state & RENDER_LIGHTING)
192     glNormal3fv(normal);
193
194   for(int i = 0; i < winding.numpoints; ++i)
195   {
196     if (state & RENDER_TEXTURE)
197       glTexCoord2fv(&winding.points[i][3]);
198     glVertex3fv(winding.points[i]);
199   }
200   glEnd();
201 #endif
202 }
203
204 const Colour4b colour_vertex(0, 255, 0, 255);
205
206
207 #include "shaderlib.h"
208
209 typedef DoubleVector3 PlanePoints[3];
210
211 inline bool planepts_equal(const PlanePoints planepts, const PlanePoints other)
212 {
213   return planepts[0] == other[0] && planepts[1] == other[1] && planepts[2] == other[2];
214 }
215
216 inline void planepts_assign(PlanePoints planepts, const PlanePoints other)
217 {
218   planepts[0] = other[0];
219   planepts[1] = other[1];
220   planepts[2] = other[2];
221 }
222
223 inline void planepts_quantise(PlanePoints planepts, double snap)
224 {
225   vector3_snap(planepts[0], snap);
226   vector3_snap(planepts[1], snap);
227   vector3_snap(planepts[2], snap);
228 }
229
230 inline float vector3_max_component(const Vector3& vec3)
231 {
232   return std::max(fabsf(vec3[0]), std::max(fabsf(vec3[1]), fabsf(vec3[2])));
233 }
234
235 inline void edge_snap(Vector3& edge, double snap)
236 {
237   float scale = static_cast<float>(ceil(fabs(snap / vector3_max_component(edge))));
238   if(scale > 0.0f)
239   {
240     vector3_scale(edge, scale);
241   }
242   vector3_snap(edge, snap);
243 }
244
245 inline void planepts_snap(PlanePoints planepts, double snap)
246 {
247   Vector3 edge01(vector3_subtracted(planepts[1], planepts[0]));
248   Vector3 edge12(vector3_subtracted(planepts[2], planepts[1]));
249   Vector3 edge20(vector3_subtracted(planepts[0], planepts[2]));
250
251   double length_squared_01 = vector3_dot(edge01, edge01);
252   double length_squared_12 = vector3_dot(edge12, edge12);
253   double length_squared_20 = vector3_dot(edge20, edge20);
254
255   vector3_snap(planepts[0], snap);
256
257   if(length_squared_01 < length_squared_12)
258   {
259     if(length_squared_12 < length_squared_20)
260     {
261       edge_snap(edge01, snap);
262       edge_snap(edge12, snap);
263       planepts[1] = vector3_added(planepts[0], edge01);
264       planepts[2] = vector3_added(planepts[1], edge12);
265     }
266     else
267     {
268       edge_snap(edge20, snap);
269       edge_snap(edge01, snap);
270       planepts[1] = vector3_added(planepts[0], edge20);
271       planepts[2] = vector3_added(planepts[1], edge01);
272     }
273   }
274   else
275   {
276     if(length_squared_01 < length_squared_20)
277     {
278       edge_snap(edge01, snap);
279       edge_snap(edge12, snap);
280       planepts[1] = vector3_added(planepts[0], edge01);
281       planepts[2] = vector3_added(planepts[1], edge12);
282     }
283     else
284     {
285       edge_snap(edge12, snap);
286       edge_snap(edge20, snap);
287       planepts[1] = vector3_added(planepts[0], edge12);
288       planepts[2] = vector3_added(planepts[1], edge20);
289     }
290   }
291 }
292
293 inline PointVertex pointvertex_for_planept(const DoubleVector3& point, const Colour4b& colour)
294 {
295   return PointVertex(
296     Vertex3f(
297       static_cast<float>(point.x()),
298       static_cast<float>(point.y()),
299       static_cast<float>(point.z())
300     ),
301     colour
302   );
303 }
304
305 inline PointVertex pointvertex_for_windingpoint(const Vector3& point, const Colour4b& colour)
306 {
307   return PointVertex(
308     vertex3f_for_vector3(point),
309     colour
310   );
311 }
312
313 inline bool check_plane_is_integer(const PlanePoints& planePoints)
314 {
315   return !float_is_integer(planePoints[0][0])
316     || !float_is_integer(planePoints[0][1])
317     || !float_is_integer(planePoints[0][2])
318     || !float_is_integer(planePoints[1][0])
319     || !float_is_integer(planePoints[1][1])
320     || !float_is_integer(planePoints[1][2])
321     || !float_is_integer(planePoints[2][0])
322     || !float_is_integer(planePoints[2][1])
323     || !float_is_integer(planePoints[2][2]);
324 }
325
326 inline void brush_check_shader(const char* name)
327 {
328   if(!shader_valid(name))
329   {
330     globalErrorStream() << "brush face has invalid texture name: '" << name << "'\n";
331   }
332 }
333
334 class FaceShaderObserver
335 {
336 public:
337   virtual void realiseShader() = 0;
338   virtual void unrealiseShader() = 0;
339 };
340
341 class FaceShaderObserverRealise
342 {
343 public:
344   void operator()(FaceShaderObserver& observer) const
345   {
346     observer.realiseShader();
347   }
348 };
349
350 class FaceShaderObserverUnrealise
351 {
352 public:
353   void operator()(FaceShaderObserver& observer) const
354   {
355     observer.unrealiseShader();
356   }
357 };
358
359 typedef ReferencePair<FaceShaderObserver> FaceShaderObserverPair;
360
361
362 class ContentsFlagsValue
363 {
364 public:
365   ContentsFlagsValue()
366   {
367   }
368   ContentsFlagsValue(int surfaceFlags, int contentFlags, int value, bool specified) :
369     m_surfaceFlags(surfaceFlags),
370     m_contentFlags(contentFlags),
371     m_value(value),
372     m_specified(specified)
373   {
374   }
375   int m_surfaceFlags;
376   int m_contentFlags;
377   int m_value;
378   bool m_specified;
379 };
380
381 inline unsigned int ContentFlags_assignable(unsigned int contentFlags)
382 {
383   return contentFlags & ~CONTENTS_DETAIL;
384 }
385
386 inline ContentsFlagsValue ContentsFlagsValue_maskDetail(const ContentsFlagsValue& other)
387 {
388   return ContentsFlagsValue(other.m_surfaceFlags, ContentFlags_assignable(other.m_contentFlags), other.m_value, other.m_specified);
389 }
390
391
392 class FaceShader : public ModuleObserver
393 {
394 public:
395   class SavedState
396   {
397   public:
398     CopiedString m_shader;
399     ContentsFlagsValue m_flags;
400
401     SavedState(const FaceShader& faceShader)
402     {
403       m_shader = faceShader.getShader();
404       m_flags = faceShader.m_flags;
405     }
406
407     void exportState(FaceShader& faceShader) const
408     {
409       faceShader.setShader(m_shader.c_str());
410       faceShader.setFlags(m_flags);
411     }
412   };
413
414   CopiedString m_shader;
415   Shader* m_state;
416   ContentsFlagsValue m_flags;
417   FaceShaderObserverPair m_observers;
418   bool m_instanced;
419   bool m_realised;
420
421   FaceShader(const char* shader, const ContentsFlagsValue& flags = ContentsFlagsValue(0, 0, 0, false)) :
422     m_shader(shader),
423     m_state(0),
424     m_flags(flags),
425     m_instanced(false),
426     m_realised(false)
427   {
428     captureShader();
429   }
430   ~FaceShader()
431   {
432     releaseShader();
433   }
434   // copy-construction not supported
435   FaceShader(const FaceShader& other);
436
437   void instanceAttach()
438   {
439     m_instanced = true;
440     m_state->incrementUsed();
441   }
442   void instanceDetach()
443   {
444     m_state->decrementUsed();
445     m_instanced = false;
446   }
447
448   void captureShader()
449   {
450     ASSERT_MESSAGE(m_state == 0, "shader cannot be captured");
451     brush_check_shader(m_shader.c_str());
452     m_state = GlobalShaderCache().capture(m_shader.c_str());
453     m_state->attach(*this);
454   }
455   void releaseShader()
456   {
457     ASSERT_MESSAGE(m_state != 0, "shader cannot be released");
458     m_state->detach(*this);
459     GlobalShaderCache().release(m_shader.c_str());
460     m_state = 0;
461   }
462
463   void realise()
464   {
465     ASSERT_MESSAGE(!m_realised, "FaceTexdef::realise: already realised");
466     m_realised = true;
467     m_observers.forEach(FaceShaderObserverRealise());
468   }
469   void unrealise()
470   {
471     ASSERT_MESSAGE(m_realised, "FaceTexdef::unrealise: already unrealised");
472     m_observers.forEach(FaceShaderObserverUnrealise());
473     m_realised = false;
474   }
475
476   void attach(FaceShaderObserver& observer)
477   {
478     m_observers.attach(observer);
479     if(m_realised)
480     {
481       observer.realiseShader();
482     }
483   }
484
485   void detach(FaceShaderObserver& observer)
486   {
487     if(m_realised)
488     {
489       observer.unrealiseShader();
490     }
491     m_observers.detach(observer);
492   }
493
494   const char* getShader() const
495   {
496     return m_shader.c_str();
497   }
498   void setShader(const char* name)
499   {
500     if(m_instanced)
501     {
502       m_state->decrementUsed();
503     }
504     releaseShader();
505     m_shader = name;
506     captureShader();
507     if(m_instanced)
508     {
509       m_state->incrementUsed();
510     }
511   }
512   ContentsFlagsValue getFlags() const
513   {
514     ASSERT_MESSAGE(m_realised, "FaceShader::getFlags: flags not valid when unrealised");
515     if(!m_flags.m_specified)
516     {
517       return ContentsFlagsValue(
518         m_state->getTexture().surfaceFlags,
519         m_state->getTexture().contentFlags,
520         m_state->getTexture().value,
521         true
522       );
523     }
524     return m_flags;
525   }
526   void setFlags(const ContentsFlagsValue& flags)
527   {
528     ASSERT_MESSAGE(m_realised, "FaceShader::setFlags: flags not valid when unrealised");
529     m_flags = ContentsFlagsValue_maskDetail(flags);
530   }
531
532   Shader* state() const
533   {
534     return m_state;
535   }
536
537   std::size_t width() const
538   {
539     if(m_realised)
540     {
541       return m_state->getTexture().width;
542     }
543     return 1;
544   }
545   std::size_t height() const
546   {
547     if(m_realised)
548     {
549       return m_state->getTexture().height;
550     }
551     return 1;
552   }
553   unsigned int shaderFlags() const
554   {
555     if(m_realised)
556     {
557       return m_state->getFlags();
558     }
559     return 0;
560   }
561 };
562
563
564
565
566 class FaceTexdef : public FaceShaderObserver
567 {
568   // not copyable
569   FaceTexdef(const FaceTexdef& other);
570   // not assignable
571   FaceTexdef& operator=(const FaceTexdef& other);
572 public:
573   class SavedState
574   {
575   public:
576     TextureProjection m_projection;
577
578     SavedState(const FaceTexdef& faceTexdef)
579     {
580       m_projection = faceTexdef.m_projection;
581     }
582
583     void exportState(FaceTexdef& faceTexdef) const
584     {
585       Texdef_Assign(faceTexdef.m_projection, m_projection);
586     }
587   };
588
589   FaceShader& m_shader;
590   TextureProjection m_projection;
591   bool m_projectionInitialised;
592   bool m_scaleApplied;
593
594   FaceTexdef(
595     FaceShader& shader,
596     const TextureProjection& projection,
597     bool projectionInitialised = true
598   ) :
599     m_shader(shader),
600     m_projection(projection),
601     m_projectionInitialised(projectionInitialised),
602     m_scaleApplied(false)
603   {
604     m_shader.attach(*this);
605   }
606   ~FaceTexdef()
607   {
608     m_shader.detach(*this);
609   }
610
611   void addScale()
612   {
613     ASSERT_MESSAGE(!m_scaleApplied, "texture scale aready added");
614     m_scaleApplied = true;
615     m_projection.m_brushprimit_texdef.addScale(m_shader.width(), m_shader.height());
616   }
617   void removeScale()
618   {
619     ASSERT_MESSAGE(m_scaleApplied, "texture scale aready removed");
620     m_scaleApplied = false;
621     m_projection.m_brushprimit_texdef.removeScale(m_shader.width(), m_shader.height());
622   }
623
624   void realiseShader()
625   {
626     if(m_projectionInitialised && !m_scaleApplied)
627     {
628       addScale();
629     }
630   }
631   void unrealiseShader()
632   {
633     if(m_projectionInitialised && m_scaleApplied)
634     {
635       removeScale();
636     }
637   }
638
639   void setTexdef(const TextureProjection& projection)
640   {
641     removeScale();
642     Texdef_Assign(m_projection, projection);
643     addScale();
644   }
645
646   void shift(float s, float t)
647   {
648     ASSERT_MESSAGE(texdef_sane(m_projection.m_texdef), "FaceTexdef::shift: bad texdef");
649     removeScale();
650     Texdef_Shift(m_projection, s, t);
651     addScale();
652   }
653
654   void scale(float s, float t)
655   {
656     removeScale();
657     Texdef_Scale(m_projection, s, t);
658     addScale();
659   }
660
661   void rotate(float angle)
662   {
663     removeScale();
664     Texdef_Rotate(m_projection, angle);
665     addScale();
666   }
667
668   void fit(const Vector3& normal, const Winding& winding, float s_repeat, float t_repeat)
669   {
670     Texdef_FitTexture(m_projection, m_shader.width(), m_shader.height(), normal, winding, s_repeat, t_repeat);
671   }
672
673   void emitTextureCoordinates(Winding& winding, const Vector3& normal, const Matrix4& localToWorld)
674   {
675     Texdef_EmitTextureCoordinates(m_projection, m_shader.width(), m_shader.height(), winding, normal, localToWorld);
676   }
677
678   void transform(const Plane3& plane, const Matrix4& matrix)
679   {
680     removeScale();
681     Texdef_transformLocked(m_projection, m_shader.width(), m_shader.height(), plane, matrix);
682     addScale();
683   }
684
685   TextureProjection normalised() const
686   {
687     brushprimit_texdef_t tmp(m_projection.m_brushprimit_texdef);
688     tmp.removeScale(m_shader.width(), m_shader.height());
689     return TextureProjection(m_projection.m_texdef, tmp, m_projection.m_basis_s, m_projection.m_basis_t);
690   }
691   void setBasis(const Vector3& normal)
692   {
693     Matrix4 basis;
694     Normal_GetTransform(normal, basis);
695     m_projection.m_basis_s = Vector3(basis.xx(), basis.yx(), basis.zx());
696     m_projection.m_basis_t = Vector3(-basis.xy(), -basis.yy(), -basis.zy());
697   }
698 };
699
700 inline void planepts_print(const PlanePoints& planePoints, TextOutputStream& ostream)
701 {
702   ostream << "( " << planePoints[0][0] << " " << planePoints[0][1] << " " << planePoints[0][2] << " ) "
703     << "( " << planePoints[1][0] << " " << planePoints[1][1] << " " << planePoints[1][2] << " ) "
704     << "( " << planePoints[2][0] << " " << planePoints[2][1] << " " << planePoints[2][2] << " )";
705 }
706
707
708 inline Plane3 Plane3_applyTranslation(const Plane3& plane, const Vector3& translation)
709 {
710   Plane3 tmp(plane3_translated(Plane3(plane.normal(), -plane.dist()), translation));
711   return Plane3(tmp.normal(), -tmp.dist());
712 }
713
714 inline Plane3 Plane3_applyTransform(const Plane3& plane, const Matrix4& matrix)
715 {
716   Plane3 tmp(plane3_transformed(Plane3(plane.normal(), -plane.dist()), matrix));
717   return Plane3(tmp.normal(), -tmp.dist());
718 }
719
720 class FacePlane
721 {
722   PlanePoints m_planepts;
723   Plane3 m_planeCached;
724   Plane3 m_plane;
725 public:
726   Vector3 m_funcStaticOrigin;
727
728   static EBrushType m_type;
729
730   static bool isDoom3Plane()
731   {
732     return FacePlane::m_type == eBrushTypeDoom3 || FacePlane::m_type == eBrushTypeQuake4;
733   }
734
735   class SavedState
736   {
737   public:
738     PlanePoints m_planepts;
739     Plane3 m_plane;
740
741     SavedState(const FacePlane& facePlane)
742     {
743       if(facePlane.isDoom3Plane())
744       {
745         m_plane = facePlane.m_plane;
746       }
747       else
748       {
749         planepts_assign(m_planepts, facePlane.planePoints());
750       }
751     }
752
753     void exportState(FacePlane& facePlane) const
754     {
755       if(facePlane.isDoom3Plane())
756       {
757         facePlane.m_plane = m_plane;
758         facePlane.updateTranslated();
759       }
760       else
761       {
762         planepts_assign(facePlane.planePoints(), m_planepts);
763         facePlane.MakePlane();
764       }
765     }
766   };
767
768   FacePlane() : m_funcStaticOrigin(0, 0, 0)
769   {
770   }
771   FacePlane(const FacePlane& other) : m_funcStaticOrigin(0, 0, 0)
772   {
773     if(!isDoom3Plane())
774     {
775       planepts_assign(m_planepts, other.m_planepts);
776       MakePlane();
777     }
778     else
779     {
780       m_plane = other.m_plane;
781       updateTranslated();
782     }
783   }
784
785   void MakePlane()
786   {
787     if(!isDoom3Plane())
788     {
789 #if 0
790       if(check_plane_is_integer(m_planepts))
791       {
792         globalErrorStream() << "non-integer planepts: ";
793         planepts_print(m_planepts, globalErrorStream());
794         globalErrorStream() << "\n";
795       }
796 #endif
797       m_planeCached = plane3_for_points(m_planepts);
798     }
799   }
800
801   void reverse()
802   {
803     if(!isDoom3Plane())
804     {
805       vector3_swap(m_planepts[0], m_planepts[2]);
806       MakePlane();
807     }
808     else
809     {
810       m_planeCached = plane3_flipped(m_plane);
811       updateSource();
812     }
813   }
814   void transform(const Matrix4& matrix, bool mirror)
815   {
816     if(!isDoom3Plane())
817     {
818
819 #if 0
820       bool off = check_plane_is_integer(planePoints());
821 #endif
822
823       matrix4_transform_point(matrix, m_planepts[0]);
824       matrix4_transform_point(matrix, m_planepts[1]);
825       matrix4_transform_point(matrix, m_planepts[2]);
826
827       if(mirror)
828       {
829         reverse();
830       }
831
832 #if 0
833       if(check_plane_is_integer(planePoints()))
834       {
835         if(!off)
836         {
837           globalErrorStream() << "caused by transform\n";
838         }
839       }
840 #endif
841       MakePlane();
842     }
843     else
844     {
845       m_planeCached = Plane3_applyTransform(m_planeCached, matrix);
846       updateSource();
847     }
848   }
849   void offset(float offset)
850   {
851     if(!isDoom3Plane())
852     {
853       Vector3 move(vector3_scaled(m_planeCached.normal(), -offset));
854
855       vector3_subtract(m_planepts[0], move);
856       vector3_subtract(m_planepts[1], move);
857       vector3_subtract(m_planepts[2], move);
858
859       MakePlane();
860     }
861     else
862     {
863       m_planeCached.d += offset;
864       updateSource();
865     }
866   }
867
868   void updateTranslated()
869   {
870     m_planeCached = Plane3_applyTranslation(m_plane, m_funcStaticOrigin);
871   }
872   void updateSource()
873   {
874     m_plane = Plane3_applyTranslation(m_planeCached, vector3_negated(m_funcStaticOrigin));
875   }
876
877
878   PlanePoints& planePoints()
879   {
880     return m_planepts;
881   }
882   const PlanePoints& planePoints() const
883   {
884     return m_planepts;
885   }
886   const Plane3& plane3() const
887   {
888     return m_planeCached;
889   }
890   void setDoom3Plane(const Plane3& plane)
891   {
892     m_plane = plane;
893     updateTranslated();
894   }
895   const Plane3& getDoom3Plane() const
896   {
897     return m_plane;
898   }
899
900   void copy(const FacePlane& other)
901   {
902     if(!isDoom3Plane())
903     {
904       planepts_assign(m_planepts, other.m_planepts);
905       MakePlane();
906     }
907     else
908     {
909       m_planeCached = other.m_plane;
910       updateSource();
911     }
912   }
913   void copy(const Vector3& p0, const Vector3& p1, const Vector3& p2)
914   {
915     if(!isDoom3Plane())
916     {
917       m_planepts[0] = p0;
918       m_planepts[1] = p1;
919       m_planepts[2] = p2;
920       MakePlane();
921     }
922     else
923     {
924       m_planeCached = plane3_for_points(p2, p1, p0);
925       updateSource();
926     }
927   }
928 };
929
930 inline void Winding_testSelect(Winding& winding, SelectionTest& test, SelectionIntersection& best)
931 {
932   test.TestPolygon(VertexPointer(reinterpret_cast<VertexPointer::pointer>(&winding.points.data()->vertex), sizeof(WindingVertex)), winding.numpoints, best);
933 }
934
935 const double GRID_MIN = 0.125;
936
937 inline double quantiseInteger(double f)
938 {
939   return float_to_integer(f);
940 }
941
942 inline double quantiseFloating(double f)
943 {
944   return float_snapped(f, 1.f / (1 << 16));
945 }
946
947 typedef double (*QuantiseFunc)(double f);
948
949 class Face;
950
951 class FaceFilter
952 {
953 public:
954   virtual bool filter(const Face& face) const = 0;
955 };
956
957 bool face_filtered(Face& face);
958
959 void Brush_addTextureChangedCallback(const SignalHandler& callback);
960 void Brush_textureChanged();
961
962
963 extern bool g_brush_texturelock_enabled;
964
965 class FaceObserver
966 {
967 public:
968   virtual void planeChanged() = 0;
969   virtual void connectivityChanged() = 0;
970   virtual void shaderChanged() = 0;
971   virtual void evaluateTransform() = 0;
972 };
973
974 class Face :
975 public OpenGLRenderable,
976 public Filterable,
977 public Undoable,
978 public FaceShaderObserver
979 {
980   std::size_t m_refcount;
981
982   class SavedState : public UndoMemento
983   {
984   public:
985     FacePlane::SavedState m_planeState;
986     FaceTexdef::SavedState m_texdefState;
987     FaceShader::SavedState m_shaderState;
988
989     SavedState(const Face& face) : m_planeState(face.getPlane()), m_texdefState(face.getTexdef()), m_shaderState(face.getShader())
990     {
991     }
992
993     void exportState(Face& face) const
994     {
995       m_planeState.exportState(face.getPlane());
996       m_shaderState.exportState(face.getShader());
997       m_texdefState.exportState(face.getTexdef());
998     }
999
1000     void release()
1001     {
1002       delete this;
1003     }
1004   };
1005
1006 public:
1007   static QuantiseFunc m_quantise;
1008   static EBrushType m_type;
1009
1010   PlanePoints m_move_planepts;
1011   PlanePoints m_move_planeptsTransformed;
1012 private:
1013   FacePlane m_plane;
1014   FacePlane m_planeTransformed;
1015   FaceShader m_shader;
1016   FaceTexdef m_texdef;
1017   TextureProjection m_texdefTransformed;
1018
1019   Winding m_winding;
1020   Vector3 m_centroid;
1021   bool m_filtered;
1022
1023   FaceObserver* m_observer;
1024   UndoObserver* m_undoable_observer;
1025   MapFile* m_map;
1026
1027   // assignment not supported
1028   Face& operator=(const Face& other);
1029   // copy-construction not supported
1030   Face(const Face& other);
1031
1032 public:
1033
1034   Face(FaceObserver* observer) :
1035     m_refcount(0),
1036     m_shader(texdef_name_default()),
1037     m_texdef(m_shader, TextureProjection(), false),
1038     m_filtered(false),
1039     m_observer(observer),
1040     m_undoable_observer(0),
1041     m_map(0)
1042   {
1043     m_shader.attach(*this);
1044     m_plane.copy(Vector3(0, 0, 0), Vector3(64, 0, 0), Vector3(0, 64, 0));
1045     m_texdef.setBasis(m_plane.plane3().normal());
1046     planeChanged();
1047   }
1048   Face(
1049     const Vector3& p0,
1050     const Vector3& p1,
1051     const Vector3& p2,
1052     const char* shader,
1053     const TextureProjection& projection,
1054     FaceObserver* observer
1055   ) :
1056     m_refcount(0),
1057     m_shader(shader),
1058     m_texdef(m_shader, projection),
1059     m_observer(observer),
1060     m_undoable_observer(0),
1061     m_map(0)
1062   {
1063     m_shader.attach(*this);
1064     m_plane.copy(p0, p1, p2);
1065     m_texdef.setBasis(m_plane.plane3().normal());
1066     planeChanged();
1067     updateFiltered();
1068   }
1069   Face(const Face& other, FaceObserver* observer) :
1070     m_refcount(0),
1071     m_shader(other.m_shader.getShader(), other.m_shader.m_flags),
1072     m_texdef(m_shader, other.getTexdef().normalised()),
1073     m_observer(observer),
1074     m_undoable_observer(0),
1075     m_map(0)
1076   {
1077     m_shader.attach(*this);
1078     m_plane.copy(other.m_plane);
1079     planepts_assign(m_move_planepts, other.m_move_planepts);
1080     m_texdef.setBasis(m_plane.plane3().normal());
1081     planeChanged();
1082     updateFiltered();
1083   }
1084   ~Face()
1085   {
1086     m_shader.detach(*this);
1087   }
1088
1089   void planeChanged()
1090   {
1091     revertTransform();
1092     m_observer->planeChanged();
1093   }
1094
1095   void realiseShader()
1096   {
1097     m_observer->shaderChanged();
1098   }
1099   void unrealiseShader()
1100   {
1101   }
1102
1103   void instanceAttach(MapFile* map)
1104   {
1105     m_shader.instanceAttach();
1106     m_map = map;
1107     m_undoable_observer = GlobalUndoSystem().observer(this);
1108     GlobalFilterSystem().registerFilterable(*this);
1109   }
1110   void instanceDetach(MapFile* map)
1111   {
1112     GlobalFilterSystem().unregisterFilterable(*this);
1113     m_undoable_observer = 0;
1114     GlobalUndoSystem().release(this);
1115     m_map = 0;
1116     m_shader.instanceDetach();
1117   }
1118
1119   void render(RenderStateFlags state) const
1120   {
1121     Winding_Draw(m_winding, m_planeTransformed.plane3().normal(), state);
1122   }
1123
1124   void updateFiltered()
1125   {
1126     m_filtered = face_filtered(*this);
1127   }
1128   bool isFiltered() const
1129   {
1130     return m_filtered;
1131   }
1132
1133   void undoSave()
1134   {
1135     if(m_map != 0)
1136     {
1137       m_map->changed();
1138     }
1139     if(m_undoable_observer != 0)
1140     {
1141       m_undoable_observer->save(this);
1142     }
1143   }
1144
1145   // undoable
1146   UndoMemento* exportState() const
1147   {
1148     return new SavedState(*this);
1149   }
1150   void importState(const UndoMemento* data)
1151   {
1152     undoSave();
1153
1154     static_cast<const SavedState*>(data)->exportState(*this);
1155
1156     planeChanged();
1157     m_observer->connectivityChanged();
1158     texdefChanged();
1159     m_observer->shaderChanged();
1160     updateFiltered();
1161   }
1162
1163   void IncRef()
1164   {
1165     ++m_refcount;
1166   }
1167   void DecRef()
1168   {
1169     if(--m_refcount == 0)
1170       delete this;
1171   }
1172
1173   void flipWinding()
1174   {
1175     m_plane.reverse();
1176     planeChanged();
1177   }
1178
1179   bool intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const
1180   {
1181     return volume.TestPlane(Plane3(plane3().normal(), -plane3().dist()), localToWorld);
1182   }
1183
1184   void render(Renderer& renderer, const Matrix4& localToWorld) const
1185   {
1186     renderer.SetState(m_shader.state(), Renderer::eFullMaterials);
1187     renderer.addRenderable(*this, localToWorld);
1188   }
1189
1190   void transform(const Matrix4& matrix, bool mirror)
1191   {
1192     if(g_brush_texturelock_enabled)
1193     {
1194       Texdef_transformLocked(m_texdefTransformed, m_shader.width(), m_shader.height(), m_plane.plane3(), matrix);
1195     }
1196
1197     m_planeTransformed.transform(matrix, mirror);
1198
1199 #if 0
1200     ASSERT_MESSAGE(projectionaxis_for_normal(normal) == projectionaxis_for_normal(plane3().normal()), "bleh");
1201 #endif
1202     m_observer->planeChanged();
1203   }
1204
1205   void assign_planepts(const PlanePoints planepts)
1206   {
1207     m_planeTransformed.copy(planepts[0], planepts[1], planepts[2]);
1208     m_observer->planeChanged();
1209   }
1210
1211   /// \brief Reverts the transformable state of the brush to identity. 
1212   void revertTransform()
1213   {
1214     m_planeTransformed = m_plane;
1215     planepts_assign(m_move_planeptsTransformed, m_move_planepts);
1216     m_texdefTransformed = m_texdef.m_projection;
1217   }
1218   void freezeTransform()
1219   {
1220     undoSave();
1221     m_plane = m_planeTransformed;
1222     planepts_assign(m_move_planepts, m_move_planeptsTransformed);
1223     m_texdef.m_projection = m_texdefTransformed;
1224   }
1225
1226   void update_move_planepts_vertex(std::size_t index, PlanePoints planePoints)
1227   {
1228     std::size_t numpoints = getWinding().numpoints;
1229     ASSERT_MESSAGE(index < numpoints, "update_move_planepts_vertex: invalid index");
1230
1231     std::size_t opposite = Winding_Opposite(getWinding(), index);
1232     std::size_t adjacent = Winding_wrap(getWinding(), opposite+numpoints-1);
1233     planePoints[0] = getWinding()[opposite].vertex;
1234     planePoints[1] = getWinding()[index].vertex;
1235     planePoints[2] = getWinding()[adjacent].vertex;
1236     // winding points are very inaccurate, so they must be quantised before using them to generate the face-plane
1237     planepts_quantise(planePoints, GRID_MIN);
1238   }
1239
1240   void snapto(float snap)
1241   {
1242     if(contributes())
1243     {
1244 #if 0
1245       ASSERT_MESSAGE(plane3_valid(m_plane.plane3()), "invalid plane before snap to grid");
1246       planepts_snap(m_plane.planePoints(), snap);
1247       ASSERT_MESSAGE(plane3_valid(m_plane.plane3()), "invalid plane after snap to grid");
1248 #else
1249       PlanePoints planePoints;
1250       update_move_planepts_vertex(0, planePoints);
1251       vector3_snap(planePoints[0], snap);
1252       vector3_snap(planePoints[1], snap);
1253       vector3_snap(planePoints[2], snap);
1254       assign_planepts(planePoints);
1255       freezeTransform();
1256 #endif
1257       SceneChangeNotify();
1258       if(!plane3_valid(m_plane.plane3()))
1259       {
1260         globalErrorStream() << "WARNING: invalid plane after snap to grid\n";
1261       }
1262     }
1263   }
1264
1265   void testSelect(SelectionTest& test, SelectionIntersection& best)
1266   {
1267     Winding_testSelect(m_winding, test, best);
1268   }
1269
1270   void testSelect_centroid(SelectionTest& test, SelectionIntersection& best)
1271   {
1272     test.TestPoint(m_centroid, best);
1273   }
1274
1275   void shaderChanged()
1276   {
1277     EmitTextureCoordinates();
1278     Brush_textureChanged();
1279     m_observer->shaderChanged();
1280     updateFiltered();
1281     SceneChangeNotify();
1282   }
1283
1284   const char* GetShader() const
1285   {
1286     return m_shader.getShader();
1287   }
1288   void SetShader(const char* name)
1289   {
1290     undoSave();
1291     m_shader.setShader(name);
1292     shaderChanged();
1293   }
1294
1295   void revertTexdef()
1296   {
1297     m_texdefTransformed = m_texdef.m_projection;
1298   }
1299   void texdefChanged()
1300   {
1301     revertTexdef();
1302     EmitTextureCoordinates();
1303     Brush_textureChanged();
1304   }
1305
1306   void GetTexdef(TextureProjection& projection) const
1307   {
1308     projection = m_texdef.normalised();
1309   }
1310   void SetTexdef(const TextureProjection& projection)
1311   {
1312     undoSave();
1313     m_texdef.setTexdef(projection);
1314     texdefChanged();
1315   }
1316
1317   void GetFlags(ContentsFlagsValue& flags) const
1318   {
1319     flags = m_shader.getFlags();
1320   }
1321   void SetFlags(const ContentsFlagsValue& flags)
1322   {
1323     undoSave();
1324     m_shader.setFlags(flags);
1325     m_observer->shaderChanged();
1326     updateFiltered();
1327   }
1328
1329   void ShiftTexdef(float s, float t)
1330   {
1331     undoSave();
1332     m_texdef.shift(s, t);
1333     texdefChanged();
1334   }
1335
1336   void ScaleTexdef(float s, float t)
1337   {
1338     undoSave();
1339     m_texdef.scale(s, t);
1340     texdefChanged();
1341   }
1342
1343   void RotateTexdef(float angle)
1344   {
1345     undoSave();
1346     m_texdef.rotate(angle);
1347     texdefChanged();
1348   }
1349
1350   void FitTexture(float s_repeat, float t_repeat)
1351   {
1352     undoSave();
1353     m_texdef.fit(m_plane.plane3().normal(), m_winding, s_repeat, t_repeat);
1354     texdefChanged();
1355   }
1356
1357   void EmitTextureCoordinates()
1358   {
1359     Texdef_EmitTextureCoordinates(m_texdefTransformed, m_shader.width(), m_shader.height(), m_winding, plane3().normal(), g_matrix4_identity);
1360   }
1361
1362
1363   const Vector3& centroid() const
1364   {
1365     return m_centroid;
1366   }
1367
1368   void construct_centroid()
1369   {
1370     Winding_Centroid(m_winding, plane3(), m_centroid);
1371   }
1372
1373   const Winding& getWinding() const
1374   {
1375     return m_winding;
1376   }
1377   Winding& getWinding()
1378   {
1379     return m_winding;
1380   }
1381
1382   const Plane3& plane3() const
1383   {
1384     m_observer->evaluateTransform();
1385     return m_planeTransformed.plane3();
1386   }
1387   FacePlane& getPlane()
1388   {
1389     return m_plane;
1390   }
1391   const FacePlane& getPlane() const
1392   {
1393     return m_plane;
1394   }
1395   FaceTexdef& getTexdef()
1396   {
1397     return m_texdef;
1398   }
1399   const FaceTexdef& getTexdef() const
1400   {
1401     return m_texdef;
1402   }
1403   FaceShader& getShader()
1404   {
1405     return m_shader;
1406   }
1407   const FaceShader& getShader() const
1408   {
1409     return m_shader;
1410   }
1411
1412   bool isDetail() const
1413   {
1414     return (m_shader.m_flags.m_contentFlags & CONTENTS_DETAIL) != 0;
1415   }
1416   void setDetail(bool detail)
1417   {
1418     undoSave();
1419     if(detail && !isDetail())
1420     {
1421       m_shader.m_flags.m_contentFlags |= CONTENTS_DETAIL;
1422     }
1423     else if(!detail && isDetail())
1424     {
1425       m_shader.m_flags.m_contentFlags &= ~CONTENTS_DETAIL;
1426     }
1427     m_observer->shaderChanged();
1428   }
1429
1430   bool contributes() const
1431   {
1432     return m_winding.numpoints > 2;
1433   }
1434   bool is_bounded() const
1435   {
1436     for(Winding::const_iterator i = m_winding.begin(); i != m_winding.end(); ++i)
1437     {
1438       if((*i).adjacent == c_brush_maxFaces)
1439       {
1440         return false;
1441       }
1442     }
1443     return true;
1444   }
1445 };
1446
1447
1448 class FaceVertexId
1449 {
1450   std::size_t m_face;
1451   std::size_t m_vertex;
1452
1453 public:
1454   FaceVertexId(std::size_t face, std::size_t vertex)
1455     : m_face(face), m_vertex(vertex)
1456   {
1457   }
1458
1459   std::size_t getFace() const
1460   {
1461     return m_face;
1462   }
1463   std::size_t getVertex() const
1464   {
1465     return m_vertex;
1466   }
1467 };
1468
1469 typedef std::size_t faceIndex_t;
1470
1471 struct EdgeRenderIndices
1472 {
1473   RenderIndex first;
1474   RenderIndex second;
1475
1476   EdgeRenderIndices()
1477     : first(0), second(0)
1478   {
1479   }
1480   EdgeRenderIndices(const RenderIndex _first, const RenderIndex _second)
1481     : first(_first), second(_second)
1482   {
1483   }
1484 };
1485
1486 struct EdgeFaces
1487 {
1488   faceIndex_t first;
1489   faceIndex_t second;
1490
1491   EdgeFaces()
1492     : first(c_brush_maxFaces), second(c_brush_maxFaces)
1493   {
1494   }
1495   EdgeFaces(const faceIndex_t _first, const faceIndex_t _second)
1496     : first(_first), second(_second)
1497   {
1498   }
1499 };
1500
1501 class RenderableWireframe : public OpenGLRenderable
1502 {
1503 public:
1504   void render(RenderStateFlags state) const
1505   {
1506 #if 1
1507     glColorPointer(4, GL_UNSIGNED_BYTE, sizeof(PointVertex), &m_vertices->colour);
1508     glVertexPointer(3, GL_FLOAT, sizeof(PointVertex), &m_vertices->vertex);
1509     glDrawElements(GL_LINES, GLsizei(m_size<<1), RenderIndexTypeID, m_faceVertex.data());
1510 #else
1511     glBegin(GL_LINES);
1512     for(std::size_t i = 0; i < m_size; ++i)
1513     {
1514       glVertex3fv(&m_vertices[m_faceVertex[i].first].vertex.x);
1515       glVertex3fv(&m_vertices[m_faceVertex[i].second].vertex.x);
1516     }
1517     glEnd();
1518 #endif
1519   }
1520
1521   Array<EdgeRenderIndices> m_faceVertex;
1522   std::size_t m_size;
1523   const PointVertex* m_vertices;
1524 };
1525
1526 class Brush;
1527 typedef std::vector<Brush*> brush_vector_t;
1528
1529 class BrushFilter
1530 {
1531 public:
1532   virtual bool filter(const Brush& brush) const = 0;
1533 };
1534
1535 bool brush_filtered(Brush& brush);
1536 void add_brush_filter(BrushFilter& filter, int mask, bool invert = false);
1537
1538
1539 /// \brief Returns true if 'self' takes priority when building brush b-rep.
1540 inline bool plane3_inside(const Plane3& self, const Plane3& other)
1541 {
1542   if(vector3_equal_epsilon(self.normal(), other.normal(), 0.001))
1543   {
1544     return self.dist() < other.dist();
1545   }
1546   return true;
1547 }
1548
1549 typedef SmartPointer<Face> FaceSmartPointer;
1550 typedef std::vector<FaceSmartPointer> Faces;
1551
1552 /// \brief Returns the unique-id of the edge adjacent to \p faceVertex in the edge-pair for the set of \p faces.
1553 inline FaceVertexId next_edge(const Faces& faces, FaceVertexId faceVertex)
1554 {
1555   std::size_t adjacent_face = faces[faceVertex.getFace()]->getWinding()[faceVertex.getVertex()].adjacent;
1556   std::size_t adjacent_vertex = Winding_FindAdjacent(faces[adjacent_face]->getWinding(), faceVertex.getFace());
1557
1558   ASSERT_MESSAGE(adjacent_vertex != c_brush_maxFaces, "connectivity data invalid");
1559   if(adjacent_vertex == c_brush_maxFaces)
1560   {
1561     return faceVertex;
1562   }
1563
1564   return FaceVertexId(adjacent_face, adjacent_vertex);
1565 }
1566
1567 /// \brief Returns the unique-id of the vertex adjacent to \p faceVertex in the vertex-ring for the set of \p faces.
1568 inline FaceVertexId next_vertex(const Faces& faces, FaceVertexId faceVertex)
1569 {
1570   FaceVertexId nextEdge = next_edge(faces, faceVertex);
1571   return FaceVertexId(nextEdge.getFace(), Winding_next(faces[nextEdge.getFace()]->getWinding(), nextEdge.getVertex()));
1572 }
1573
1574 class SelectableEdge
1575 {
1576   Vector3 getEdge() const
1577   {
1578     const Winding& winding = getFace().getWinding();
1579     return vector3_mid(winding[m_faceVertex.getVertex()].vertex, winding[Winding_next(winding, m_faceVertex.getVertex())].vertex);
1580   }
1581
1582 public:
1583   Faces& m_faces;
1584   FaceVertexId m_faceVertex;
1585
1586   SelectableEdge(Faces& faces, FaceVertexId faceVertex)
1587     : m_faces(faces), m_faceVertex(faceVertex)
1588   {
1589   }
1590   SelectableEdge& operator=(const SelectableEdge& other)
1591   {
1592     m_faceVertex = other.m_faceVertex;
1593     return *this;
1594   }
1595
1596   Face& getFace() const
1597   {
1598     return *m_faces[m_faceVertex.getFace()];
1599   }
1600
1601   void testSelect(SelectionTest& test, SelectionIntersection& best)
1602   {
1603     test.TestPoint(getEdge(), best);
1604   }
1605 };
1606
1607 class SelectableVertex
1608 {
1609   Vector3 getVertex() const
1610   {
1611     return getFace().getWinding()[m_faceVertex.getVertex()].vertex;
1612   }
1613
1614 public:
1615   Faces& m_faces;
1616   FaceVertexId m_faceVertex;
1617
1618   SelectableVertex(Faces& faces, FaceVertexId faceVertex)
1619     : m_faces(faces), m_faceVertex(faceVertex)
1620   {
1621   }
1622   SelectableVertex& operator=(const SelectableVertex& other)
1623   {
1624     m_faceVertex = other.m_faceVertex;
1625     return *this;
1626   }
1627
1628   Face& getFace() const
1629   {
1630     return *m_faces[m_faceVertex.getFace()];
1631   }
1632
1633   void testSelect(SelectionTest& test, SelectionIntersection& best)
1634   {
1635     test.TestPoint(getVertex(), best);
1636   }
1637 };
1638
1639 class BrushObserver
1640 {
1641 public:
1642   virtual void reserve(std::size_t size) = 0;
1643   virtual void clear() = 0;
1644   virtual void push_back(Face& face) = 0;
1645   virtual void pop_back() = 0;
1646   virtual void erase(std::size_t index) = 0;
1647   virtual void connectivityChanged() = 0;
1648
1649   virtual void edge_clear() = 0;
1650   virtual void edge_push_back(SelectableEdge& edge) = 0;
1651
1652   virtual void vertex_clear() = 0;
1653   virtual void vertex_push_back(SelectableVertex& vertex) = 0;
1654
1655   virtual void DEBUG_verify() const = 0;
1656 };
1657
1658 class BrushVisitor
1659 {
1660 public:
1661   virtual void visit(Face& face) const = 0;
1662 };
1663
1664 class Brush :
1665   public TransformNode,
1666   public Bounded,
1667   public Cullable,
1668   public Snappable,
1669   public Undoable,
1670   public FaceObserver,
1671   public Filterable,
1672   public Nameable,
1673   public BrushDoom3
1674 {
1675 private:
1676   scene::Node* m_node;
1677   typedef UniqueSet<BrushObserver*> Observers;
1678   Observers m_observers;
1679   UndoObserver* m_undoable_observer;
1680   MapFile* m_map;
1681
1682   // state
1683   Faces m_faces;
1684   // ----
1685
1686   // cached data compiled from state
1687   Array<PointVertex> m_faceCentroidPoints;
1688   RenderablePointArray m_render_faces;
1689
1690   Array<PointVertex> m_uniqueVertexPoints;
1691   typedef std::vector<SelectableVertex> SelectableVertices;
1692   SelectableVertices m_select_vertices;
1693   RenderablePointArray m_render_vertices;
1694
1695   Array<PointVertex> m_uniqueEdgePoints;
1696   typedef std::vector<SelectableEdge> SelectableEdges;
1697   SelectableEdges m_select_edges;
1698   RenderablePointArray m_render_edges;
1699
1700   Array<EdgeRenderIndices> m_edge_indices;
1701   Array<EdgeFaces> m_edge_faces;
1702
1703   AABB m_aabb_local;
1704   // ----
1705
1706   Callback m_evaluateTransform;
1707   Callback m_boundsChanged;
1708
1709   mutable bool m_planeChanged; // b-rep evaluation required
1710   mutable bool m_transformChanged; // transform evaluation required
1711   // ----
1712
1713 public:  
1714   STRING_CONSTANT(Name, "Brush");
1715
1716   Callback m_lightsChanged;
1717
1718   // static data
1719   static Shader* m_state_point;
1720   // ----
1721
1722   static EBrushType m_type;
1723   static double m_maxWorldCoord;
1724
1725   Brush(scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) :
1726     m_node(&node),
1727     m_undoable_observer(0),
1728     m_map(0),
1729     m_render_faces(m_faceCentroidPoints, GL_POINTS),
1730     m_render_vertices(m_uniqueVertexPoints, GL_POINTS),
1731     m_render_edges(m_uniqueEdgePoints, GL_POINTS),
1732     m_planeChanged(false),
1733     m_transformChanged(false),
1734     m_evaluateTransform(evaluateTransform),
1735     m_boundsChanged(boundsChanged)
1736   {
1737     planeChanged();
1738   }
1739   Brush(const Brush& other, scene::Node& node, const Callback& evaluateTransform, const Callback& boundsChanged) :
1740     m_node(&node),
1741     m_undoable_observer(0),
1742     m_map(0),
1743     m_render_faces(m_faceCentroidPoints, GL_POINTS),
1744     m_render_vertices(m_uniqueVertexPoints, GL_POINTS),
1745     m_render_edges(m_uniqueEdgePoints, GL_POINTS),
1746     m_planeChanged(false),
1747     m_transformChanged(false),
1748     m_evaluateTransform(evaluateTransform),
1749     m_boundsChanged(boundsChanged)
1750   {
1751     copy(other);
1752   }
1753   Brush(const Brush& other) :
1754     TransformNode(other),
1755     Bounded(other),
1756     Cullable(other),
1757     Undoable(other),
1758     FaceObserver(other),
1759     Filterable(other),
1760     Nameable(other),
1761     BrushDoom3(other),
1762     m_node(0),
1763     m_undoable_observer(0),
1764     m_map(0),
1765     m_render_faces(m_faceCentroidPoints, GL_POINTS),
1766     m_render_vertices(m_uniqueVertexPoints, GL_POINTS),
1767     m_render_edges(m_uniqueEdgePoints, GL_POINTS),
1768     m_planeChanged(false),
1769     m_transformChanged(false)
1770   {
1771     copy(other);
1772   }
1773   ~Brush()
1774   {
1775     ASSERT_MESSAGE(m_observers.empty(), "Brush::~Brush: observers still attached");
1776   }
1777
1778   // assignment not supported
1779   Brush& operator=(const Brush& other);
1780
1781   void setDoom3GroupOrigin(const Vector3& origin)
1782   {
1783     //globalOutputStream() << "func_static origin before: " << m_funcStaticOrigin << " after: " << origin << "\n";
1784     for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1785     {
1786       (*i)->getPlane().m_funcStaticOrigin = origin;
1787       (*i)->getPlane().updateTranslated();
1788       (*i)->planeChanged();
1789     }
1790     planeChanged();
1791   }
1792
1793   void attach(BrushObserver& observer)
1794   {
1795     for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1796     {
1797       observer.push_back(*(*i));
1798     }
1799
1800     for(SelectableEdges::iterator i = m_select_edges.begin(); i !=m_select_edges.end(); ++i)
1801     {
1802       observer.edge_push_back(*i);
1803     }
1804
1805     for(SelectableVertices::iterator i = m_select_vertices.begin(); i != m_select_vertices.end(); ++i)
1806     {
1807       observer.vertex_push_back(*i);
1808     }
1809
1810     m_observers.insert(&observer);
1811   }
1812   void detach(BrushObserver& observer)
1813   {
1814     m_observers.erase(&observer);
1815   }
1816
1817   void forEachFace(const BrushVisitor& visitor) const
1818   {
1819     for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1820     {
1821       visitor.visit(*(*i));
1822     }
1823   }
1824
1825   void forEachFace_instanceAttach(MapFile* map) const
1826   {
1827     for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1828     {
1829       (*i)->instanceAttach(map);
1830     }
1831   }
1832   void forEachFace_instanceDetach(MapFile* map) const
1833   {
1834     for(Faces::const_iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1835     {
1836       (*i)->instanceDetach(map);
1837     }
1838   }
1839
1840   InstanceCounter m_instanceCounter;
1841   void instanceAttach(const scene::Path& path)
1842   {
1843     if(++m_instanceCounter.m_count == 1)
1844     {
1845       m_map = path_find_mapfile(path.begin(), path.end());
1846       m_undoable_observer = GlobalUndoSystem().observer(this);
1847       GlobalFilterSystem().registerFilterable(*this);
1848       forEachFace_instanceAttach(m_map);
1849     }
1850     else
1851     {
1852       ASSERT_MESSAGE(path_find_mapfile(path.begin(), path.end()) == m_map, "node is instanced across more than one file");
1853     }
1854   }
1855   void instanceDetach(const scene::Path& path)
1856   {
1857     if(--m_instanceCounter.m_count == 0)
1858     {
1859       forEachFace_instanceDetach(m_map);
1860       GlobalFilterSystem().unregisterFilterable(*this);
1861       m_map = 0;
1862       m_undoable_observer = 0;
1863       GlobalUndoSystem().release(this);
1864     }
1865   }
1866
1867   // nameable
1868   const char* name() const
1869   {
1870     return "brush";
1871   }
1872   void attach(const NameCallback& callback)
1873   {
1874   }
1875   void detach(const NameCallback& callback)
1876   {
1877   }
1878
1879   // filterable
1880   void updateFiltered()
1881   {
1882     if(m_node != 0)
1883     {
1884       if(brush_filtered(*this))
1885       {
1886         m_node->enable(scene::Node::eFiltered);
1887       }
1888       else
1889       {
1890         m_node->disable(scene::Node::eFiltered);
1891       }
1892     }
1893   }
1894
1895   // observer
1896   void planeChanged()
1897   {
1898     m_planeChanged = true;
1899     aabbChanged();
1900     m_lightsChanged();
1901   }
1902   void shaderChanged()
1903   {
1904     updateFiltered();
1905   }
1906
1907   void evaluateBRep() const
1908   {
1909     if(m_planeChanged)
1910     {
1911       m_planeChanged = false;
1912       const_cast<Brush*>(this)->buildBRep();
1913     }
1914   }
1915
1916   void transformChanged()
1917   {
1918     m_transformChanged = true;
1919     planeChanged();
1920   }
1921   typedef MemberCaller<Brush, &Brush::transformChanged> TransformChangedCaller;
1922
1923   void evaluateTransform()
1924   {
1925     if(m_transformChanged)
1926     {
1927       m_transformChanged = false;
1928       revertTransform();
1929       m_evaluateTransform();
1930     }
1931   }
1932   const Matrix4& localToParent() const
1933   {
1934     return g_matrix4_identity;
1935   }
1936   void aabbChanged()
1937   {
1938     m_boundsChanged();
1939   }
1940   const AABB& localAABB() const
1941   {
1942     evaluateBRep();
1943     return m_aabb_local;
1944   }
1945
1946   VolumeIntersectionValue intersectVolume(const VolumeTest& test, const Matrix4& localToWorld) const
1947   {
1948     return test.TestAABB(m_aabb_local, localToWorld);
1949   }
1950
1951   void renderComponents(SelectionSystem::EComponentMode mode, Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
1952   {
1953     switch(mode)
1954     {
1955     case SelectionSystem::eVertex:
1956       renderer.addRenderable(m_render_vertices, localToWorld);
1957       break;
1958     case SelectionSystem::eEdge:
1959       renderer.addRenderable(m_render_edges, localToWorld);
1960       break;
1961     case SelectionSystem::eFace:
1962       renderer.addRenderable(m_render_faces, localToWorld);
1963       break;
1964     default:
1965       break;
1966     }
1967   }
1968
1969   void transform(const Matrix4& matrix)
1970   {
1971     bool mirror = matrix4_handedness(matrix) == MATRIX4_LEFTHANDED;
1972
1973     for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1974     {
1975       (*i)->transform(matrix, mirror);
1976     }
1977   }
1978   void snapto(float snap)
1979   {
1980     for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1981     {
1982       (*i)->snapto(snap);
1983     }
1984   }
1985   void revertTransform()
1986   {
1987     for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1988     {
1989       (*i)->revertTransform();
1990     }
1991   }
1992   void freezeTransform()
1993   {
1994     for(Faces::iterator i = m_faces.begin(); i != m_faces.end(); ++i)
1995     {
1996       (*i)->freezeTransform();
1997     }
1998   }
1999
2000   /// \brief Returns the absolute index of the \p faceVertex.
2001   std::size_t absoluteIndex(FaceVertexId faceVertex)
2002   {
2003     std::size_t index = 0;
2004     for(std::size_t i = 0; i < faceVertex.getFace(); ++i)
2005     {
2006       index += m_faces[i]->getWinding().numpoints;
2007     }
2008     return index + faceVertex.getVertex();
2009   }
2010
2011   void appendFaces(const Faces& other)
2012   {
2013     clear();
2014     for(Faces::const_iterator i = other.begin(); i != other.end(); ++i)
2015     {
2016       push_back(*i);
2017     }
2018   }
2019
2020   /// \brief The undo memento for a brush stores only the list of face references - the faces are not copied.
2021   class BrushUndoMemento : public UndoMemento
2022   {
2023   public:
2024     BrushUndoMemento(const Faces& faces) : m_faces(faces)
2025     {
2026     }
2027     void release()
2028     {
2029       delete this;
2030     }
2031
2032     Faces m_faces;
2033   };
2034
2035   void undoSave()
2036   {
2037     if(m_map != 0)
2038     {
2039       m_map->changed();
2040     }
2041     if(m_undoable_observer != 0)
2042     {
2043       m_undoable_observer->save(this);
2044     }
2045   }
2046
2047   UndoMemento* exportState() const
2048   {
2049     return new BrushUndoMemento(m_faces);
2050   }
2051
2052   void importState(const UndoMemento* state)
2053   {
2054     undoSave();
2055     appendFaces(static_cast<const BrushUndoMemento*>(state)->m_faces);
2056     planeChanged();
2057
2058     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2059     {
2060       (*i)->DEBUG_verify();
2061     }
2062   }
2063
2064   bool isDetail()
2065   {
2066     return !m_faces.empty() && m_faces.front()->isDetail();
2067   }
2068
2069   /// \brief Appends a copy of \p face to the end of the face list.
2070   Face* addFace(const Face& face)
2071   {
2072     if(m_faces.size() == c_brush_maxFaces)
2073     {
2074       return 0;
2075     }
2076     undoSave();
2077     push_back(FaceSmartPointer(new Face(face, this)));
2078     m_faces.back()->setDetail(isDetail());
2079     planeChanged();
2080     return m_faces.back();
2081   }
2082
2083   /// \brief Appends a new face constructed from the parameters to the end of the face list.
2084   Face* addPlane(const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection)
2085   {
2086     if(m_faces.size() == c_brush_maxFaces)
2087     {
2088       return 0;
2089     }
2090     undoSave();
2091     push_back(FaceSmartPointer(new Face(p0, p1, p2, shader, projection, this)));
2092     m_faces.back()->setDetail(isDetail());
2093     planeChanged();
2094     return m_faces.back();
2095   }
2096
2097   static void constructStatic(EBrushType type)
2098   {
2099     m_type = type;
2100     Face::m_type = type;
2101     FacePlane::m_type = type;
2102
2103     g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_QUAKE;
2104     if(m_type == eBrushTypeQuake3BP || m_type == eBrushTypeDoom3 || m_type == eBrushTypeQuake4)
2105     {
2106       g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_BRUSHPRIMITIVES;
2107       g_brush_texturelock_enabled = true;
2108     }
2109     else if(m_type == eBrushTypeHalfLife)
2110     {
2111       g_bp_globals.m_texdefTypeId = TEXDEFTYPEID_HALFLIFE;
2112       g_brush_texturelock_enabled = true;
2113     }
2114
2115     Face::m_quantise = (m_type == eBrushTypeQuake) ? quantiseInteger : quantiseFloating;
2116
2117     m_state_point = GlobalShaderCache().capture("$POINT");
2118   }
2119   static void destroyStatic()
2120   {
2121     GlobalShaderCache().release("$POINT");
2122   }
2123
2124   std::size_t DEBUG_size()
2125   {
2126     return m_faces.size();
2127   }
2128
2129   typedef Faces::const_iterator const_iterator;
2130
2131   const_iterator begin() const
2132   {
2133     return m_faces.begin();
2134   }
2135   const_iterator end() const
2136   {
2137     return m_faces.end();
2138   }
2139
2140   Face* back()
2141   {
2142     return m_faces.back();
2143   }
2144   const Face* back() const
2145   {
2146     return m_faces.back();
2147   }
2148   void reserve(std::size_t count)
2149   {
2150     m_faces.reserve(count);
2151     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2152     {
2153       (*i)->reserve(count);
2154     }
2155   }
2156   void push_back(Faces::value_type face)
2157   {
2158     m_faces.push_back(face);
2159     if(m_instanceCounter.m_count != 0)
2160     {
2161       m_faces.back()->instanceAttach(m_map);
2162     }
2163     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2164     {
2165       (*i)->push_back(*face);
2166       (*i)->DEBUG_verify();
2167     }
2168   }
2169   void pop_back()
2170   {
2171     if(m_instanceCounter.m_count != 0)
2172     {
2173       m_faces.back()->instanceDetach(m_map);
2174     }
2175     m_faces.pop_back();
2176     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2177     {
2178       (*i)->pop_back();
2179       (*i)->DEBUG_verify();
2180     }
2181   }
2182   void erase(std::size_t index)
2183   {
2184     if(m_instanceCounter.m_count != 0)
2185     {
2186       m_faces[index]->instanceDetach(m_map);
2187     }
2188     m_faces.erase(m_faces.begin() + index);
2189     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2190     {
2191       (*i)->erase(index);
2192       (*i)->DEBUG_verify();
2193     }
2194   }
2195   void connectivityChanged()
2196   {
2197     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2198     {
2199       (*i)->connectivityChanged();
2200     }
2201   }
2202
2203
2204   void clear()
2205   {
2206     undoSave();
2207     if(m_instanceCounter.m_count != 0)
2208     {
2209       forEachFace_instanceDetach(m_map);
2210     }
2211     m_faces.clear();
2212     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2213     {
2214       (*i)->clear();
2215       (*i)->DEBUG_verify();
2216     }
2217   }
2218   std::size_t size() const
2219   {
2220     return m_faces.size();
2221   }
2222   bool empty() const
2223   {
2224     return m_faces.empty();
2225   }
2226
2227   /// \brief Returns true if any face of the brush contributes to the final B-Rep.
2228   bool hasContributingFaces() const
2229   {
2230     for(const_iterator i = begin(); i != end(); ++i)
2231     {
2232       if((*i)->contributes())
2233       {
2234         return true;
2235       }
2236     }
2237     return false;
2238   }
2239
2240   /// \brief Removes faces that do not contribute to the brush. This is useful for cleaning up after CSG operations on the brush.
2241   /// Note: removal of empty faces is not performed during direct brush manipulations, because it would make a manipulation irreversible if it created an empty face.
2242   void removeEmptyFaces()
2243   {
2244     evaluateBRep();
2245
2246     {
2247       std::size_t i = 0;
2248       while(i < m_faces.size())
2249       {
2250         if(!m_faces[i]->contributes())
2251         {
2252           erase(i);
2253           planeChanged();
2254         }
2255         else
2256         {
2257           ++i;
2258         }
2259       }
2260     }
2261   }
2262
2263   /// \brief Constructs \p winding from the intersection of \p plane with the other planes of the brush.
2264   void windingForClipPlane(Winding& winding, const Plane3& plane) const
2265   {
2266     FixedWinding buffer[2];
2267     bool swap = false;
2268
2269     // get a poly that covers an effectively infinite area
2270     Winding_createInfinite(buffer[swap], plane, m_maxWorldCoord + 1);
2271
2272     // chop the poly by all of the other faces
2273     {
2274       for (std::size_t i = 0;  i < m_faces.size(); ++i)
2275       {
2276         const Face& clip = *m_faces[i];
2277
2278         if(plane3_equal(clip.plane3(), plane) 
2279           || !plane3_valid(clip.plane3()) || !plane_unique(i)
2280           || plane3_opposing(plane, clip.plane3()))
2281         {
2282           continue;
2283         }
2284
2285         buffer[!swap].clear();
2286
2287 #if BRUSH_CONNECTIVITY_DEBUG
2288         globalOutputStream() << "clip vs face: " << i << "\n";
2289 #endif
2290
2291         {
2292           // flip the plane, because we want to keep the back side
2293           Plane3 clipPlane(vector3_negated(clip.plane3().normal()), -clip.plane3().dist());
2294           Winding_Clip(buffer[swap], plane, clipPlane, i, buffer[!swap]);
2295         }
2296
2297 #if BRUSH_CONNECTIVITY_DEBUG
2298         for(FixedWinding::Points::iterator k = buffer[!swap].points.begin(), j = buffer[!swap].points.end() - 1; k != buffer[!swap].points.end(); j = k, ++k)
2299         {
2300           if(vector3_length_squared(vector3_subtracted((*k).vertex, (*j).vertex)) < 1)
2301           {
2302             globalOutputStream() << "v: " << std::distance(buffer[!swap].points.begin(), j) << " tiny edge adjacent to face " << (*j).adjacent << "\n";
2303           }
2304         }
2305 #endif
2306
2307         //ASSERT_MESSAGE(buffer[!swap].numpoints != 1, "created single-point winding");
2308
2309         swap = !swap;
2310       }
2311     }
2312
2313     Winding_forFixedWinding(winding, buffer[swap]);
2314
2315 #if BRUSH_CONNECTIVITY_DEBUG
2316     Winding_printConnectivity(winding);
2317
2318     for(Winding::iterator i = winding.begin(), j = winding.end() - 1; i != winding.end(); j = i, ++i)
2319     {
2320       if(vector3_length_squared(vector3_subtracted((*i).vertex, (*j).vertex)) < 1)
2321       {
2322         globalOutputStream() << "v: " << std::distance(winding.begin(), j) << " tiny edge adjacent to face " << (*j).adjacent << "\n";
2323       }
2324     }
2325 #endif
2326   }
2327
2328   void update_wireframe(RenderableWireframe& wire, const bool* faces_visible) const
2329   {
2330     wire.m_faceVertex.resize(m_edge_indices.size());
2331     wire.m_vertices = m_uniqueVertexPoints.data();
2332     wire.m_size = 0;
2333     for(std::size_t i = 0; i < m_edge_faces.size(); ++i)
2334     {
2335       if(faces_visible[m_edge_faces[i].first]
2336         || faces_visible[m_edge_faces[i].second])
2337       {
2338         wire.m_faceVertex[wire.m_size++] = m_edge_indices[i];
2339       }
2340     }
2341   }
2342
2343
2344   void update_faces_wireframe(Array<PointVertex>& wire, const bool* faces_visible) const
2345   {
2346     std::size_t count = 0;
2347     for(std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i)
2348     {
2349       if(faces_visible[i])
2350       {
2351         ++count;
2352       }
2353     }
2354
2355     wire.resize(count);
2356     Array<PointVertex>::iterator p = wire.begin();
2357     for(std::size_t i = 0; i < m_faceCentroidPoints.size(); ++i)
2358     {
2359       if(faces_visible[i])
2360       {
2361         *p++ = m_faceCentroidPoints[i];
2362       }
2363     }
2364   }
2365
2366   /// \brief Makes this brush a deep-copy of the \p other.
2367   void copy(const Brush& other)
2368   {
2369     for(Faces::const_iterator i = other.m_faces.begin(); i != other.m_faces.end(); ++i)
2370     {
2371       addFace(*(*i));
2372     }
2373     planeChanged();
2374   }
2375
2376 private:
2377   void edge_push_back(FaceVertexId faceVertex)
2378   {
2379     m_select_edges.push_back(SelectableEdge(m_faces, faceVertex));
2380     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2381     {
2382       (*i)->edge_push_back(m_select_edges.back());
2383     }
2384   }
2385   void edge_clear()
2386   {
2387     m_select_edges.clear();
2388     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2389     {
2390       (*i)->edge_clear();
2391     }
2392   }
2393   void vertex_push_back(FaceVertexId faceVertex)
2394   {
2395     m_select_vertices.push_back(SelectableVertex(m_faces, faceVertex));
2396     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2397     {
2398       (*i)->vertex_push_back(m_select_vertices.back());
2399     }
2400   }
2401   void vertex_clear()
2402   {
2403     m_select_vertices.clear();
2404     for(Observers::iterator i = m_observers.begin(); i != m_observers.end(); ++i)
2405     {
2406       (*i)->vertex_clear();
2407     }
2408   }
2409
2410   /// \brief Returns true if the face identified by \p index is preceded by another plane that takes priority over it.
2411   bool plane_unique(std::size_t index) const
2412   {
2413     // duplicate plane
2414     for(std::size_t i = 0; i < m_faces.size(); ++i)
2415     {
2416       if(index != i && !plane3_inside(m_faces[index]->plane3(), m_faces[i]->plane3()))
2417       {
2418         return false;
2419       }
2420     }
2421     return true;
2422   }
2423
2424   /// \brief Removes edges that are smaller than the tolerance used when generating brush windings.
2425   void removeDegenerateEdges()
2426   {
2427     for (std::size_t i = 0;  i < m_faces.size(); ++i)
2428     {
2429       Winding& winding = m_faces[i]->getWinding();
2430       for(Winding::iterator j = winding.begin(); j != winding.end();)
2431       {
2432         std::size_t index = std::distance(winding.begin(), j);
2433         std::size_t next = Winding_next(winding, index);
2434         if(Edge_isDegenerate(winding[index].vertex, winding[next].vertex))
2435         {
2436 #if BRUSH_DEGENERATE_DEBUG
2437           globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate edge adjacent to " << winding[index].adjacent << "\n";
2438 #endif
2439           Winding& other = m_faces[winding[index].adjacent]->getWinding();
2440           std::size_t adjacent = Winding_FindAdjacent(other, i);
2441           if(adjacent != c_brush_maxFaces)
2442           {
2443             other.erase(other.begin() + adjacent);
2444           }
2445           winding.erase(j);
2446         }
2447         else
2448         {
2449           ++j;
2450         }
2451       }
2452     }
2453   }
2454
2455   /// \brief Invalidates faces that have only two vertices in their winding, while preserving edge-connectivity information.
2456   void removeDegenerateFaces()
2457   {
2458     // save adjacency info for degenerate faces
2459     for (std::size_t i = 0;  i < m_faces.size(); ++i)
2460     {
2461       Winding& degen = m_faces[i]->getWinding();
2462       
2463       if(degen.numpoints == 2)
2464       {
2465 #if BRUSH_DEGENERATE_DEBUG
2466         globalOutputStream() << "Brush::buildWindings: face " << i << ": degenerate winding adjacent to " << degen[0].adjacent << ", " << degen[1].adjacent << "\n";
2467 #endif
2468         // this is an "edge" face, where the plane touches the edge of the brush
2469         {
2470           Winding& winding = m_faces[degen[0].adjacent]->getWinding();
2471           std::size_t index = Winding_FindAdjacent(winding, i);
2472           if(index != c_brush_maxFaces)
2473           {
2474 #if BRUSH_DEGENERATE_DEBUG
2475             globalOutputStream() << "Brush::buildWindings: face " << degen[0].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[1].adjacent << "\n";
2476 #endif
2477             winding[index].adjacent = degen[1].adjacent;
2478           }
2479         }
2480
2481         {
2482           Winding& winding = m_faces[degen[1].adjacent]->getWinding();
2483           std::size_t index = Winding_FindAdjacent(winding, i);
2484           if(index != c_brush_maxFaces)
2485           {
2486 #if BRUSH_DEGENERATE_DEBUG
2487             globalOutputStream() << "Brush::buildWindings: face " << degen[1].adjacent << ": remapping adjacent " << winding[index].adjacent << " to " << degen[0].adjacent << "\n";
2488 #endif
2489             winding[index].adjacent = degen[0].adjacent;
2490           }
2491         }
2492
2493         degen.resize(0);
2494       }
2495     }
2496   }
2497
2498   /// \brief Removes edges that have the same adjacent-face as their immediate neighbour.
2499   void removeDuplicateEdges()
2500   {
2501     // verify face connectivity graph
2502     for(std::size_t i = 0; i < m_faces.size(); ++i)
2503     {
2504       //if(m_faces[i]->contributes())
2505       {
2506         Winding& winding = m_faces[i]->getWinding();
2507         for(std::size_t j = 0; j != winding.numpoints;)
2508         {
2509           std::size_t next = Winding_next(winding, j);
2510           if(winding[j].adjacent == winding[next].adjacent)
2511           {
2512 #if BRUSH_DEGENERATE_DEBUG
2513             globalOutputStream() << "Brush::buildWindings: face " << i << ": removed duplicate edge adjacent to face " << winding[j].adjacent << "\n";
2514 #endif
2515             winding.erase(winding.begin() + next);
2516           }
2517           else
2518           {
2519             ++j;
2520           }
2521         }
2522       }
2523     }
2524   }
2525
2526   /// \brief Removes edges that do not have a matching pair in their adjacent-face.
2527   void verifyConnectivityGraph()
2528   {
2529     // verify face connectivity graph
2530     for(std::size_t i = 0; i < m_faces.size(); ++i)
2531     {
2532       //if(m_faces[i]->contributes())
2533       {
2534         Winding& winding = m_faces[i]->getWinding();
2535         for(Winding::iterator j = winding.begin(); j != winding.end();)
2536         {
2537 #if BRUSH_CONNECTIVITY_DEBUG
2538           globalOutputStream() << "Brush::buildWindings: face " << i << ": adjacent to face " << (*j).adjacent << "\n";
2539 #endif
2540           // remove unidirectional graph edges
2541           if((*j).adjacent == c_brush_maxFaces
2542             || Winding_FindAdjacent(m_faces[(*j).adjacent]->getWinding(), i) == c_brush_maxFaces)
2543           {
2544 #if BRUSH_CONNECTIVITY_DEBUG
2545             globalOutputStream() << "Brush::buildWindings: face " << i << ": removing unidirectional connectivity graph edge adjacent to face " << (*j).adjacent << "\n";
2546 #endif
2547             winding.erase(j);
2548           }
2549           else
2550           {
2551             ++j;
2552           }
2553         }
2554       }
2555     }
2556   }
2557
2558   /// \brief Returns true if the brush is a finite volume. A brush without a finite volume extends past the maximum world bounds and is not valid.
2559   bool isBounded()
2560   {
2561     for(const_iterator i = begin(); i != end(); ++i)
2562     {
2563       if(!(*i)->is_bounded())
2564       {
2565         return false;
2566       }
2567     }
2568     return true;
2569   }
2570
2571   /// \brief Constructs the polygon windings for each face of the brush. Also updates the brush bounding-box and face texture-coordinates.
2572   bool buildWindings()
2573   {
2574
2575     {
2576       m_aabb_local = AABB();
2577
2578       for (std::size_t i = 0;  i < m_faces.size(); ++i)
2579       {
2580         Face& f = *m_faces[i];
2581
2582         if(!plane3_valid(f.plane3()) || !plane_unique(i))
2583         {
2584           f.getWinding().resize(0);
2585         }
2586         else
2587         {
2588 #if BRUSH_CONNECTIVITY_DEBUG
2589           globalOutputStream() << "face: " << i << "\n";
2590 #endif
2591           windingForClipPlane(f.getWinding(), f.plane3());
2592
2593           // update brush bounds
2594           const Winding& winding = f.getWinding();
2595           for(Winding::const_iterator i = winding.begin(); i != winding.end(); ++i)
2596           {
2597             aabb_extend_by_point_safe(m_aabb_local, (*i).vertex);
2598           }
2599
2600           // update texture coordinates
2601           f.EmitTextureCoordinates();
2602         }
2603       }
2604     }
2605
2606     bool degenerate = !isBounded();
2607
2608     if(!degenerate)
2609     {
2610       // clean up connectivity information.
2611       // these cleanups must be applied in a specific order.
2612       removeDegenerateEdges();
2613       removeDegenerateFaces();
2614       removeDuplicateEdges();
2615       verifyConnectivityGraph();
2616     }
2617
2618     return degenerate;
2619   }
2620
2621   /// \brief Constructs the face windings and updates anything that depends on them.
2622   void buildBRep();
2623 };
2624
2625
2626
2627 class FaceInstance;
2628
2629 class FaceInstanceSet
2630 {
2631   typedef SelectionList<FaceInstance> FaceInstances;
2632   FaceInstances m_faceInstances;
2633 public:
2634   void insert(FaceInstance& faceInstance)
2635   {
2636     m_faceInstances.append(faceInstance);
2637   }
2638   void erase(FaceInstance& faceInstance)
2639   {
2640     m_faceInstances.erase(faceInstance);
2641   }
2642
2643   template<typename Functor>
2644   void foreach(Functor functor)
2645   {
2646     for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
2647     {
2648       functor(*(*i));
2649     }
2650   }
2651
2652   bool empty() const
2653   {
2654     return m_faceInstances.empty();
2655   }
2656   FaceInstance& last() const
2657   {
2658     return m_faceInstances.back();
2659   }
2660 };
2661
2662 extern FaceInstanceSet g_SelectedFaceInstances;
2663
2664 typedef std::list<std::size_t> VertexSelection;
2665
2666 inline VertexSelection::iterator VertexSelection_find(VertexSelection& self, std::size_t value)
2667 {
2668   return std::find(self.begin(), self.end(), value);
2669 }
2670
2671 inline VertexSelection::const_iterator VertexSelection_find(const VertexSelection& self, std::size_t value)
2672 {
2673   return std::find(self.begin(), self.end(), value);
2674 }
2675
2676 inline VertexSelection::iterator VertexSelection_insert(VertexSelection& self, std::size_t value)
2677 {
2678   VertexSelection::iterator i = VertexSelection_find(self, value);
2679   if(i == self.end())
2680   {
2681     self.push_back(value);
2682     return --self.end();
2683   }
2684   return i;
2685 }
2686 inline void VertexSelection_erase(VertexSelection& self, std::size_t value)
2687 {
2688   VertexSelection::iterator i = VertexSelection_find(self, value);
2689   if(i != self.end())
2690   {
2691     self.erase(i);
2692   }
2693 }
2694
2695 inline bool triangle_reversed(std::size_t x, std::size_t y, std::size_t z)
2696 {
2697   return !((x < y && y < z) || (z < x && x < y) || (y < z && z < x));
2698 }
2699 template<typename Element>
2700 inline Vector3 triangle_cross(const BasicVector3<Element>& x, const BasicVector3<Element> y, const BasicVector3<Element>& z)
2701 {
2702   return vector3_cross(y - x, z - x);
2703 }
2704 template<typename Element>
2705 inline bool triangles_same_winding(const BasicVector3<Element>& x1, const BasicVector3<Element> y1, const BasicVector3<Element>& z1, const BasicVector3<Element>& x2, const BasicVector3<Element> y2, const BasicVector3<Element>& z2)
2706 {
2707   return vector3_dot(triangle_cross(x1, y1, z1), triangle_cross(x2, y2, z2)) > 0;
2708 }
2709
2710
2711 typedef const Plane3* PlanePointer;
2712 typedef PlanePointer* PlanesIterator;
2713
2714 class VectorLightList : public LightList
2715 {
2716   typedef std::vector<const RendererLight*> Lights;
2717   Lights m_lights;
2718 public:
2719   void addLight(const RendererLight& light)
2720   {
2721     m_lights.push_back(&light);
2722   }
2723   void clear()
2724   {
2725     m_lights.clear();
2726   }
2727   void evaluateLights() const
2728   {
2729   }
2730   void lightsChanged() const
2731   {
2732   }
2733   void forEachLight(const RendererLightCallback& callback) const
2734   {
2735     for(Lights::const_iterator i = m_lights.begin(); i != m_lights.end(); ++i)
2736     {
2737       callback(*(*i));
2738     }
2739   }
2740 };
2741
2742 class FaceInstance
2743 {
2744   Face* m_face;
2745   ObservedSelectable m_selectable;
2746   ObservedSelectable m_selectableVertices;
2747   ObservedSelectable m_selectableEdges;
2748   SelectionChangeCallback m_selectionChanged;
2749
2750   VertexSelection m_vertexSelection;
2751   VertexSelection m_edgeSelection;
2752
2753 public:
2754   mutable VectorLightList m_lights;
2755
2756   FaceInstance(Face& face, const SelectionChangeCallback& observer) :
2757     m_face(&face),
2758     m_selectable(SelectedChangedCaller(*this)),
2759     m_selectableVertices(observer),
2760     m_selectableEdges(observer),
2761     m_selectionChanged(observer)
2762   {
2763   }
2764   FaceInstance(const FaceInstance& other) :
2765     m_face(other.m_face),
2766     m_selectable(SelectedChangedCaller(*this)),
2767     m_selectableVertices(other.m_selectableVertices),
2768     m_selectableEdges(other.m_selectableEdges),
2769     m_selectionChanged(other.m_selectionChanged)
2770   {
2771   }
2772   FaceInstance& operator=(const FaceInstance& other)
2773   {
2774     m_face = other.m_face;
2775     return *this;
2776   }
2777
2778   Face& getFace()
2779   {
2780     return *m_face;
2781   }
2782   const Face& getFace() const
2783   {
2784     return *m_face;
2785   }
2786
2787   void selectedChanged(const Selectable& selectable)
2788   {
2789     if(selectable.isSelected())
2790     {
2791       g_SelectedFaceInstances.insert(*this);
2792     }
2793     else
2794     {
2795       g_SelectedFaceInstances.erase(*this);
2796     }
2797     m_selectionChanged(selectable);
2798   }
2799   typedef MemberCaller1<FaceInstance, const Selectable&, &FaceInstance::selectedChanged> SelectedChangedCaller;
2800
2801   bool selectedVertices() const
2802   {
2803     return !m_vertexSelection.empty();
2804   }
2805   bool selectedEdges() const
2806   {
2807     return !m_edgeSelection.empty();
2808   }
2809   bool isSelected() const
2810   {
2811     return m_selectable.isSelected();
2812   }
2813
2814   bool selectedComponents() const
2815   {
2816     return selectedVertices() || selectedEdges() || isSelected();
2817   }
2818   bool selectedComponents(SelectionSystem::EComponentMode mode) const
2819   {
2820     switch(mode)
2821     {
2822     case SelectionSystem::eVertex:
2823       return selectedVertices();
2824     case SelectionSystem::eEdge:
2825       return selectedEdges();
2826     case SelectionSystem::eFace:
2827       return isSelected();
2828     default:
2829       return false;
2830     }
2831   }
2832   void setSelected(SelectionSystem::EComponentMode mode, bool select)
2833   {
2834     switch(mode)
2835     {
2836     case SelectionSystem::eFace:
2837       m_selectable.setSelected(select);
2838       break;
2839     case SelectionSystem::eVertex:
2840       ASSERT_MESSAGE(!select, "select-all not supported");
2841
2842       m_vertexSelection.clear();
2843       m_selectableVertices.setSelected(false);
2844       break;
2845     case SelectionSystem::eEdge:
2846       ASSERT_MESSAGE(!select, "select-all not supported");
2847
2848       m_edgeSelection.clear();
2849       m_selectableEdges.setSelected(false);
2850       break;
2851     default:
2852       break;
2853     }
2854   }
2855
2856   template<typename Functor>
2857   void SelectedVertices_foreach(Functor functor) const
2858   {
2859     for(VertexSelection::const_iterator i = m_vertexSelection.begin(); i != m_vertexSelection.end(); ++i)
2860     {
2861       std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *i);
2862       if(index != c_brush_maxFaces)
2863       {
2864         functor(getFace().getWinding()[index].vertex);
2865       }
2866     }
2867   }
2868   template<typename Functor>
2869   void SelectedEdges_foreach(Functor functor) const
2870   {
2871     for(VertexSelection::const_iterator i = m_edgeSelection.begin(); i != m_edgeSelection.end(); ++i)
2872     {
2873       std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *i);
2874       if(index != c_brush_maxFaces)
2875       {
2876         const Winding& winding = getFace().getWinding();
2877         std::size_t adjacent = Winding_next(winding, index);
2878         functor(vector3_mid(winding[index].vertex, winding[adjacent].vertex));
2879       }
2880     }
2881   }
2882   template<typename Functor>
2883   void SelectedFaces_foreach(Functor functor) const
2884   {
2885     if(isSelected())
2886     {
2887       functor(centroid());
2888     }
2889   }
2890
2891   template<typename Functor>
2892   void SelectedComponents_foreach(Functor functor) const
2893   {
2894     SelectedVertices_foreach(functor);
2895     SelectedEdges_foreach(functor);
2896     SelectedFaces_foreach(functor);
2897   }
2898
2899   void iterate_selected(AABB& aabb) const
2900   {
2901     SelectedComponents_foreach(AABBExtendByPoint(aabb));
2902   }
2903
2904   class RenderablePointVectorPushBack
2905   {
2906     RenderablePointVector& m_points;
2907   public:
2908     RenderablePointVectorPushBack(RenderablePointVector& points) : m_points(points)
2909     {
2910     }
2911     void operator()(const Vector3& point) const
2912     {
2913       const Colour4b colour_selected(0, 0, 255, 255);
2914       m_points.push_back(pointvertex_for_windingpoint(point, colour_selected));
2915     }
2916   };
2917   
2918   void iterate_selected(RenderablePointVector& points) const
2919   {
2920     SelectedComponents_foreach(RenderablePointVectorPushBack(points));
2921   }
2922   
2923   bool intersectVolume(const VolumeTest& volume, const Matrix4& localToWorld) const
2924   {
2925     return m_face->intersectVolume(volume, localToWorld);
2926   }
2927
2928   void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
2929   {
2930     if(!m_face->isFiltered() && m_face->contributes() && intersectVolume(volume, localToWorld))
2931     {
2932       renderer.PushState();
2933       if(selectedComponents())
2934       {
2935         renderer.Highlight(Renderer::eFace);
2936       }
2937       m_face->render(renderer, localToWorld);
2938       renderer.PopState();
2939     }
2940   }
2941
2942   void testSelect(SelectionTest& test, SelectionIntersection& best)
2943   {
2944     if(!m_face->isFiltered())
2945     {
2946       m_face->testSelect(test, best);
2947     }
2948   }
2949   void testSelect(Selector& selector, SelectionTest& test)
2950   {
2951     SelectionIntersection best;
2952     testSelect(test, best);
2953     if(best.valid())
2954     {
2955       Selector_add(selector, m_selectable, best);
2956     }
2957   }
2958   void testSelect_centroid(Selector& selector, SelectionTest& test)
2959   {
2960     if(m_face->contributes() && !m_face->isFiltered())
2961     {
2962       SelectionIntersection best;
2963       m_face->testSelect_centroid(test, best);
2964       if(best.valid())
2965       {
2966         Selector_add(selector, m_selectable, best);
2967       }
2968     }
2969   }
2970
2971   void selectPlane(Selector& selector, const Line& line, PlanesIterator first, PlanesIterator last, const PlaneCallback& selectedPlaneCallback)
2972   {
2973     for(Winding::const_iterator i = getFace().getWinding().begin(); i != getFace().getWinding().end(); ++i)
2974     {
2975       Vector3 v(vector3_subtracted(line_closest_point(line, (*i).vertex), (*i).vertex));
2976       double dot = vector3_dot(getFace().plane3().normal(), v);
2977       if(dot <= 0)
2978       {
2979         return;
2980       }
2981     }
2982
2983     Selector_add(selector, m_selectable);
2984
2985     selectedPlaneCallback(getFace().plane3());
2986   }
2987   void selectReversedPlane(Selector& selector, const SelectedPlanes& selectedPlanes)
2988   {
2989     if(selectedPlanes.contains(plane3_flipped(getFace().plane3())))
2990     {
2991       Selector_add(selector, m_selectable);
2992     }
2993   }
2994
2995   void transformComponents(const Matrix4& matrix)
2996   {
2997     if(isSelected())
2998     {
2999       m_face->transform(matrix, false);
3000     }
3001     if(selectedVertices())
3002     {
3003       if(m_vertexSelection.size() == 1)
3004       {
3005         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3006         m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3007       }
3008       else if(m_vertexSelection.size() == 2)
3009       {
3010         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3011         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]);
3012         m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3013       }
3014       else if(m_vertexSelection.size() >= 3)
3015       {
3016         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]);
3017         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3018         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]);
3019         m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3020       }
3021     }
3022     if(selectedEdges())
3023     {
3024       if(m_edgeSelection.size() == 1)
3025       {
3026         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]);
3027         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3028         m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3029       }
3030       else if(m_edgeSelection.size() >= 2)
3031       {
3032         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[0]);
3033         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[1]);
3034         matrix4_transform_point(matrix, m_face->m_move_planeptsTransformed[2]);
3035         m_face->assign_planepts(m_face->m_move_planeptsTransformed);
3036       }
3037     }
3038   }
3039
3040   void snapto(float snap)
3041   {
3042     m_face->snapto(snap);
3043   }
3044
3045   void snapComponents(float snap)
3046   {
3047     if(isSelected())
3048     {
3049       snapto(snap);
3050     }
3051     if(selectedVertices())
3052     {
3053       vector3_snap(m_face->m_move_planepts[0], snap);
3054       vector3_snap(m_face->m_move_planepts[1], snap);
3055       vector3_snap(m_face->m_move_planepts[2], snap);
3056       m_face->assign_planepts(m_face->m_move_planepts);
3057       planepts_assign(m_face->m_move_planeptsTransformed, m_face->m_move_planepts);
3058       m_face->freezeTransform();
3059     }
3060     if(selectedEdges())
3061     {
3062       vector3_snap(m_face->m_move_planepts[0], snap);
3063       vector3_snap(m_face->m_move_planepts[1], snap);
3064       vector3_snap(m_face->m_move_planepts[2], snap);
3065       m_face->assign_planepts(m_face->m_move_planepts);
3066       planepts_assign(m_face->m_move_planeptsTransformed, m_face->m_move_planepts);
3067       m_face->freezeTransform();
3068     }
3069   }
3070   void update_move_planepts_vertex(std::size_t index)
3071   {
3072     m_face->update_move_planepts_vertex(index, m_face->m_move_planepts);
3073   }
3074   void update_move_planepts_vertex2(std::size_t index, std::size_t other)
3075   {
3076     const std::size_t numpoints = m_face->getWinding().numpoints;
3077     ASSERT_MESSAGE(index < numpoints, "select_vertex: invalid index");
3078
3079     const std::size_t opposite = Winding_Opposite(m_face->getWinding(), index, other);
3080
3081     if(triangle_reversed(index, other, opposite))
3082     {
3083       std::swap(index, other);
3084     }
3085
3086     ASSERT_MESSAGE(
3087       triangles_same_winding(
3088         m_face->getWinding()[opposite].vertex,
3089         m_face->getWinding()[index].vertex,
3090         m_face->getWinding()[other].vertex,
3091         m_face->getWinding()[0].vertex,
3092         m_face->getWinding()[1].vertex,
3093         m_face->getWinding()[2].vertex
3094       ),
3095       "update_move_planepts_vertex2: error"
3096     )
3097
3098     m_face->m_move_planepts[0] = m_face->getWinding()[opposite].vertex;
3099     m_face->m_move_planepts[1] = m_face->getWinding()[index].vertex;
3100     m_face->m_move_planepts[2] = m_face->getWinding()[other].vertex;
3101     planepts_quantise(m_face->m_move_planepts, GRID_MIN); // winding points are very inaccurate
3102   }
3103   void update_selection_vertex()
3104   {
3105     if(m_vertexSelection.size() == 0)
3106     {
3107       m_selectableVertices.setSelected(false);
3108     }
3109     else
3110     {
3111       m_selectableVertices.setSelected(true);
3112
3113       if(m_vertexSelection.size() == 1)
3114       {
3115         std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_vertexSelection.begin());
3116
3117         if(index != c_brush_maxFaces)
3118         {
3119           update_move_planepts_vertex(index);
3120         }
3121       }
3122       else if(m_vertexSelection.size() == 2)
3123       {
3124         std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_vertexSelection.begin());
3125         std::size_t other = Winding_FindAdjacent(getFace().getWinding(), *(++m_vertexSelection.begin()));
3126
3127         if(index != c_brush_maxFaces
3128           && other != c_brush_maxFaces)
3129         {
3130           update_move_planepts_vertex2(index, other);
3131         }
3132       }
3133     }
3134   }
3135   void select_vertex(std::size_t index, bool select)
3136   {
3137     if(select)
3138     {
3139       VertexSelection_insert(m_vertexSelection, getFace().getWinding()[index].adjacent);
3140     }
3141     else
3142     {
3143       VertexSelection_erase(m_vertexSelection, getFace().getWinding()[index].adjacent);
3144     }
3145
3146     SceneChangeNotify();
3147     update_selection_vertex();
3148   }
3149
3150   bool selected_vertex(std::size_t index) const
3151   {
3152     return VertexSelection_find(m_vertexSelection, getFace().getWinding()[index].adjacent) != m_vertexSelection.end();
3153   }
3154
3155   void update_move_planepts_edge(std::size_t index)
3156   {
3157     std::size_t numpoints = m_face->getWinding().numpoints;
3158     ASSERT_MESSAGE(index < numpoints, "select_edge: invalid index");
3159
3160     std::size_t adjacent = Winding_next(m_face->getWinding(), index);
3161     std::size_t opposite = Winding_Opposite(m_face->getWinding(), index);
3162     m_face->m_move_planepts[0] = m_face->getWinding()[index].vertex;
3163     m_face->m_move_planepts[1] = m_face->getWinding()[adjacent].vertex;
3164     m_face->m_move_planepts[2] = m_face->getWinding()[opposite].vertex;
3165     planepts_quantise(m_face->m_move_planepts, GRID_MIN); // winding points are very inaccurate
3166   }
3167   void update_selection_edge()
3168   {
3169     if(m_edgeSelection.size() == 0)
3170     {
3171       m_selectableEdges.setSelected(false);
3172     }
3173     else
3174     {
3175       m_selectableEdges.setSelected(true);
3176
3177       if(m_edgeSelection.size() == 1)
3178       {
3179         std::size_t index = Winding_FindAdjacent(getFace().getWinding(), *m_edgeSelection.begin());
3180
3181         if(index != c_brush_maxFaces)
3182         {
3183           update_move_planepts_edge(index);
3184         }
3185       }
3186     }
3187   }
3188   void select_edge(std::size_t index, bool select)
3189   {
3190     if(select)
3191     {
3192       VertexSelection_insert(m_edgeSelection, getFace().getWinding()[index].adjacent);
3193     }
3194     else
3195     {
3196       VertexSelection_erase(m_edgeSelection, getFace().getWinding()[index].adjacent);
3197     }
3198
3199     SceneChangeNotify();
3200     update_selection_edge();
3201   }
3202
3203   bool selected_edge(std::size_t index) const
3204   {
3205     return VertexSelection_find(m_edgeSelection, getFace().getWinding()[index].adjacent) != m_edgeSelection.end();
3206   }
3207
3208   const Vector3& centroid() const
3209   {
3210     return m_face->centroid();
3211   }
3212
3213   void connectivityChanged()
3214   {
3215     // This occurs when a face is added or removed.
3216     // The current vertex and edge selections no longer valid and must be cleared.
3217     m_vertexSelection.clear();
3218     m_selectableVertices.setSelected(false);
3219     m_edgeSelection.clear();
3220     m_selectableEdges.setSelected(false);
3221   }
3222 };
3223
3224 class BrushClipPlane : public OpenGLRenderable
3225 {
3226   Plane3 m_plane;
3227   Winding m_winding;
3228   static Shader* m_state;
3229 public:
3230   static void constructStatic()
3231   {
3232     m_state = GlobalShaderCache().capture("$CLIPPER_OVERLAY");
3233   }
3234   static void destroyStatic()
3235   {
3236     GlobalShaderCache().release("$CLIPPER_OVERLAY");
3237   }
3238
3239   void setPlane(const Brush& brush, const Plane3& plane)
3240   {
3241     m_plane = plane;
3242     if(plane3_valid(m_plane))
3243     {
3244       brush.windingForClipPlane(m_winding, m_plane);
3245     }
3246     else
3247     {
3248       m_winding.resize(0);
3249     }
3250   }
3251
3252   void render(RenderStateFlags state) const
3253   {
3254     if((state & RENDER_FILL) != 0)
3255     {
3256       Winding_Draw(m_winding, m_plane.normal(), state);
3257     }
3258     else
3259     {
3260       Winding_DrawWireframe(m_winding);
3261     }
3262   }
3263
3264   void render(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
3265   {
3266     renderer.SetState(m_state, Renderer::eWireframeOnly);
3267     renderer.SetState(m_state, Renderer::eFullMaterials);
3268     renderer.addRenderable(*this, localToWorld);
3269   }
3270 };
3271
3272 inline void Face_addLight(const FaceInstance& face, const Matrix4& localToWorld, const RendererLight& light)
3273 {
3274   const Plane3& facePlane = face.getFace().plane3();
3275   const Vector3& origin = light.aabb().origin;
3276   Plane3 tmp(plane3_transformed(Plane3(facePlane.normal(), -facePlane.dist()), localToWorld));
3277   if(!plane3_test_point(tmp, origin)
3278     || !plane3_test_point(tmp, vector3_added(origin, light.offset())))
3279   {
3280     face.m_lights.addLight(light);
3281   }
3282 }
3283
3284
3285
3286 typedef std::vector<FaceInstance> FaceInstances;
3287
3288 class EdgeInstance : public Selectable
3289 {
3290   FaceInstances& m_faceInstances;
3291   SelectableEdge* m_edge;
3292
3293   void select_edge(bool select)
3294   {
3295     FaceVertexId faceVertex = m_edge->m_faceVertex;
3296     m_faceInstances[faceVertex.getFace()].select_edge(faceVertex.getVertex(), select);
3297     faceVertex = next_edge(m_edge->m_faces, faceVertex);
3298     m_faceInstances[faceVertex.getFace()].select_edge(faceVertex.getVertex(), select);
3299   }
3300   bool selected_edge() const
3301   {
3302     FaceVertexId faceVertex = m_edge->m_faceVertex;
3303     if(!m_faceInstances[faceVertex.getFace()].selected_edge(faceVertex.getVertex()))
3304     {
3305       return false;
3306     }
3307     faceVertex = next_edge(m_edge->m_faces, faceVertex);
3308     if(!m_faceInstances[faceVertex.getFace()].selected_edge(faceVertex.getVertex()))
3309     {
3310       return false;
3311     }
3312
3313     return true;
3314   }
3315
3316 public:
3317   EdgeInstance(FaceInstances& faceInstances, SelectableEdge& edge)
3318     : m_faceInstances(faceInstances), m_edge(&edge)
3319   {
3320   }
3321   EdgeInstance& operator=(const EdgeInstance& other)
3322   {
3323     m_edge = other.m_edge;
3324     return *this;
3325   }
3326
3327   void setSelected(bool select)
3328   {
3329     select_edge(select);
3330   }
3331   bool isSelected() const
3332   {
3333     return selected_edge();
3334   }
3335
3336
3337   void testSelect(Selector& selector, SelectionTest& test)
3338   {
3339     SelectionIntersection best;
3340     m_edge->testSelect(test, best);
3341     if(best.valid())
3342     {
3343       Selector_add(selector, *this, best);
3344     }
3345   }
3346 };
3347
3348 class VertexInstance : public Selectable
3349 {
3350   FaceInstances& m_faceInstances;
3351   SelectableVertex* m_vertex;
3352
3353   void select_vertex(bool select)
3354   {
3355     FaceVertexId faceVertex = m_vertex->m_faceVertex;
3356     do
3357     {
3358       m_faceInstances[faceVertex.getFace()].select_vertex(faceVertex.getVertex(), select);
3359       faceVertex = next_vertex(m_vertex->m_faces, faceVertex);
3360     }
3361     while(faceVertex.getFace() != m_vertex->m_faceVertex.getFace());
3362   }
3363   bool selected_vertex() const
3364   {
3365     FaceVertexId faceVertex = m_vertex->m_faceVertex;
3366     do
3367     {
3368       if(!m_faceInstances[faceVertex.getFace()].selected_vertex(faceVertex.getVertex()))
3369       {
3370         return false;
3371       }
3372       faceVertex = next_vertex(m_vertex->m_faces, faceVertex);
3373     }
3374     while(faceVertex.getFace() != m_vertex->m_faceVertex.getFace());
3375     return true;
3376   }
3377
3378 public:
3379   VertexInstance(FaceInstances& faceInstances, SelectableVertex& vertex)
3380     : m_faceInstances(faceInstances), m_vertex(&vertex)
3381   {
3382   }
3383   VertexInstance& operator=(const VertexInstance& other)
3384   {
3385     m_vertex = other.m_vertex;
3386     return *this;
3387   }
3388
3389   void setSelected(bool select)
3390   {
3391     select_vertex(select);
3392   }
3393   bool isSelected() const
3394   {
3395     return selected_vertex();
3396   }
3397
3398   void testSelect(Selector& selector, SelectionTest& test)
3399   {
3400     SelectionIntersection best;
3401     m_vertex->testSelect(test, best);
3402     if(best.valid())
3403     {
3404       Selector_add(selector, *this, best);
3405     }
3406   }
3407 };
3408
3409 class BrushInstanceVisitor
3410 {
3411 public:
3412   virtual void visit(FaceInstance& face) const = 0;
3413 };
3414
3415 class BrushInstance :
3416 public BrushObserver,
3417 public scene::Instance,
3418 public Selectable,
3419 public Renderable,
3420 public SelectionTestable,
3421 public ComponentSelectionTestable,
3422 public ComponentEditable,
3423 public ComponentSnappable,
3424 public PlaneSelectable,
3425 public LightCullable
3426 {
3427   class TypeCasts
3428   {
3429     InstanceTypeCastTable m_casts;
3430   public:
3431     TypeCasts()
3432     {
3433       InstanceStaticCast<BrushInstance, Selectable>::install(m_casts);
3434       InstanceContainedCast<BrushInstance, Bounded>::install(m_casts);
3435       InstanceContainedCast<BrushInstance, Cullable>::install(m_casts);
3436       InstanceStaticCast<BrushInstance, Renderable>::install(m_casts);
3437       InstanceStaticCast<BrushInstance, SelectionTestable>::install(m_casts);
3438       InstanceStaticCast<BrushInstance, ComponentSelectionTestable>::install(m_casts);
3439       InstanceStaticCast<BrushInstance, ComponentEditable>::install(m_casts);
3440       InstanceStaticCast<BrushInstance, ComponentSnappable>::install(m_casts);
3441       InstanceStaticCast<BrushInstance, PlaneSelectable>::install(m_casts);
3442       InstanceIdentityCast<BrushInstance>::install(m_casts);
3443       InstanceContainedCast<BrushInstance, Transformable>::install(m_casts);
3444     }
3445     InstanceTypeCastTable& get()
3446     {
3447       return m_casts;
3448     }
3449   };
3450
3451
3452   Brush& m_brush;
3453
3454   FaceInstances m_faceInstances;
3455
3456   typedef std::vector<EdgeInstance> EdgeInstances;
3457   EdgeInstances m_edgeInstances;
3458   typedef std::vector<VertexInstance> VertexInstances;
3459   VertexInstances m_vertexInstances;
3460
3461   ObservedSelectable m_selectable;
3462
3463   mutable RenderableWireframe m_render_wireframe;
3464   mutable RenderablePointVector m_render_selected;
3465   mutable AABB m_aabb_component;
3466   mutable Array<PointVertex> m_faceCentroidPointsCulled;
3467   RenderablePointArray m_render_faces_wireframe;
3468   mutable bool m_viewChanged; // requires re-evaluation of view-dependent cached data
3469
3470   BrushClipPlane m_clipPlane;
3471
3472   static Shader* m_state_selpoint;
3473
3474   const LightList* m_lightList;
3475
3476   TransformModifier m_transform;
3477
3478   BrushInstance(const BrushInstance& other); // NOT COPYABLE
3479   BrushInstance& operator=(const BrushInstance& other); // NOT ASSIGNABLE
3480 public:
3481   static Counter* m_counter;
3482
3483   typedef LazyStatic<TypeCasts> StaticTypeCasts;
3484
3485   void lightsChanged()
3486   {
3487     m_lightList->lightsChanged();
3488   }
3489   typedef MemberCaller<BrushInstance, &BrushInstance::lightsChanged> LightsChangedCaller;
3490
3491   STRING_CONSTANT(Name, "BrushInstance");
3492
3493   BrushInstance(const scene::Path& path, scene::Instance* parent, Brush& brush) :
3494     Instance(path, parent, this, StaticTypeCasts::instance().get()),
3495     m_brush(brush),
3496     m_selectable(SelectedChangedCaller(*this)),
3497     m_render_selected(GL_POINTS),
3498     m_render_faces_wireframe(m_faceCentroidPointsCulled, GL_POINTS),
3499     m_viewChanged(false),
3500     m_transform(Brush::TransformChangedCaller(m_brush), ApplyTransformCaller(*this))
3501   {
3502     m_brush.instanceAttach(Instance::path());
3503     m_brush.attach(*this);
3504     m_counter->increment();
3505
3506     m_lightList = &GlobalShaderCache().attach(*this);
3507     m_brush.m_lightsChanged = LightsChangedCaller(*this); ///\todo Make this work with instancing.
3508
3509     Instance::setTransformChangedCallback(LightsChangedCaller(*this));
3510   }
3511   ~BrushInstance()
3512   {
3513     Instance::setTransformChangedCallback(Callback());
3514
3515     m_brush.m_lightsChanged = Callback();
3516     GlobalShaderCache().detach(*this);
3517
3518     m_counter->decrement();
3519     m_brush.detach(*this);
3520     m_brush.instanceDetach(Instance::path());
3521   }
3522
3523   Brush& getBrush()
3524   {
3525     return m_brush;
3526   }
3527   const Brush& getBrush() const
3528   {
3529     return m_brush;
3530   }
3531
3532   Bounded& get(NullType<Bounded>)
3533   {
3534     return m_brush;
3535   }
3536   Cullable& get(NullType<Cullable>)
3537   {
3538     return m_brush;
3539   }
3540   Transformable& get(NullType<Transformable>)
3541   {
3542     return m_transform;
3543   }
3544
3545   void selectedChanged(const Selectable& selectable)
3546   {
3547     GlobalSelectionSystem().getObserver(SelectionSystem::ePrimitive)(selectable);
3548     GlobalSelectionSystem().onSelectedChanged(*this, selectable);
3549
3550     Instance::selectedChanged();
3551   }
3552   typedef MemberCaller1<BrushInstance, const Selectable&, &BrushInstance::selectedChanged> SelectedChangedCaller;
3553
3554   void selectedChangedComponent(const Selectable& selectable)
3555   {
3556     GlobalSelectionSystem().getObserver(SelectionSystem::eComponent)(selectable);
3557     GlobalSelectionSystem().onComponentSelection(*this, selectable);
3558   }
3559   typedef MemberCaller1<BrushInstance, const Selectable&, &BrushInstance::selectedChangedComponent> SelectedChangedComponentCaller;
3560
3561   const BrushInstanceVisitor& forEachFaceInstance(const BrushInstanceVisitor& visitor)
3562   {
3563     for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3564     {
3565       visitor.visit(*i);
3566     }
3567     return visitor;
3568   }
3569
3570   static void constructStatic()
3571   {
3572     m_state_selpoint = GlobalShaderCache().capture("$SELPOINT");
3573   }
3574   static void destroyStatic()
3575   {
3576     GlobalShaderCache().release("$SELPOINT");
3577   }
3578
3579   void clear()
3580   {
3581     m_faceInstances.clear();
3582   }
3583   void reserve(std::size_t size)
3584   {
3585     m_faceInstances.reserve(size);
3586   }
3587
3588   void push_back(Face& face)
3589   {
3590     m_faceInstances.push_back(FaceInstance(face, SelectedChangedComponentCaller(*this)));
3591   }
3592   void pop_back()
3593   {
3594     ASSERT_MESSAGE(!m_faceInstances.empty(), "erasing invalid element");
3595     m_faceInstances.pop_back();
3596   }
3597   void erase(std::size_t index)
3598   {
3599     ASSERT_MESSAGE(index < m_faceInstances.size(), "erasing invalid element");
3600     m_faceInstances.erase(m_faceInstances.begin() + index);
3601   }
3602   void connectivityChanged()
3603   {
3604     for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3605     {
3606       (*i).connectivityChanged();
3607     }
3608   }
3609
3610   void edge_clear()
3611   {
3612     m_edgeInstances.clear();
3613   }
3614   void edge_push_back(SelectableEdge& edge)
3615   {
3616     m_edgeInstances.push_back(EdgeInstance(m_faceInstances, edge));
3617   }
3618
3619   void vertex_clear()
3620   {
3621     m_vertexInstances.clear();
3622   }
3623   void vertex_push_back(SelectableVertex& vertex)
3624   {
3625     m_vertexInstances.push_back(VertexInstance(m_faceInstances, vertex));
3626   }
3627
3628   void DEBUG_verify() const
3629   {
3630     ASSERT_MESSAGE(m_faceInstances.size() == m_brush.DEBUG_size(), "FATAL: mismatch");
3631   }
3632
3633   bool isSelected() const
3634   {
3635     return m_selectable.isSelected();
3636   }
3637   void setSelected(bool select)
3638   {
3639     m_selectable.setSelected(select);
3640   }
3641
3642   void update_selected() const
3643   {
3644     m_render_selected.clear();
3645     for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3646     {
3647       if((*i).getFace().contributes())
3648       {
3649         (*i).iterate_selected(m_render_selected);
3650       }
3651     }
3652   }
3653
3654   void evaluateViewDependent(const VolumeTest& volume, const Matrix4& localToWorld) const
3655   {
3656     if(m_viewChanged)
3657     {
3658       m_viewChanged = false;
3659
3660       bool faces_visible[c_brush_maxFaces];
3661       {
3662         bool* j = faces_visible;
3663         for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i, ++j)
3664         {
3665           *j = (*i).intersectVolume(volume, localToWorld);
3666         }
3667       }
3668
3669       m_brush.update_wireframe(m_render_wireframe, faces_visible);
3670       m_brush.update_faces_wireframe(m_faceCentroidPointsCulled, faces_visible);
3671     }
3672   }
3673
3674   void renderComponentsSelected(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
3675   {
3676     m_brush.evaluateBRep();
3677
3678     update_selected();
3679     if(!m_render_selected.empty())
3680     {
3681       renderer.Highlight(Renderer::ePrimitive, false);
3682       renderer.SetState(m_state_selpoint, Renderer::eWireframeOnly);
3683       renderer.SetState(m_state_selpoint, Renderer::eFullMaterials);
3684       renderer.addRenderable(m_render_selected, localToWorld);
3685     }
3686   }
3687
3688   void renderComponents(Renderer& renderer, const VolumeTest& volume) const
3689   {
3690     m_brush.evaluateBRep();
3691
3692     const Matrix4& localToWorld = Instance::localToWorld();
3693
3694     renderer.SetState(m_brush.m_state_point, Renderer::eWireframeOnly);
3695     renderer.SetState(m_brush.m_state_point, Renderer::eFullMaterials);
3696
3697     if(volume.fill() && GlobalSelectionSystem().ComponentMode() == SelectionSystem::eFace)
3698     {
3699       evaluateViewDependent(volume, localToWorld);
3700       renderer.addRenderable(m_render_faces_wireframe, localToWorld);
3701     }
3702     else
3703     {
3704       m_brush.renderComponents(GlobalSelectionSystem().ComponentMode(), renderer, volume, localToWorld);
3705     }
3706   }
3707
3708   void renderClipPlane(Renderer& renderer, const VolumeTest& volume) const
3709   {
3710     if(GlobalSelectionSystem().ManipulatorMode() == SelectionSystem::eClip && isSelected())
3711     {
3712       m_clipPlane.render(renderer, volume, localToWorld());
3713     }
3714   }
3715
3716   void renderCommon(Renderer& renderer, const VolumeTest& volume) const
3717   {
3718     bool componentMode = GlobalSelectionSystem().Mode() == SelectionSystem::eComponent;
3719     
3720     if(componentMode && isSelected())
3721     {
3722       renderComponents(renderer, volume);
3723     }
3724     
3725     if(parentSelected())
3726     {
3727       if(!componentMode)
3728       {
3729         renderer.Highlight(Renderer::eFace);
3730       }
3731       renderer.Highlight(Renderer::ePrimitive);
3732     }
3733   }
3734
3735   void renderSolid(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
3736   {
3737     //renderCommon(renderer, volume);
3738
3739     m_lightList->evaluateLights();
3740
3741     for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3742     {
3743       renderer.setLights((*i).m_lights);
3744       (*i).render(renderer, volume, localToWorld);
3745     }
3746
3747     renderComponentsSelected(renderer, volume, localToWorld);
3748   }
3749
3750   void renderWireframe(Renderer& renderer, const VolumeTest& volume, const Matrix4& localToWorld) const
3751   {
3752     //renderCommon(renderer, volume);
3753
3754     evaluateViewDependent(volume, localToWorld);
3755
3756     if(m_render_wireframe.m_size != 0)
3757     {
3758       renderer.addRenderable(m_render_wireframe, localToWorld);
3759     }
3760
3761     renderComponentsSelected(renderer, volume, localToWorld);
3762   }
3763
3764   void renderSolid(Renderer& renderer, const VolumeTest& volume) const
3765   {
3766     m_brush.evaluateBRep();
3767
3768     renderClipPlane(renderer, volume);
3769
3770     renderSolid(renderer, volume, localToWorld());
3771   }
3772
3773   void renderWireframe(Renderer& renderer, const VolumeTest& volume) const
3774   {
3775     m_brush.evaluateBRep();
3776
3777     renderClipPlane(renderer, volume);
3778
3779     renderWireframe(renderer, volume, localToWorld());
3780   }
3781
3782   void viewChanged() const
3783   {
3784     m_viewChanged = true;
3785   }
3786
3787   void testSelect(Selector& selector, SelectionTest& test)
3788   {
3789     test.BeginMesh(localToWorld());
3790
3791     SelectionIntersection best;
3792     for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3793     {
3794       (*i).testSelect(test, best);
3795     }
3796     if(best.valid())
3797     {
3798       selector.addIntersection(best);
3799     }
3800   }
3801
3802   bool isSelectedComponents() const
3803   {
3804     for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3805     {
3806       if((*i).selectedComponents())
3807       {
3808         return true;
3809       }
3810     }
3811     return false;
3812   }
3813   void setSelectedComponents(bool select, SelectionSystem::EComponentMode mode)
3814   {
3815     for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3816     {
3817       (*i).setSelected(mode, select);
3818     }
3819   }
3820   void testSelectComponents(Selector& selector, SelectionTest& test, SelectionSystem::EComponentMode mode)
3821   {
3822     test.BeginMesh(localToWorld());
3823
3824     switch(mode)
3825     {
3826     case SelectionSystem::eVertex:
3827       {
3828         for(VertexInstances::iterator i = m_vertexInstances.begin(); i != m_vertexInstances.end(); ++i)
3829         {
3830           (*i).testSelect(selector, test);
3831         }
3832       }
3833       break;
3834     case SelectionSystem::eEdge:
3835       {
3836         for(EdgeInstances::iterator i = m_edgeInstances.begin(); i != m_edgeInstances.end(); ++i)
3837         {
3838           (*i).testSelect(selector, test);
3839         }
3840       }
3841       break;
3842     case SelectionSystem::eFace:
3843       {
3844         if(test.getVolume().fill())
3845         {
3846           for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3847           {
3848             (*i).testSelect(selector, test);
3849           }
3850         }
3851         else
3852         {
3853           for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3854           {
3855             (*i).testSelect_centroid(selector, test);
3856           }
3857         }
3858       }
3859       break;
3860     default:
3861       break;
3862     }
3863   }
3864
3865   void selectPlanes(Selector& selector, SelectionTest& test, const PlaneCallback& selectedPlaneCallback)
3866   {
3867     test.BeginMesh(localToWorld());
3868
3869     PlanePointer brushPlanes[c_brush_maxFaces];
3870     PlanesIterator j = brushPlanes;
3871
3872     for(Brush::const_iterator i = m_brush.begin(); i != m_brush.end(); ++i)
3873     {
3874       *j++ = &(*i)->plane3();
3875     }
3876
3877     for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3878     {
3879       (*i).selectPlane(selector, Line(test.getNear(), test.getFar()), brushPlanes, j, selectedPlaneCallback);
3880     }
3881   }
3882   void selectReversedPlanes(Selector& selector, const SelectedPlanes& selectedPlanes)
3883   {
3884     for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3885     {
3886       (*i).selectReversedPlane(selector, selectedPlanes);
3887     }
3888   }
3889
3890
3891   void transformComponents(const Matrix4& matrix)
3892   {
3893     for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3894     {
3895       (*i).transformComponents(matrix);
3896     }
3897   }
3898   const AABB& getSelectedComponentsBounds() const
3899   {
3900     m_aabb_component = AABB();
3901
3902     for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3903     {
3904       (*i).iterate_selected(m_aabb_component);
3905     }
3906
3907     return m_aabb_component;
3908   }
3909
3910   void snapComponents(float snap)
3911   {
3912     for(FaceInstances::iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3913     {
3914       (*i).snapComponents(snap);
3915     }
3916   }
3917   void evaluateTransform()
3918   {
3919     Matrix4 matrix(m_transform.calculateTransform());
3920     //globalOutputStream() << "matrix: " << matrix << "\n";
3921
3922     if(m_transform.getType() == TRANSFORM_PRIMITIVE)
3923     {
3924       m_brush.transform(matrix);
3925     }
3926     else
3927     {
3928       transformComponents(matrix);
3929     }
3930   }
3931   void applyTransform()
3932   {
3933     m_brush.revertTransform();
3934     evaluateTransform();
3935     m_brush.freezeTransform();
3936   }
3937   typedef MemberCaller<BrushInstance, &BrushInstance::applyTransform> ApplyTransformCaller;
3938
3939   void setClipPlane(const Plane3& plane)
3940   {
3941     m_clipPlane.setPlane(m_brush, plane);
3942   }
3943
3944   bool testLight(const RendererLight& light) const
3945   {
3946     return light.testAABB(worldAABB());
3947   }
3948   void insertLight(const RendererLight& light)
3949   {
3950     const Matrix4& localToWorld = Instance::localToWorld();
3951     for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3952     {
3953       Face_addLight(*i, localToWorld, light);
3954     }
3955   }
3956   void clearLights()
3957   {
3958     for(FaceInstances::const_iterator i = m_faceInstances.begin(); i != m_faceInstances.end(); ++i)
3959     {
3960       (*i).m_lights.clear();
3961     }
3962   }
3963 };
3964
3965 inline BrushInstance* Instance_getBrush(scene::Instance& instance)
3966 {
3967   return InstanceTypeCast<BrushInstance>::cast(instance);
3968 }
3969
3970
3971 template<typename Functor>
3972 class BrushSelectedVisitor : public SelectionSystem::Visitor
3973 {
3974   const Functor& m_functor;
3975 public:
3976   BrushSelectedVisitor(const Functor& functor) : m_functor(functor)
3977   {
3978   }
3979   void visit(scene::Instance& instance) const
3980   {
3981     BrushInstance* brush = Instance_getBrush(instance);
3982     if(brush != 0)
3983     {
3984       m_functor(*brush);
3985     }
3986   }
3987 };
3988
3989 template<typename Functor>
3990 inline const Functor& Scene_forEachSelectedBrush(const Functor& functor)
3991 {
3992   GlobalSelectionSystem().foreachSelected(BrushSelectedVisitor<Functor>(functor));
3993   return functor;
3994 }
3995
3996 template<typename Functor>
3997 class BrushVisibleSelectedVisitor : public SelectionSystem::Visitor
3998 {
3999   const Functor& m_functor;
4000 public:
4001   BrushVisibleSelectedVisitor(const Functor& functor) : m_functor(functor)
4002   {
4003   }
4004   void visit(scene::Instance& instance) const
4005   {
4006     BrushInstance* brush = Instance_getBrush(instance);
4007     if(brush != 0
4008       && instance.path().top().get().visible())
4009     {
4010       m_functor(*brush);
4011     }
4012   }
4013 };
4014
4015 template<typename Functor>
4016 inline const Functor& Scene_forEachVisibleSelectedBrush(const Functor& functor)
4017 {
4018   GlobalSelectionSystem().foreachSelected(BrushVisibleSelectedVisitor<Functor>(functor));
4019   return functor;
4020 }
4021
4022 class BrushForEachFace
4023 {
4024   const BrushInstanceVisitor& m_visitor;
4025 public:
4026   BrushForEachFace(const BrushInstanceVisitor& visitor) : m_visitor(visitor)
4027   {
4028   }
4029   void operator()(BrushInstance& brush) const
4030   {
4031     brush.forEachFaceInstance(m_visitor);
4032   }
4033 };
4034
4035 template<class Functor>
4036 class FaceInstanceVisitFace : public BrushInstanceVisitor
4037 {
4038   const Functor& functor;
4039 public:
4040   FaceInstanceVisitFace(const Functor& functor)
4041     : functor(functor)
4042   {
4043   }
4044   void visit(FaceInstance& face) const
4045   {
4046     functor(face.getFace());
4047   }
4048 };
4049
4050 template<typename Functor>
4051 inline const Functor& Brush_forEachFace(BrushInstance& brush, const Functor& functor)
4052 {
4053   brush.forEachFaceInstance(FaceInstanceVisitFace<Functor>(functor));
4054   return functor;
4055 }
4056
4057 template<class Functor>
4058 class FaceVisitAll : public BrushVisitor
4059 {
4060   const Functor& functor;
4061 public:
4062   FaceVisitAll(const Functor& functor)
4063     : functor(functor)
4064   {
4065   }
4066   void visit(Face& face) const
4067   {
4068     functor(face);
4069   }
4070 };
4071
4072 template<typename Functor>
4073 inline const Functor& Brush_forEachFace(const Brush& brush, const Functor& functor)
4074 {
4075   brush.forEachFace(FaceVisitAll<Functor>(functor));
4076   return functor;
4077 }
4078
4079 template<typename Functor>
4080 inline const Functor& Brush_forEachFace(Brush& brush, const Functor& functor)
4081 {
4082   brush.forEachFace(FaceVisitAll<Functor>(functor));
4083   return functor;
4084 }
4085
4086 template<class Functor>
4087 class FaceInstanceVisitAll : public BrushInstanceVisitor
4088 {
4089   const Functor& functor;
4090 public:
4091   FaceInstanceVisitAll(const Functor& functor)
4092     : functor(functor)
4093   {
4094   }
4095   void visit(FaceInstance& face) const
4096   {
4097     functor(face);
4098   }
4099 };
4100
4101 template<typename Functor>
4102 inline const Functor& Brush_ForEachFaceInstance(BrushInstance& brush, const Functor& functor)
4103 {
4104   brush.forEachFaceInstance(FaceInstanceVisitAll<Functor>(functor));
4105   return functor;
4106 }
4107
4108 template<typename Functor>
4109 inline const Functor& Scene_forEachBrush(scene::Graph& graph, const Functor& functor)
4110 {
4111   graph.traverse(InstanceWalker< InstanceApply<BrushInstance, Functor> >(functor));
4112   return functor;
4113 }
4114
4115 template<typename Type, typename Functor>
4116 class InstanceIfVisible : public Functor
4117 {
4118 public:
4119   InstanceIfVisible(const Functor& functor) : Functor(functor)
4120   {
4121   }
4122   void operator()(scene::Instance& instance)
4123   {
4124     if(instance.path().top().get().visible())
4125     {
4126       Functor::operator()(instance);
4127     }
4128   }
4129 };
4130
4131 template<typename Functor>
4132 class BrushVisibleWalker : public scene::Graph::Walker
4133 {
4134   const Functor& m_functor;
4135 public:
4136   BrushVisibleWalker(const Functor& functor) : m_functor(functor)
4137   {
4138   }
4139   bool pre(const scene::Path& path, scene::Instance& instance) const
4140   {
4141     if(path.top().get().visible())
4142     {
4143       BrushInstance* brush = Instance_getBrush(instance);
4144       if(brush != 0)
4145       {
4146         m_functor(*brush);
4147       }
4148     }
4149     return true;
4150   }
4151 };
4152
4153 template<typename Functor>
4154 inline const Functor& Scene_forEachVisibleBrush(scene::Graph& graph, const Functor& functor)
4155 {
4156   graph.traverse(BrushVisibleWalker<Functor>(functor));
4157   return functor;
4158 }
4159
4160 template<typename Functor>
4161 inline const Functor& Scene_ForEachBrush_ForEachFace(scene::Graph& graph, const Functor& functor)
4162 {
4163   Scene_forEachBrush(graph, BrushForEachFace(FaceInstanceVisitFace<Functor>(functor)));
4164   return functor;
4165 }
4166
4167 template<typename Functor>
4168 inline const Functor& Scene_ForEachSelectedBrush_ForEachFace(scene::Graph& graph, const Functor& functor)
4169 {
4170   Scene_forEachSelectedBrush(BrushForEachFace(FaceInstanceVisitFace<Functor>(functor)));
4171   return functor;
4172 }
4173
4174 template<typename Functor>
4175 inline const Functor& Scene_ForEachSelectedBrush_ForEachFaceInstance(scene::Graph& graph, const Functor& functor)
4176 {
4177   Scene_forEachSelectedBrush(BrushForEachFace(FaceInstanceVisitAll<Functor>(functor)));
4178   return functor;
4179 }
4180
4181 template<typename Functor>
4182 class FaceVisitorWrapper
4183 {
4184   const Functor& functor;
4185 public:
4186   FaceVisitorWrapper(const Functor& functor) : functor(functor)
4187   {
4188   }
4189
4190   void operator()(FaceInstance& faceInstance) const
4191   {
4192     functor(faceInstance.getFace());
4193   }
4194 };
4195
4196 template<typename Functor>
4197 inline const Functor& Scene_ForEachSelectedBrushFace(scene::Graph& graph, const Functor& functor)
4198 {
4199   g_SelectedFaceInstances.foreach(FaceVisitorWrapper<Functor>(functor));
4200   return functor;
4201 }
4202
4203
4204 #endif