]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - radiant/csg.cpp
Embrace variadic templates
[xonotic/netradiant.git] / radiant / csg.cpp
1 /*
2    Copyright (C) 1999-2006 Id Software, Inc. and contributors.
3    For a list of contributors, see the accompanying CONTRIBUTORS file.
4
5    This file is part of GtkRadiant.
6
7    GtkRadiant is free software; you can redistribute it and/or modify
8    it under the terms of the GNU General Public License as published by
9    the Free Software Foundation; either version 2 of the License, or
10    (at your option) any later version.
11
12    GtkRadiant is distributed in the hope that it will be useful,
13    but WITHOUT ANY WARRANTY; without even the implied warranty of
14    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15    GNU General Public License for more details.
16
17    You should have received a copy of the GNU General Public License
18    along with GtkRadiant; if not, write to the Free Software
19    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
20  */
21
22 #include "csg.h"
23
24 #include "debugging/debugging.h"
25
26 #include <list>
27
28 #include "map.h"
29 #include "brushmanip.h"
30 #include "brushnode.h"
31 #include "grid.h"
32
33 void Face_makeBrush( Face& face, const Brush& brush, brush_vector_t& out, float offset ){
34         if ( face.contributes() ) {
35                 out.push_back( new Brush( brush ) );
36                 Face* newFace = out.back()->addFace( face );
37                 if ( newFace != 0 ) {
38                         newFace->flipWinding();
39                         newFace->getPlane().offset( offset );
40                         newFace->planeChanged();
41                 }
42         }
43 }
44
45 class FaceMakeBrush
46 {
47 const Brush& brush;
48 brush_vector_t& out;
49 float offset;
50 public:
51 FaceMakeBrush( const Brush& brush, brush_vector_t& out, float offset )
52         : brush( brush ), out( out ), offset( offset ){
53 }
54 void operator()( Face& face ) const {
55         Face_makeBrush( face, brush, out, offset );
56 }
57 };
58
59 void Brush_makeHollow( const Brush& brush, brush_vector_t& out, float offset ){
60         Brush_forEachFace( brush, FaceMakeBrush( brush, out, offset ) );
61 }
62
63 class BrushHollowSelectedWalker : public scene::Graph::Walker
64 {
65 float m_offset;
66 public:
67 BrushHollowSelectedWalker( float offset )
68         : m_offset( offset ){
69 }
70 bool pre( const scene::Path& path, scene::Instance& instance ) const {
71         if ( path.top().get().visible() ) {
72                 Brush* brush = Node_getBrush( path.top() );
73                 if ( brush != 0
74                          && Instance_getSelectable( instance )->isSelected()
75                          && path.size() > 1 ) {
76                         brush_vector_t out;
77                         Brush_makeHollow( *brush, out, m_offset );
78                         for ( brush_vector_t::const_iterator i = out.begin(); i != out.end(); ++i )
79                         {
80                                 ( *i )->removeEmptyFaces();
81                                 NodeSmartReference node( ( new BrushNode() )->node() );
82                                 Node_getBrush( node )->copy( *( *i ) );
83                                 delete ( *i );
84                                 Node_getTraversable( path.parent() )->insert( node );
85                         }
86                 }
87         }
88         return true;
89 }
90 };
91
92 typedef std::list<Brush*> brushlist_t;
93
94 class BrushGatherSelected : public scene::Graph::Walker
95 {
96 brush_vector_t& m_brushlist;
97 public:
98 BrushGatherSelected( brush_vector_t& brushlist )
99         : m_brushlist( brushlist ){
100 }
101 bool pre( const scene::Path& path, scene::Instance& instance ) const {
102         if ( path.top().get().visible() ) {
103                 Brush* brush = Node_getBrush( path.top() );
104                 if ( brush != 0
105                          && Instance_getSelectable( instance )->isSelected() ) {
106                         m_brushlist.push_back( brush );
107                 }
108         }
109         return true;
110 }
111 };
112
113 class BrushDeleteSelected : public scene::Graph::Walker
114 {
115 public:
116 bool pre( const scene::Path& path, scene::Instance& instance ) const {
117         return true;
118 }
119 void post( const scene::Path& path, scene::Instance& instance ) const {
120         if ( path.top().get().visible() ) {
121                 Brush* brush = Node_getBrush( path.top() );
122                 if ( brush != 0
123                          && Instance_getSelectable( instance )->isSelected()
124                          && path.size() > 1 ) {
125                         Path_deleteTop( path );
126                 }
127         }
128 }
129 };
130
131 void Scene_BrushMakeHollow_Selected( scene::Graph& graph ){
132         GlobalSceneGraph().traverse( BrushHollowSelectedWalker( GetGridSize() ) );
133         GlobalSceneGraph().traverse( BrushDeleteSelected() );
134 }
135
136 /*
137    =============
138    CSG_MakeHollow
139    =============
140  */
141
142 void CSG_MakeHollow( void ){
143         UndoableCommand undo( "brushHollow" );
144
145         Scene_BrushMakeHollow_Selected( GlobalSceneGraph() );
146
147         SceneChangeNotify();
148 }
149
150 template<typename Type>
151 class RemoveReference
152 {
153 public:
154 typedef Type type;
155 };
156
157 template<typename Type>
158 class RemoveReference<Type&>
159 {
160 public:
161 typedef Type type;
162 };
163
164 template<typename Functor>
165 class Dereference
166 {
167 const Functor& functor;
168 public:
169 Dereference( const Functor& functor ) : functor( functor ){
170 }
171 get_result_type<Functor> operator()( typename RemoveReference<get_argument<Functor, 0>>::type *firstArgument ) const {
172         return functor( *firstArgument );
173 }
174 };
175
176 template<typename Functor>
177 inline Dereference<Functor> makeDereference( const Functor& functor ){
178         return Dereference<Functor>( functor );
179 }
180
181 typedef Face* FacePointer;
182 const FacePointer c_nullFacePointer = 0;
183
184 template<typename Predicate>
185 Face* Brush_findIf( const Brush& brush, const Predicate& predicate ){
186         Brush::const_iterator i = std::find_if( brush.begin(), brush.end(), makeDereference( predicate ) );
187         return i == brush.end() ? c_nullFacePointer : *i; // uses c_nullFacePointer instead of 0 because otherwise gcc 4.1 attempts conversion to int
188 }
189
190 template<typename Caller>
191 class BindArguments1
192 {
193 typedef get_argument<Caller, 1> FirstBound;
194 FirstBound firstBound;
195 public:
196 BindArguments1( FirstBound firstBound )
197         : firstBound( firstBound ){
198 }
199 get_result_type<Caller> operator()( get_argument<Caller, 0> firstArgument ) const {
200         return Caller::call( firstArgument, firstBound );
201 }
202 };
203
204 template<typename Caller>
205 class BindArguments2
206 {
207 typedef get_argument<Caller, 1> FirstBound;
208 typedef get_argument<Caller, 2> SecondBound;
209 FirstBound firstBound;
210 SecondBound secondBound;
211 public:
212 BindArguments2( FirstBound firstBound, SecondBound secondBound )
213         : firstBound( firstBound ), secondBound( secondBound ){
214 }
215 get_result_type<Caller> operator()( get_argument<Caller, 0> firstArgument ) const {
216         return Caller::call( firstArgument, firstBound, secondBound );
217 }
218 };
219
220 template<typename Caller, typename FirstBound, typename SecondBound>
221 BindArguments2<Caller> bindArguments( const Caller& caller, FirstBound firstBound, SecondBound secondBound ){
222         return BindArguments2<Caller>( firstBound, secondBound );
223 }
224
225 inline bool Face_testPlane( const Face& face, const Plane3& plane, bool flipped ){
226         return face.contributes() && !Winding_TestPlane( face.getWinding(), plane, flipped );
227 }
228 typedef Function3<const Face&, const Plane3&, bool, bool, Face_testPlane> FaceTestPlane;
229
230
231
232 /// \brief Returns true if
233 /// \li !flipped && brush is BACK or ON
234 /// \li flipped && brush is FRONT or ON
235 bool Brush_testPlane( const Brush& brush, const Plane3& plane, bool flipped ){
236         brush.evaluateBRep();
237 #if 1
238         for ( Brush::const_iterator i( brush.begin() ); i != brush.end(); ++i )
239         {
240                 if ( Face_testPlane( *( *i ), plane, flipped ) ) {
241                         return false;
242                 }
243         }
244         return true;
245 #else
246         return Brush_findIf( brush, bindArguments( FaceTestPlane(), makeReference( plane ), flipped ) ) == 0;
247 #endif
248 }
249
250 brushsplit_t Brush_classifyPlane( const Brush& brush, const Plane3& plane ){
251         brush.evaluateBRep();
252         brushsplit_t split;
253         for ( Brush::const_iterator i( brush.begin() ); i != brush.end(); ++i )
254         {
255                 if ( ( *i )->contributes() ) {
256                         split += Winding_ClassifyPlane( ( *i )->getWinding(), plane );
257                 }
258         }
259         return split;
260 }
261
262 bool Brush_subtract( const Brush& brush, const Brush& other, brush_vector_t& ret_fragments ){
263         if ( aabb_intersects_aabb( brush.localAABB(), other.localAABB() ) ) {
264                 brush_vector_t fragments;
265                 fragments.reserve( other.size() );
266                 Brush back( brush );
267
268                 for ( Brush::const_iterator i( other.begin() ); i != other.end(); ++i )
269                 {
270                         if ( ( *i )->contributes() ) {
271                                 brushsplit_t split = Brush_classifyPlane( back, ( *i )->plane3() );
272                                 if ( split.counts[ePlaneFront] != 0
273                                          && split.counts[ePlaneBack] != 0 ) {
274                                         fragments.push_back( new Brush( back ) );
275                                         Face* newFace = fragments.back()->addFace( *( *i ) );
276                                         if ( newFace != 0 ) {
277                                                 newFace->flipWinding();
278                                         }
279                                         back.addFace( *( *i ) );
280                                 }
281                                 else if ( split.counts[ePlaneBack] == 0 ) {
282                                         for ( brush_vector_t::iterator i = fragments.begin(); i != fragments.end(); ++i )
283                                         {
284                                                 delete( *i );
285                                         }
286                                         return false;
287                                 }
288                         }
289                 }
290                 ret_fragments.insert( ret_fragments.end(), fragments.begin(), fragments.end() );
291                 return true;
292         }
293         return false;
294 }
295
296 class SubtractBrushesFromUnselected : public scene::Graph::Walker
297 {
298 const brush_vector_t& m_brushlist;
299 std::size_t& m_before;
300 std::size_t& m_after;
301 public:
302 SubtractBrushesFromUnselected( const brush_vector_t& brushlist, std::size_t& before, std::size_t& after )
303         : m_brushlist( brushlist ), m_before( before ), m_after( after ){
304 }
305 bool pre( const scene::Path& path, scene::Instance& instance ) const {
306         return true;
307 }
308 void post( const scene::Path& path, scene::Instance& instance ) const {
309         if ( path.top().get().visible() ) {
310                 Brush* brush = Node_getBrush( path.top() );
311                 if ( brush != 0
312                          && !Instance_getSelectable( instance )->isSelected() ) {
313                         brush_vector_t buffer[2];
314                         bool swap = false;
315                         Brush* original = new Brush( *brush );
316                         buffer[static_cast<std::size_t>( swap )].push_back( original );
317
318                         {
319                                 for ( brush_vector_t::const_iterator i( m_brushlist.begin() ); i != m_brushlist.end(); ++i )
320                                 {
321                                         for ( brush_vector_t::iterator j( buffer[static_cast<std::size_t>( swap )].begin() ); j != buffer[static_cast<std::size_t>( swap )].end(); ++j )
322                                         {
323                                                 if ( Brush_subtract( *( *j ), *( *i ), buffer[static_cast<std::size_t>( !swap )] ) ) {
324                                                         delete ( *j );
325                                                 }
326                                                 else
327                                                 {
328                                                         buffer[static_cast<std::size_t>( !swap )].push_back( ( *j ) );
329                                                 }
330                                         }
331                                         buffer[static_cast<std::size_t>( swap )].clear();
332                                         swap = !swap;
333                                 }
334                         }
335
336                         brush_vector_t& out = buffer[static_cast<std::size_t>( swap )];
337
338                         if ( out.size() == 1 && out.back() == original ) {
339                                 delete original;
340                         }
341                         else
342                         {
343                                 ++m_before;
344                                 for ( brush_vector_t::const_iterator i = out.begin(); i != out.end(); ++i )
345                                 {
346                                         ++m_after;
347                                         ( *i )->removeEmptyFaces();
348                                         if ( !( *i )->empty() ) {
349                                                 NodeSmartReference node( ( new BrushNode() )->node() );
350                                                 Node_getBrush( node )->copy( *( *i ) );
351                                                 delete ( *i );
352                                                 Node_getTraversable( path.parent() )->insert( node );
353                                         }
354                                         else{
355                                                 delete ( *i );
356                                         }
357                                 }
358                                 Path_deleteTop( path );
359                         }
360                 }
361         }
362 }
363 };
364
365 void CSG_Subtract(){
366         brush_vector_t selected_brushes;
367         GlobalSceneGraph().traverse( BrushGatherSelected( selected_brushes ) );
368
369         if ( selected_brushes.empty() ) {
370                 globalOutputStream() << "CSG Subtract: No brushes selected.\n";
371         }
372         else
373         {
374                 globalOutputStream() << "CSG Subtract: Subtracting " << Unsigned( selected_brushes.size() ) << " brushes.\n";
375
376                 UndoableCommand undo( "brushSubtract" );
377
378                 // subtract selected from unselected
379                 std::size_t before = 0;
380                 std::size_t after = 0;
381                 GlobalSceneGraph().traverse( SubtractBrushesFromUnselected( selected_brushes, before, after ) );
382                 globalOutputStream() << "CSG Subtract: Result: "
383                                                          << Unsigned( after ) << " fragment" << ( after == 1 ? "" : "s" )
384                                                          << " from " << Unsigned( before ) << " brush" << ( before == 1 ? "" : "es" ) << ".\n";
385
386                 SceneChangeNotify();
387         }
388 }
389
390 class BrushSplitByPlaneSelected : public scene::Graph::Walker
391 {
392 const Vector3& m_p0;
393 const Vector3& m_p1;
394 const Vector3& m_p2;
395 const char* m_shader;
396 const TextureProjection& m_projection;
397 EBrushSplit m_split;
398 public:
399 BrushSplitByPlaneSelected( const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, const TextureProjection& projection, EBrushSplit split )
400         : m_p0( p0 ), m_p1( p1 ), m_p2( p2 ), m_shader( shader ), m_projection( projection ), m_split( split ){
401 }
402 bool pre( const scene::Path& path, scene::Instance& instance ) const {
403         return true;
404 }
405 void post( const scene::Path& path, scene::Instance& instance ) const {
406         if ( path.top().get().visible() ) {
407                 Brush* brush = Node_getBrush( path.top() );
408                 if ( brush != 0
409                          && Instance_getSelectable( instance )->isSelected() ) {
410                         Plane3 plane( plane3_for_points( m_p0, m_p1, m_p2 ) );
411                         if ( plane3_valid( plane ) ) {
412                                 brushsplit_t split = Brush_classifyPlane( *brush, m_split == eFront ? plane3_flipped( plane ) : plane );
413                                 if ( split.counts[ePlaneBack] && split.counts[ePlaneFront] ) {
414                                         // the plane intersects this brush
415                                         if ( m_split == eFrontAndBack ) {
416                                                 NodeSmartReference node( ( new BrushNode() )->node() );
417                                                 Brush* fragment = Node_getBrush( node );
418                                                 fragment->copy( *brush );
419                                                 Face* newFace = fragment->addPlane( m_p0, m_p1, m_p2, m_shader, m_projection );
420                                                 if ( newFace != 0 && m_split != eFront ) {
421                                                         newFace->flipWinding();
422                                                 }
423                                                 fragment->removeEmptyFaces();
424                                                 ASSERT_MESSAGE( !fragment->empty(), "brush left with no faces after split" );
425
426                                                 Node_getTraversable( path.parent() )->insert( node );
427                                                 {
428                                                         scene::Path fragmentPath = path;
429                                                         fragmentPath.top() = makeReference( node.get() );
430                                                         selectPath( fragmentPath, true );
431                                                 }
432                                         }
433
434                                         Face* newFace = brush->addPlane( m_p0, m_p1, m_p2, m_shader, m_projection );
435                                         if ( newFace != 0 && m_split == eFront ) {
436                                                 newFace->flipWinding();
437                                         }
438                                         brush->removeEmptyFaces();
439                                         ASSERT_MESSAGE( !brush->empty(), "brush left with no faces after split" );
440                                 }
441                                 else
442                                 // the plane does not intersect this brush
443                                 if ( m_split != eFrontAndBack && split.counts[ePlaneBack] != 0 ) {
444                                         // the brush is "behind" the plane
445                                         Path_deleteTop( path );
446                                 }
447                         }
448                 }
449         }
450 }
451 };
452
453 void Scene_BrushSplitByPlane( scene::Graph& graph, const Vector3& p0, const Vector3& p1, const Vector3& p2, const char* shader, EBrushSplit split ){
454         TextureProjection projection;
455         TexDef_Construct_Default( projection );
456         graph.traverse( BrushSplitByPlaneSelected( p0, p1, p2, shader, projection, split ) );
457         SceneChangeNotify();
458 }
459
460
461 class BrushInstanceSetClipPlane : public scene::Graph::Walker
462 {
463 Plane3 m_plane;
464 public:
465 BrushInstanceSetClipPlane( const Plane3& plane )
466         : m_plane( plane ){
467 }
468 bool pre( const scene::Path& path, scene::Instance& instance ) const {
469         BrushInstance* brush = Instance_getBrush( instance );
470         if ( brush != 0
471                  && path.top().get().visible()
472                  && brush->isSelected() ) {
473                 BrushInstance& brushInstance = *brush;
474                 brushInstance.setClipPlane( m_plane );
475         }
476         return true;
477 }
478 };
479
480 void Scene_BrushSetClipPlane( scene::Graph& graph, const Plane3& plane ){
481         graph.traverse( BrushInstanceSetClipPlane( plane ) );
482 }
483
484 /*
485    =============
486    CSG_Merge
487    =============
488  */
489 bool Brush_merge( Brush& brush, const brush_vector_t& in, bool onlyshape ){
490         // gather potential outer faces
491
492         {
493                 typedef std::vector<const Face*> Faces;
494                 Faces faces;
495                 for ( brush_vector_t::const_iterator i( in.begin() ); i != in.end(); ++i )
496                 {
497                         ( *i )->evaluateBRep();
498                         for ( Brush::const_iterator j( ( *i )->begin() ); j != ( *i )->end(); ++j )
499                         {
500                                 if ( !( *j )->contributes() ) {
501                                         continue;
502                                 }
503
504                                 const Face& face1 = *( *j );
505
506                                 bool skip = false;
507                                 // test faces of all input brushes
508                                 //!\todo SPEEDUP: Flag already-skip faces and only test brushes from i+1 upwards.
509                                 for ( brush_vector_t::const_iterator k( in.begin() ); !skip && k != in.end(); ++k )
510                                 {
511                                         if ( k != i ) { // don't test a brush against itself
512                                                 for ( Brush::const_iterator l( ( *k )->begin() ); !skip && l != ( *k )->end(); ++l )
513                                                 {
514                                                         const Face& face2 = *( *l );
515
516                                                         // face opposes another face
517                                                         if ( plane3_opposing( face1.plane3(), face2.plane3() ) ) {
518                                                                 // skip opposing planes
519                                                                 skip  = true;
520                                                                 break;
521                                                         }
522                                                 }
523                                         }
524                                 }
525
526                                 // check faces already stored
527                                 for ( Faces::const_iterator m = faces.begin(); !skip && m != faces.end(); ++m )
528                                 {
529                                         const Face& face2 = *( *m );
530
531                                         // face equals another face
532                                         if ( plane3_equal( face1.plane3(), face2.plane3() ) ) {
533                                                 //if the texture/shader references should be the same but are not
534                                                 if ( !onlyshape && !shader_equal( face1.getShader().getShader(), face2.getShader().getShader() ) ) {
535                                                         return false;
536                                                 }
537                                                 // skip duplicate planes
538                                                 skip = true;
539                                                 break;
540                                         }
541
542                                         // face1 plane intersects face2 winding or vice versa
543                                         if ( Winding_PlanesConcave( face1.getWinding(), face2.getWinding(), face1.plane3(), face2.plane3() ) ) {
544                                                 // result would not be convex
545                                                 return false;
546                                         }
547                                 }
548
549                                 if ( !skip ) {
550                                         faces.push_back( &face1 );
551                                 }
552                         }
553                 }
554                 for ( Faces::const_iterator i = faces.begin(); i != faces.end(); ++i )
555                 {
556                         if ( !brush.addFace( *( *i ) ) ) {
557                                 // result would have too many sides
558                                 return false;
559                         }
560                 }
561         }
562
563         brush.removeEmptyFaces();
564
565         return true;
566 }
567
568 void CSG_Merge( void ){
569         brush_vector_t selected_brushes;
570
571         // remove selected
572         GlobalSceneGraph().traverse( BrushGatherSelected( selected_brushes ) );
573
574         if ( selected_brushes.empty() ) {
575                 globalOutputStream() << "CSG Merge: No brushes selected.\n";
576                 return;
577         }
578
579         if ( selected_brushes.size() < 2 ) {
580                 globalOutputStream() << "CSG Merge: At least two brushes have to be selected.\n";
581                 return;
582         }
583
584         globalOutputStream() << "CSG Merge: Merging " << Unsigned( selected_brushes.size() ) << " brushes.\n";
585
586         UndoableCommand undo( "brushMerge" );
587
588         scene::Path merged_path = GlobalSelectionSystem().ultimateSelected().path();
589
590         NodeSmartReference node( ( new BrushNode() )->node() );
591         Brush* brush = Node_getBrush( node );
592         // if the new brush would not be convex
593         if ( !Brush_merge( *brush, selected_brushes, true ) ) {
594                 globalOutputStream() << "CSG Merge: Failed - result would not be convex.\n";
595         }
596         else
597         {
598                 ASSERT_MESSAGE( !brush->empty(), "brush left with no faces after merge" );
599
600                 // free the original brushes
601                 GlobalSceneGraph().traverse( BrushDeleteSelected() );
602
603                 merged_path.pop();
604                 Node_getTraversable( merged_path.top() )->insert( node );
605                 merged_path.push( makeReference( node.get() ) );
606
607                 selectPath( merged_path, true );
608
609                 globalOutputStream() << "CSG Merge: Succeeded.\n";
610                 SceneChangeNotify();
611         }
612 }