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