/
convexsubspace.cpp
625 lines (518 loc) · 17.9 KB
/
convexsubspace.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
/** @file world/bsp/convexsubspace.cpp BSP Builder Convex Subspace.
*
* @authors Copyright © 2013 Daniel Swanson <danij@dengine.net>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include <QHash>
#include <QSet>
#include <QtAlgorithms>
#include <de/binangle.h>
#include <de/mathutil.h>
#include "Face"
#include "HEdge"
#include "Mesh"
#include "BspLeaf"
#include "Line"
#include "Sector"
#include "Segment"
#include "world/bsp/linesegment.h"
#include "render/r_main.h" /// validCount @todo Remove me
#include "world/bsp/convexsubspace.h"
/// Smallest difference between two angles before being considered equal (in degrees).
static coord_t const ANG_EPSILON = 1.0 / 1024.0;
namespace de {
namespace bsp {
typedef QList<LineSegment::Side *> SegmentList;
/**
* Represents a clockwise ordering of a subset of the line segments and
* implements logic for partitioning that subset into @em contiguous ranges
* for geometry construction.
*/
struct Continuity
{
typedef QList<OrderedSegment *> OrderedSegmentList;
/// Front sector uniformly referenced by all line segments.
Sector *sector;
/// Coverage metric.
double coverage;
/// Number of discordant (i.e., non-contiguous) line segments.
int discordSegments;
/// Number of referencing line segments of each type:
int norm;
int part;
int self;
/// The ordered line segments.
OrderedSegmentList orderedSegs;
/// The discordant line segments.
OrderedSegmentList discordSegs;
Continuity(Sector *sector)
: sector(sector), coverage(0), discordSegments(0)
{}
/**
* Perform heuristic comparison between two continuities to determine a
* preference order for BSP sector attribution. The algorithm used weights
* the two choices according to the number and "type" of the referencing
* line segments and the "coverage" metric.
*
* @return @c true if "this" choice is rated better than @a other.
*
* @todo Remove when heuristic sector selection is no longer necessary.
*/
bool operator < (Continuity const &other) const
{
if(norm == other.norm)
{
return !(coverage < other.coverage);
}
return norm > other.norm;
}
/**
* Assumes that segments are added in clockwise order.
*/
void addOneSegment(OrderedSegment const &oseg)
{
DENG_ASSERT(oseg.segment->sectorPtr() == sector);
// Separate the discordant duplicates.
OrderedSegmentList *list = &orderedSegs;
foreach(OrderedSegment const *other, orderedSegs)
{
if(oseg == *other)
{
list = &discordSegs;
break;
}
}
list->append(const_cast<OrderedSegment *>(&oseg));
// Account for the new line segment.
LineSegment::Side const &seg = *oseg.segment;
if(!seg.hasMapSide())
{
part += 1;
}
else if(seg.mapSide().line().isSelfReferencing())
{
self += 1;
}
else
{
norm += 1;
}
// Update the 'coverage' metric.
if(oseg.fromAngle > oseg.toAngle)
coverage += oseg.fromAngle - oseg.toAngle;
else
coverage += oseg.fromAngle + (360.0 - oseg.toAngle);
}
void evaluate()
{
// Account remaining discontiguous segments.
discordSegments = 0;
for(int i = 0; i < orderedSegs.count() - 1; ++i)
{
LineSegment::Side const &segA = *orderedSegs[i ]->segment;
LineSegment::Side const &segB = *orderedSegs[i+1]->segment;
if(segB.from().origin() != segA.to().origin())
discordSegments += 1;
}
if(orderedSegs.count() > 1)
{
LineSegment::Side const &segB = *orderedSegs.last()->segment;
LineSegment::Side const &segA = *orderedSegs.first()->segment;
if(segB.to().origin() != segA.from().origin())
discordSegments += 1;
}
}
#ifdef DENG_DEBUG
void debugPrint() const
{
LOG_INFO("Continuity [%p] (sector:%i, coverage:%f, discord:%i)")
<< de::dintptr(this)
<< (sector? sector->indexInArchive() : -1)
<< coverage
<< discordSegments;
foreach(OrderedSegment const *oseg, orderedSegs)
{
oseg->debugPrint();
}
foreach(OrderedSegment const *oseg, discordSegs)
{
oseg->debugPrint();
}
}
#endif
};
DENG2_PIMPL_NOREF(ConvexSubspace)
{
typedef QSet<LineSegment::Side *> Segments;
/// The set of line segments.
Segments segments;
/// The same line segments in a clockwise order with angle info.
OrderedSegments orderedSegments;
/// Set to @c true when the ordered segment list needs to be rebuilt.
bool needRebuildOrderedSegments;
/// BSP leaf attributed to the subspace (if any).
BspLeaf *bspLeaf;
Instance()
: needRebuildOrderedSegments(false),
bspLeaf(0)
{}
Instance(Instance const &other)
: de::IPrivate(),
segments (other.segments),
orderedSegments (other.orderedSegments),
needRebuildOrderedSegments(other.needRebuildOrderedSegments),
bspLeaf (other.bspLeaf)
{}
/**
* Returns @c true iff at least one line segment in the set is derived
* from a map line.
*/
bool haveMapLineSegment()
{
foreach(LineSegment::Side *seg, segments)
{
if(seg->hasMapSide())
return true;
}
return false;
}
Vector2d findCenter()
{
Vector2d center;
int numPoints = 0;
foreach(LineSegment::Side *seg, segments)
{
center += seg->from().origin();
center += seg->to().origin();
numPoints += 2;
}
if(numPoints)
{
center /= numPoints;
}
return center;
}
/**
* Builds the ordered list of line segments, which, is sorted firstly in
* a clockwise order (i.e., descending angles) according to the origin of
* their 'from' vertex relative to @a point. A secondary ordering is also
* applied such that line segments with the same origin coordinates are
* sorted by descending 'to' angle.
*/
void buildOrderedSegments(Vector2d const &point)
{
needRebuildOrderedSegments = false;
orderedSegments.clear();
foreach(LineSegment::Side *seg, segments)
{
Vector2d fromDist = seg->from().origin() - point;
Vector2d toDist = seg->to().origin() - point;
OrderedSegment oseg;
oseg.segment = seg;
oseg.fromAngle = M_DirectionToAngleXY(fromDist.x, fromDist.y);
oseg.toAngle = M_DirectionToAngleXY(toDist.x, toDist.y);
orderedSegments.append(oseg);
}
// Sort algorithm: "double bubble".
// Order by descending 'from' angle.
int const numSegments = orderedSegments.count();
for(int pass = 0; pass < numSegments - 1; ++pass)
{
bool swappedAny = false;
for(int i = 0; i < numSegments - 1; ++i)
{
OrderedSegment const &a = orderedSegments.at(i);
OrderedSegment const &b = orderedSegments.at(i+1);
if(a.fromAngle + ANG_EPSILON < b.fromAngle)
{
orderedSegments.swap(i, i + 1);
swappedAny = true;
}
}
if(!swappedAny) break;
}
for(int pass = 0; pass < numSegments - 1; ++pass)
{
bool swappedAny = false;
for(int i = 0; i < numSegments - 1; ++i)
{
OrderedSegment const &a = orderedSegments.at(i);
OrderedSegment const &b = orderedSegments.at(i+1);
if(a.fromAngle == b.fromAngle)
{
if(b.segment->length() > a.segment->length())
{
orderedSegments.swap(i, i + 1);
swappedAny = true;
}
}
}
if(!swappedAny) break;
}
// LOG_DEBUG("Ordered segments around %s") << point.asText();
}
private:
Instance &operator = (Instance const &); // no assignment
};
ConvexSubspace::ConvexSubspace()
: d(new Instance())
{}
ConvexSubspace::ConvexSubspace(QList<LineSegment::Side *> const &segments)
: d(new Instance())
{
addSegments(segments);
}
ConvexSubspace::ConvexSubspace(ConvexSubspace const &other)
: d(new Instance(*other.d))
{}
ConvexSubspace &ConvexSubspace::operator = (ConvexSubspace const &other)
{
d.reset(new Instance(*other.d));
return *this;
}
void ConvexSubspace::addSegments(QList<LineSegment::Side *> const &newSegments)
{
int sizeBefore = d->segments.size();
d->segments.unite(QSet<LineSegment::Side *>::fromList(newSegments));
if(d->segments.size() != sizeBefore)
{
// We'll need to rebuild the ordered segment list.
d->needRebuildOrderedSegments = true;
}
#ifdef DENG_DEBUG
int numSegmentsAdded = d->segments.size() - sizeBefore;
if(numSegmentsAdded < newSegments.size())
{
LOG_DEBUG("ConvexSubspace pruned %i duplicate segments")
<< (newSegments.size() - numSegmentsAdded);
}
#endif
}
void ConvexSubspace::addOneSegment(LineSegment::Side const &newSegment)
{
int sizeBefore = d->segments.size();
d->segments.insert(const_cast<LineSegment::Side *>(&newSegment));
if(d->segments.size() != sizeBefore)
{
// We'll need to rebuild the ordered segment list.
d->needRebuildOrderedSegments = true;
}
else
{
LOG_DEBUG("ConvexSubspace pruned one duplicate segment");
}
}
void ConvexSubspace::buildGeometry(BspLeaf &leaf, Mesh &mesh) const
{
LOG_AS("ConvexSubspace::buildGeometry");
bool const isDegenerate = segmentCount() < 3;
// Sanity check.
if(!isDegenerate && !d->haveMapLineSegment())
throw Error("ConvexSubspace::buildGeometry", "No map line segment");
if(d->needRebuildOrderedSegments)
{
d->buildOrderedSegments(d->findCenter());
}
/*
* Build the line segment -> sector continuity map.
*/
typedef QList<Continuity> Continuities;
Continuities continuities;
typedef QHash<Sector *, Continuity *> SectorContinuityMap;
SectorContinuityMap scMap;
foreach(OrderedSegment const &oseg, d->orderedSegments)
{
Sector *frontSector = oseg.segment->sectorPtr();
SectorContinuityMap::iterator found = scMap.find(frontSector);
if(found == scMap.end())
{
continuities.append(Continuity(frontSector));
found = scMap.insert(frontSector, &continuities.last());
}
Continuity *conty = found.value();
conty->addOneSegment(oseg);
}
for(int i = 0; i < continuities.count(); ++i)
{
Continuity &conty = continuities[i];
conty.evaluate();
if(!conty.discordSegs.isEmpty())
{
// Construct a new mesh and set of half-edges.
Mesh *extraMesh = new Mesh;
Face *face = extraMesh->newFace();
foreach(OrderedSegment const *oseg, conty.discordSegs)
{
LineSegment::Side *lineSeg = oseg->segment;
HEdge *hedge = extraMesh->newHEdge(lineSeg->from());
if(Line::Side *mapSide = lineSeg->mapSidePtr())
{
Segment *seg = new Segment(*mapSide, *hedge);
// Attribute the segment to half-edge.
hedge->setMapElement(seg);
#ifdef __CLIENT__
seg->setLineSideOffset(Vector2d(mapSide->from().origin() - lineSeg->from().origin()).length());
seg->setLength(Vector2d(lineSeg->to().origin() - lineSeg->from().origin()).length());
#endif
}
// Link the new half-edge for this line segment to the head of
// the list in the new face geometry.
hedge->setNext(face->hedge());
face->setHEdge(hedge);
// Is there a half-edge on the back side we need to twin with?
if(lineSeg->back().hasHEdge())
{
lineSeg->back().hedge().setTwin(hedge);
hedge->setTwin(lineSeg->back().hedgePtr());
}
// Link the new half-edge with the line segment.
lineSeg->setHEdge(hedge);
}
// Link the half-edges anticlockwise and close the ring.
HEdge *hedge = face->hedge();
forever
{
// There is now one more half-edge in this face.
/// @todo Face should encapsulate.
face->_hedgeCount += 1;
// Attribute the half-edge to the Face.
hedge->setFace(face);
if(hedge->hasNext())
{
// Link anticlockwise.
hedge->next().setPrev(hedge);
hedge = &hedge->next();
}
else
{
// Circular link.
hedge->setNext(face->hedge());
hedge->next().setPrev(hedge);
break;
}
}
/// @todo Face should encapsulate.
face->updateAABox();
face->updateCenter();
// Assign the mesh to the BSP leaf (takes ownership).
leaf.assignExtraMesh(*extraMesh);
}
}
// Determine which sector to attribute to the BSP leaf.
qSort(continuities.begin(), continuities.end());
leaf.setSector(continuities.first().sector);
/*#ifdef DENG_DEBUG
LOG_INFO("\nConvexSubspace %s BSP sector:%i (%i continuities)")
<< d->findCenter().asText()
<< (leaf.hasSector()? leaf.sector().indexInArchive() : -1)
<< continuities.count();
foreach(Continuity const &conty, continuities)
{
conty.debugPrint();
}
#endif*/
if(!isDegenerate)
{
// Construct a new face and a ring of half-edges.
Face *face = mesh.newFace();
// Iterate backwards so that the half-edges can be linked clockwise.
for(int i = d->orderedSegments.size(); i-- > 0; )
{
LineSegment::Side *lineSeg = d->orderedSegments[i].segment;
if(lineSeg->hasHEdge())
continue;
HEdge *hedge = mesh.newHEdge(lineSeg->from());
if(Line::Side *mapSide = lineSeg->mapSidePtr())
{
Segment *seg = new Segment(*mapSide, *hedge);
// Attribute the segment to the half-edge.
hedge->setMapElement(seg);
#ifdef __CLIENT__
seg->setLineSideOffset(Vector2d(mapSide->from().origin() - lineSeg->from().origin()).length());
seg->setLength(Vector2d(lineSeg->to().origin() - lineSeg->from().origin()).length());
#endif
}
// Link the new half-edge for this line segment to the head of
// the list in the new Face geometry.
hedge->setNext(face->hedge());
face->setHEdge(hedge);
// Is there a half-edge on the back side we need to twin with?
if(lineSeg->back().hasHEdge())
{
lineSeg->back().hedge().setTwin(hedge);
hedge->setTwin(lineSeg->back().hedgePtr());
}
// Link the new half-edge with the line segment.
lineSeg->setHEdge(hedge);
}
// Link the half-edges anticlockwise and close the ring.
HEdge *hedge = face->hedge();
forever
{
// There is now one more half-edge in this face.
/// @todo Face should encapsulate.
face->_hedgeCount += 1;
// Attribute the half-edge to the Face.
hedge->setFace(face);
if(hedge->hasNext())
{
// Link anticlockwise.
hedge->next().setPrev(hedge);
hedge = &hedge->next();
}
else
{
// Circular link.
hedge->setNext(face->hedge());
hedge->next().setPrev(hedge);
break;
}
}
/// @todo Face should encapsulate.
face->updateAABox();
face->updateCenter();
// Assign the mesh to the BSP leaf (takes ownership).
leaf.setPoly(face);
}
if(!leaf.hasSector())
{
LOG_WARNING("BspLeaf %p is degenerate/orphan (%d half-edges).")
<< de::dintptr(&leaf)
<< (leaf.hasPoly()? leaf.poly().hedgeCount() : 0);
}
}
int ConvexSubspace::segmentCount() const
{
return d->segments.count();
}
OrderedSegments const &ConvexSubspace::segments() const
{
if(d->needRebuildOrderedSegments)
{
d->buildOrderedSegments(d->findCenter());
}
return d->orderedSegments;
}
BspLeaf *ConvexSubspace::bspLeaf() const
{
return d->bspLeaf;
}
void ConvexSubspace::setBspLeaf(BspLeaf *newBspLeaf)
{
d->bspLeaf = newBspLeaf;
}
} // namespace bsp
} // namespace de