/
partitioner.cpp
2529 lines (2145 loc) · 83.5 KB
/
partitioner.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
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file partitioner.cpp
* BSP Partitioner. Recursive node creation and sorting. @ingroup map
*
* Originally based on glBSP 2.24 (in turn, based on BSP 2.3), which is hosted
* on SourceForge: http://sourceforge.net/projects/glbsp/
*
* @author Copyright © 2006-2012 Daniel Swanson <danij@dengine.net>
* @author Copyright © 2006-2007 Jamie Jones <jamie_jones_au@yahoo.com.au>
* @author Copyright © 2000-2007 Andrew Apted <ajapted@gmail.com>
* @author Copyright © 1998-2000 Colin Reed <cph@moria.org.uk>
* @author Copyright © 1998-2000 Lee Killough <killough@rsn.hp.com>
* @author Copyright © 1997-1998 Raphael.Quinet <raphael.quinet@eed.ericsson.se>
*
* @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 <cmath>
#include <vector>
#include <map>
#include <algorithm>
#include <de/Error>
#include <de/Log>
#include <de/memory.h>
#include "de_base.h"
#include "p_mapdata.h"
#include "bspleaf.h"
#include "bspnode.h"
#include "hedge.h"
#include "map/bsp/hedgeinfo.h"
#include "map/bsp/hedgeintercept.h"
#include "map/bsp/hedgetip.h"
#include "map/bsp/hplane.h"
#include "map/bsp/linedefinfo.h"
#include "map/bsp/partitioncost.h"
#include "map/bsp/superblockmap.h"
#include "map/bsp/vertexinfo.h"
#include "map/bsp/partitioner.h"
using namespace de::bsp;
/// Minimum length of a half-edge post partitioning. Used in cost evaluation.
static const coord_t SHORT_HEDGE_EPSILON = 4.0;
/// Smallest distance between two points before being considered equal.
static const coord_t DIST_EPSILON = (1.0 / 128.0);
/// Smallest difference between two angles before being considered equal (in degrees).
static const coord_t ANG_EPSILON = (1.0 / 1024.0);
//DENG_DEBUG_ONLY(static int printSuperBlockHEdgesWorker(SuperBlock* block, void* /*parameters*/));
static bool findBspLeafCenter(BspLeaf const& leaf, pvec2d_t midPoint);
static void initAABoxFromEditableLineDefVertexes(AABoxd* aaBox, const LineDef* line);
static Sector* findFirstSectorInHEdgeList(const BspLeaf* leaf);
struct Partitioner::Instance
{
// Used when sorting BSP leaf half-edges by angle around midpoint.
typedef std::vector<HEdge*>HEdgeSortBuffer;
/// HEdge split cost factor.
int splitCostFactor;
/// Current map which we are building BSP data for.
GameMap* map;
/// @todo Refactor me away:
uint* numEditableVertexes;
Vertex*** editableVertexes;
/// Running totals of constructed BSP data objects.
uint numNodes;
uint numLeafs;
uint numHEdges;
uint numVertexes;
/// Extended info about LineDefs in the current map.
typedef std::vector<LineDefInfo> LineDefInfos;
LineDefInfos lineDefInfos;
/// Extended info about HEdges in the BSP object tree.
typedef std::map<HEdge*, HEdgeInfo> HEdgeInfos;
HEdgeInfos hedgeInfos;
/// Extended info about Vertexes in the current map (including extras).
/// @note May be larger than Instance::numVertexes (deallocation is lazy).
typedef std::vector<VertexInfo> VertexInfos;
VertexInfos vertexInfos;
/// Extra vertexes allocated for the current map.
/// @note May be larger than Instance::numVertexes (deallocation is lazy).
typedef std::vector<Vertex*> Vertexes;
Vertexes vertexes;
/// Root node of our internal binary tree around which the final BSP data
/// objects are constructed.
BspTreeNode* rootNode;
/// HPlane used to model the current BSP partition and the list of intercepts.
HPlane* partition;
/// Extra info about the partition plane.
HEdgeInfo partitionInfo;
LineDef* partitionLineDef;
/// Unclosed sectors are recorded here so we don't print too many warnings.
struct UnclosedSectorRecord
{
Sector* sector;
vec2d_t nearPoint;
UnclosedSectorRecord(Sector* _sector, coord_t x, coord_t y)
: sector(_sector)
{
V2d_Set(nearPoint, x, y);
}
};
typedef std::map<Sector*, UnclosedSectorRecord> UnclosedSectors;
UnclosedSectors unclosedSectors;
/// Unclosed BSP leafs are recorded here so we don't print too many warnings.
struct UnclosedBspLeafRecord
{
BspLeaf* leaf;
uint gapTotal;
UnclosedBspLeafRecord(BspLeaf* _leaf, uint _gapTotal)
: leaf(_leaf), gapTotal(_gapTotal)
{}
};
typedef std::map<BspLeaf*, UnclosedBspLeafRecord> UnclosedBspLeafs;
UnclosedBspLeafs unclosedBspLeafs;
/// Migrant hedges are recorded here so we don't print too many warnings.
struct MigrantHEdgeRecord
{
HEdge* hedge;
Sector* facingSector;
MigrantHEdgeRecord(HEdge* _hedge, Sector* _facingSector)
: hedge(_hedge), facingSector(_facingSector)
{}
};
typedef std::map<HEdge*, MigrantHEdgeRecord> MigrantHEdges;
MigrantHEdges migrantHEdges;
/// @c true = a BSP for the current map has been built successfully.
bool builtOK;
Instance(GameMap* _map, uint* _numEditableVertexes,
Vertex*** _editableVertexes, int _splitCostFactor)
: splitCostFactor(_splitCostFactor),
map(_map),
numEditableVertexes(_numEditableVertexes), editableVertexes(_editableVertexes),
numNodes(0), numLeafs(0), numHEdges(0), numVertexes(0),
rootNode(0), partition(0), partitionLineDef(0),
unclosedSectors(), unclosedBspLeafs(), migrantHEdges(),
builtOK(false)
{
initPartitionInfo();
}
~Instance()
{
for(uint i = 0; i < *numEditableVertexes; ++i)
{
clearHEdgeTipsByVertex((*editableVertexes)[i]);
}
DENG2_FOR_EACH(it, vertexes, Vertexes::iterator)
{
Vertex* vtx = *it;
// Has ownership of this vertex been claimed?
if(!vtx) continue;
clearHEdgeTipsByVertex(vtx);
M_Free(vtx);
}
// We are finished with the BSP data.
if(rootNode)
{
// If ownership of the BSP data has been claimed this should be a no-op.
clearAllBspObjects();
// Destroy our private BSP tree.
delete rootNode;
}
}
/**
* Retrieve the extended build info for the specified @a lineDef.
* @return Extended info for that LineDef.
*/
LineDefInfo& lineDefInfo(const LineDef& lineDef) {
return lineDefInfos[lineDef.buildData.index - 1];
}
const LineDefInfo& lineDefInfo(const LineDef& lineDef) const {
return lineDefInfos[lineDef.buildData.index - 1];
}
/**
* Retrieve the extended build info for the specified @a hedge.
* @return Extended info for that HEdge.
*/
HEdgeInfo& hedgeInfo(HEdge& hedge)
{
HEdgeInfos::iterator found = hedgeInfos.find(&hedge);
if(found != hedgeInfos.end()) return found->second;
throw de::Error("Partitioner::hedgeInfo", QString("Failed locating HEdgeInfo for 0x%1").arg(de::dintptr(&hedge), 0, 16));
}
const HEdgeInfo& hedgeInfo(const HEdge& hedge) const
{
HEdgeInfos::const_iterator found = hedgeInfos.find(const_cast<HEdge*>(&hedge));
if(found != hedgeInfos.end()) return found->second;
throw de::Error("Partitioner::hedgeInfo", QString("Failed locating HEdgeInfo for 0x%1").arg(de::dintptr(&hedge), 0, 16));
}
/**
* Retrieve the extended build info for the specified @a vertex.
* @return Extended info for that Vertex.
*/
VertexInfo& vertexInfo(const Vertex& vertex) {
return vertexInfos[vertex.buildData.index - 1];
}
const VertexInfo& vertexInfo(const Vertex& vertex) const {
return vertexInfos[vertex.buildData.index - 1];
}
void initForMap()
{
uint numLineDefs = GameMap_LineDefCount(map);
lineDefInfos.resize(numLineDefs);
for(uint i = 0; i < numLineDefs; ++i)
{
LineDef* l = GameMap_LineDef(map, i);
LineDefInfo& info = lineDefInfo(*l);
const Vertex* start = l->v[0];
const Vertex* end = l->v[1];
// Check for zero-length line.
if((fabs(start->origin[VX] - end->origin[VX]) < DIST_EPSILON) &&
(fabs(start->origin[VY] - end->origin[VY]) < DIST_EPSILON))
info.flags |= LineDefInfo::ZEROLENGTH;
if(l->L_backsidedef && l->L_frontsidedef)
{
info.flags |= LineDefInfo::TWOSIDED;
if(l->L_backsector == l->L_frontsector)
info.flags |= LineDefInfo::SELFREF;
}
}
vertexInfos.resize(*numEditableVertexes);
}
void findMapBounds(AABoxd* aaBox) const
{
DENG_ASSERT(aaBox);
AABoxd bounds;
boolean initialized = false;
for(uint i = 0; i < GameMap_LineDefCount(map); ++i)
{
LineDef* line = GameMap_LineDef(map, i);
// Do not consider zero-length LineDefs.
if(lineDefInfo(*line).flags.testFlag(LineDefInfo::ZEROLENGTH)) continue;
AABoxd lineAABox;
initAABoxFromEditableLineDefVertexes(&lineAABox, line);
if(initialized)
{
V2d_AddToBox(bounds.arvec2, lineAABox.min);
}
else
{
V2d_InitBox(bounds.arvec2, lineAABox.min);
initialized = true;
}
V2d_AddToBox(bounds.arvec2, lineAABox.max);
}
if(initialized)
{
V2d_CopyBox(aaBox->arvec2, bounds.arvec2);
return;
}
// Clear.
V2d_Set(aaBox->min, DDMAXFLOAT, DDMAXFLOAT);
V2d_Set(aaBox->max, DDMINFLOAT, DDMINFLOAT);
}
HEdge* linkHEdgeInSuperBlockmap(SuperBlock& block, HEdge* hedge)
{
if(hedge)
{
HEdgeInfo& hInfo = hedgeInfo(*hedge);
SuperBlock* subblock = &block.push(*hedge);
// Associate this half-edge with the final subblock.
hInfo.bmapBlock = subblock;
}
return hedge;
}
/**
* Initially create all half-edges and add them to specified SuperBlock.
*/
void createInitialHEdges(SuperBlock& hedgeList)
{
DENG_ASSERT(map);
for(uint i = 0; i < map->numLineDefs; ++i)
{
LineDef* line = GameMap_LineDef(map, i);
HEdge* front = NULL;
HEdge* back = NULL;
// Polyobj lines are completely ignored.
if(line->inFlags & LF_POLYOBJ) continue;
// Ignore zero-length and polyobj lines.
if(!lineDefInfo(*line).flags.testFlag(LineDefInfo::ZEROLENGTH)
/*&& !lineDefInfo(*line).overlap*/)
{
// Check for Humungously long lines.
if(ABS(line->L_v1origin[VX] - line->L_v2origin[VX]) >= 10000 ||
ABS(line->L_v1origin[VY] - line->L_v2origin[VY]) >= 10000)
{
if(3000 >= V2d_Distance(line->L_v1origin, line->L_v2origin))
{
LOG_WARNING("LineDef #%d is very long, it may cause problems.") << line->buildData.index;
}
}
if(line->L_frontsidedef)
{
if(!line->L_frontsector)
LOG_INFO("Bad SideDef on LineDef #%d.") << line->buildData.index;
front = newHEdge(line, line, line->L_v1, line->L_v2, line->L_frontsector, false);
linkHEdgeInSuperBlockmap(hedgeList, front);
}
else
{
LOG_INFO("LineDef #%d has no front SideDef!") << line->buildData.index;
}
if(line->L_backsidedef)
{
if(!line->L_backsector)
LOG_INFO("Bad SideDef on LineDef #%d.") << line->buildData.index;
back = newHEdge(line, line, line->L_v2, line->L_v1, line->L_backsector, true);
linkHEdgeInSuperBlockmap(hedgeList, back);
if(front)
{
// Half-edges always maintain a one-to-one relationship with their
// twins, so if one gets split, the other must be split also.
back->twin = front;
front->twin = back;
}
}
else
{
if(lineDefInfo(*line).flags.testFlag(LineDefInfo::TWOSIDED))
{
LOG_INFO("LineDef #%d is two-sided but has no back SideDef.") << line->buildData.index;
lineDefInfo(*line).flags &= ~LineDefInfo::TWOSIDED;
}
// Handle the 'One-Sided Window' trick.
if(line->buildData.windowEffect && front)
{
HEdge* other = newHEdge(front->lineDef, line, line->L_v2, line->L_v1,
line->buildData.windowEffect, true);
linkHEdgeInSuperBlockmap(hedgeList, other);
// Setup the twin-ing (it's very strange to have a mini
// and a normal partnered together).
other->twin = front;
front->twin = other;
}
}
}
// @todo edge tips should be created when half-edges are created.
const coord_t x1 = line->L_v1origin[VX];
const coord_t y1 = line->L_v1origin[VY];
const coord_t x2 = line->L_v2origin[VX];
const coord_t y2 = line->L_v2origin[VY];
addHEdgeTip(line->v[0], M_DirectionToAngleXY(x2 - x1, y2 - y1), front, back);
addHEdgeTip(line->v[1], M_DirectionToAngleXY(x1 - x2, y1 - y2), back, front);
}
}
void initHEdgesAndBuildBsp(SuperBlockmap& blockmap)
{
DENG_ASSERT(map);
// It begins...
rootNode = NULL;
createInitialHEdges(blockmap.root());
builtOK = buildNodes(blockmap.root(), &rootNode);
if(rootNode)
{
windLeafs();
// We're done with the build info.
//clearAllHEdgeInfo();
}
}
const HPlaneIntercept* makePartitionIntersection(HEdge* hedge, int leftSide)
{
DENG_ASSERT(hedge);
// Already present on this edge?
Vertex* vertex = hedge->v[leftSide?1:0];
const HPlaneIntercept* inter = partitionInterceptByVertex(vertex);
if(inter) return inter;
LineDef* line = hedge->lineDef;
HEdgeIntercept* intercept = newHEdgeIntercept(vertex, line && lineDefInfo(*line).flags.testFlag(LineDefInfo::SELFREF));
return &partition->newIntercept(vertexDistanceFromPartition(vertex), intercept);
}
/**
* @return Same as @a final for caller convenience.
*/
HEdgeIntercept& mergeHEdgeIntercepts(HEdgeIntercept& final, HEdgeIntercept& other)
{
/*
LOG_TRACE("Merging intersections:");
HEdgeIntercept::DebugPrint(final);
HEdgeIntercept::DebugPrint(other);
*/
if(final.selfRef && !other.selfRef)
{
if(final.before && other.before)
final.before = other.before;
if(final.after && other.after)
final.after = other.after;
final.selfRef = false;
}
if(!final.before && other.before)
final.before = other.before;
if(!final.after && other.after)
final.after = other.after;
/*
LOG_TRACE("Result:");
HEdgeIntercept::DebugPrint(final);
*/
// Destroy the redundant other.
deleteHEdgeIntercept(other);
return final;
}
void mergeIntersections()
{
HPlane::Intercepts::const_iterator node = partition->intercepts().begin();
while(node != partition->intercepts().end())
{
HPlane::Intercepts::const_iterator np = node; np++;
if(np == partition->intercepts().end()) break;
coord_t len = *np - *node;
if(len < -0.1)
{
throw de::Error("Partitioner::MergeIntersections",
QString("Invalid intercept order - %1 > %2")
.arg(node->distance(), 0, 'f', 3)
.arg( np->distance(), 0, 'f', 3));
}
else if(len > 0.2)
{
node++;
continue;
}
HEdgeIntercept* cur = reinterpret_cast<HEdgeIntercept*>(node->userData());
HEdgeIntercept* next = reinterpret_cast<HEdgeIntercept*>(np->userData());
/*if(len > DIST_EPSILON)
{
LOG_DEBUG("Skipping very short half-edge (len: %1.3f) near [%1.1f, %1.1f]")
<< len << cur->vertex->V_pos[VX] << cur->vertex->V_pos[VY];
}*/
// Merge info for the two intersections into one (next is destroyed).
mergeHEdgeIntercepts(*cur, *next);
// Unlink this intercept.
partition->deleteIntercept(np);
}
}
void buildHEdgesAtIntersectionGaps(SuperBlock& rightList, SuperBlock& leftList)
{
HPlane::Intercepts::const_iterator node = partition->intercepts().begin();
while(node != partition->intercepts().end())
{
HPlane::Intercepts::const_iterator np = node; np++;
if(np == partition->intercepts().end()) break;
HEdgeIntercept* cur = reinterpret_cast<HEdgeIntercept*>((*node).userData());
HEdgeIntercept* next = reinterpret_cast<HEdgeIntercept*>((*np).userData());
if(!(!cur->after && !next->before))
{
// Check for some nasty open/closed or close/open cases.
if(cur->after && !next->before)
{
if(!cur->selfRef)
{
coord_t pos[2];
pos[VX] = cur->vertex->origin[VX] + next->vertex->origin[VX];
pos[VY] = cur->vertex->origin[VY] + next->vertex->origin[VY];
pos[VX] /= 2;
pos[VY] /= 2;
registerUnclosedSector(cur->after, pos[VX], pos[VY]);
}
}
else if(!cur->after && next->before)
{
if(!next->selfRef)
{
coord_t pos[2];
pos[VX] = cur->vertex->origin[VX] + next->vertex->origin[VX];
pos[VY] = cur->vertex->origin[VY] + next->vertex->origin[VY];
pos[VX] /= 2;
pos[VY] /= 2;
registerUnclosedSector(next->before, pos[VX], pos[VY]);
}
}
else
{
// This is definitetly open space.
HEdge* right, *left;
// Do a sanity check on the sectors (just for good measure).
if(cur->after != next->before)
{
if(!cur->selfRef && !next->selfRef)
{
LOG_DEBUG("Sector mismatch (#%d [%1.1f, %1.1f] != #%d [%1.1f, %1.1f]).")
<< cur->after->buildData.index-1 << cur->vertex->origin[VX]
<< cur->vertex->origin[VY] << next->before->buildData.index-1
<< next->vertex->origin[VX] << next->vertex->origin[VY];
}
// Choose the non-self-referencing sector when we can.
if(cur->selfRef && !next->selfRef)
{
cur->after = next->before;
}
}
addHEdgesBetweenIntercepts(cur, next, &right, &left);
// Add the new half-edges to the appropriate lists.
linkHEdgeInSuperBlockmap(rightList, right);
linkHEdgeInSuperBlockmap(leftList, left);
}
}
node++;
}
}
/**
* Splits the given half-edge at the point (x,y). The new half-edge is returned.
* The old half-edge is shortened (the original start vertex is unchanged), the
* new half-edge becomes the cut-off tail (keeping the original end vertex).
*
* @note If the half-edge has a twin it is also split.
*/
HEdge* splitHEdge(HEdge* oldHEdge, const_pvec2d_t point)
{
DENG_ASSERT(oldHEdge);
//LOG_DEBUG("Splitting hedge %p at [%1.1f, %1.1f].")
// << de::dintptr(oldHEdge) << x << y;
Vertex* newVert = newVertex(point);
{ HEdgeInfo& oldInfo = hedgeInfo(*oldHEdge);
addHEdgeTip(newVert, M_DirectionToAngleXY(-oldInfo.direction[VX], -oldInfo.direction[VY]), oldHEdge->twin, oldHEdge);
addHEdgeTip(newVert, M_DirectionToAngleXY( oldInfo.direction[VX], oldInfo.direction[VY]), oldHEdge, oldHEdge->twin);
}
HEdge* newHEdge = cloneHEdge(*oldHEdge);
HEdgeInfo& oldInfo = hedgeInfo(*oldHEdge);
HEdgeInfo& newInfo = hedgeInfo(*newHEdge);
newInfo.prevOnSide = oldHEdge;
oldInfo.nextOnSide = newHEdge;
oldHEdge->v[1] = newVert;
oldInfo.initFromHEdge(*oldHEdge);
newHEdge->v[0] = newVert;
newInfo.initFromHEdge(*newHEdge);
// Handle the twin.
if(oldHEdge->twin)
{
//LOG_DEBUG("Splitting hedge twin %p.") << de::dintptr(oldHEdge->twin);
// Copy the old hedge info.
newHEdge->twin = cloneHEdge(*oldHEdge->twin);
newHEdge->twin->twin = newHEdge;
hedgeInfo(*newHEdge->twin).nextOnSide = oldHEdge->twin;
hedgeInfo(*oldHEdge->twin).prevOnSide = newHEdge->twin;
oldHEdge->twin->v[0] = newVert;
hedgeInfo(*oldHEdge->twin).initFromHEdge(*oldHEdge->twin);
newHEdge->twin->v[1] = newVert;
hedgeInfo(*newHEdge->twin).initFromHEdge(*newHEdge->twin);
// Has this already been added to a leaf?
if(oldHEdge->twin->bspLeaf)
{
// Update the in-leaf references.
oldHEdge->twin->next = newHEdge->twin;
// There is now one more half-edge in this leaf.
oldHEdge->twin->bspLeaf->hedgeCount += 1;
}
}
return newHEdge;
}
/**
* Partition the given edge and perform any further necessary action (moving it
* into either the left list, right list, or splitting it).
*
* Take the given half-edge 'cur', compare it with the partition line and determine
* it's fate: moving it into either the left or right lists (perhaps both, when
* splitting it in two). Handles the twin as well. Updates the intersection list
* if the half-edge lies on or crosses the partition line.
*
* @note AJA: I have rewritten this routine based on evalPartition() (which I've
* also reworked, heavily). I think it is important that both these routines
* follow the exact same logic.
*/
void divideHEdge(HEdge* hedge, SuperBlock& rightList, SuperBlock& leftList)
{
#define RIGHT 0
#define LEFT 1
// Determine the relationship between this half-edge and the partition plane.
coord_t a = hedgeDistanceFromPartition(hedge, false/*start vertex*/);
coord_t b = hedgeDistanceFromPartition(hedge, true/*end vertex*/);
/// @kludge Half-edges produced from the same source linedef must always
/// be treated as collinear.
/// @todo Why is this override necessary?
HEdgeInfo& hInfo = hedgeInfo(*hedge);
if(hInfo.sourceLineDef == partitionInfo.sourceLineDef)
a = b = 0;
// kludge end
// Collinear with the partition plane?
if(fabs(a) <= DIST_EPSILON && fabs(b) <= DIST_EPSILON)
{
makePartitionIntersection(hedge, RIGHT);
makePartitionIntersection(hedge, LEFT);
// Direction (vs that of the partition plane) determines in which subset
// this half-edge belongs.
if(hInfo.direction[VX] * partitionInfo.direction[VX] +
hInfo.direction[VY] * partitionInfo.direction[VY] < 0)
{
linkHEdgeInSuperBlockmap(leftList, hedge);
}
else
{
linkHEdgeInSuperBlockmap(rightList, hedge);
}
return;
}
// Right of the partition plane?.
if(a > -DIST_EPSILON && b > -DIST_EPSILON)
{
// Close enough to intersect?
if(a < DIST_EPSILON)
makePartitionIntersection(hedge, RIGHT);
else if(b < DIST_EPSILON)
makePartitionIntersection(hedge, LEFT);
linkHEdgeInSuperBlockmap(rightList, hedge);
return;
}
// Left of the partition plane?
if(a < DIST_EPSILON && b < DIST_EPSILON)
{
// Close enough to intersect?
if(a > -DIST_EPSILON)
makePartitionIntersection(hedge, RIGHT);
else if(b > -DIST_EPSILON)
makePartitionIntersection(hedge, LEFT);
linkHEdgeInSuperBlockmap(leftList, hedge);
return;
}
/**
* Straddles the partition plane and must therefore be split.
*/
vec2d_t point;
interceptHEdgePartition(hedge, a, b, point);
HEdge* newHEdge = splitHEdge(hedge, point);
// Ensure the new twin is inserted into the same block as the old twin.
if(hedge->twin && !hedge->twin->bspLeaf)
{
SuperBlock* bmapBlock = hedgeInfo(*hedge->twin).bmapBlock;
DENG_ASSERT(bmapBlock);
linkHEdgeInSuperBlockmap(*bmapBlock, newHEdge->twin);
}
makePartitionIntersection(hedge, LEFT);
if(a < 0)
{
linkHEdgeInSuperBlockmap(rightList, newHEdge);
linkHEdgeInSuperBlockmap(leftList, hedge);
}
else
{
linkHEdgeInSuperBlockmap(rightList, hedge);
linkHEdgeInSuperBlockmap(leftList, newHEdge);
}
#undef LEFT
#undef RIGHT
}
/**
* Remove all the half-edges from the list, partitioning them into the left or
* right lists based on the given partition line. Adds any intersections onto the
* intersection list as it goes.
*/
void partitionHEdges(SuperBlock& hedgeList, SuperBlock& rights, SuperBlock& lefts)
{
// Iterative pre-order traversal of SuperBlock.
SuperBlock* cur = &hedgeList;
SuperBlock* prev = 0;
while(cur)
{
while(cur)
{
HEdge* hedge;
while((hedge = cur->pop()))
{
// Disassociate the half-edge from the blockmap.
hedgeInfo(*hedge).bmapBlock = 0;
divideHEdge(hedge, rights, lefts);
}
if(prev == cur->parent())
{
// Descending - right first, then left.
prev = cur;
if(cur->hasRight()) cur = cur->right();
else cur = cur->left();
}
else if(prev == cur->right())
{
// Last moved up the right branch - descend the left.
prev = cur;
cur = cur->left();
}
else if(prev == cur->left())
{
// Last moved up the left branch - continue upward.
prev = cur;
cur = cur->parent();
}
}
if(prev)
{
// No left child - back up.
cur = prev->parent();
}
}
// Sanity checks...
if(!rights.totalHEdgeCount())
throw de::Error("Partitioner::partitionhedges", "Separated half-edge has no right side.");
if(!lefts.totalHEdgeCount())
throw de::Error("Partitioner::partitionhedges", "Separated half-edge has no left side.");
}
void evalPartitionCostForHEdge(const HEdgeInfo& partInfo, int costFactorMultiplier,
const HEdge* hedge, PartitionCost& cost)
{
#define ADD_LEFT() \
if (hedge->lineDef) cost.realLeft += 1; \
else cost.miniLeft += 1; \
#define ADD_RIGHT() \
if (hedge->lineDef) cost.realRight += 1; \
else cost.miniRight += 1; \
DENG_ASSERT(hedge);
coord_t a, b, fa, fb;
// Get state of lines' relation to each other.
const HEdgeInfo& hInfo = hedgeInfo(*hedge);
if(hInfo.sourceLineDef == partInfo.sourceLineDef)
{
a = b = fa = fb = 0;
}
else
{
a = V2d_PointLinePerpDistance(hInfo.start, partInfo.direction, partInfo.pPerp, partInfo.pLength);
b = V2d_PointLinePerpDistance(hInfo.end, partInfo.direction, partInfo.pPerp, partInfo.pLength);
fa = fabs(a);
fb = fabs(b);
}
// Collinear?
if(fa <= DIST_EPSILON && fb <= DIST_EPSILON)
{
// This half-edge runs along the same line as the partition.
// hedge whether it goes in the same direction or the opposite.
if(hInfo.direction[VX] * partInfo.direction[VX] + hInfo.direction[VY] * partInfo.direction[VY] < 0)
{
ADD_LEFT();
}
else
{
ADD_RIGHT();
}
return;
}
// Off to the right?
if(a > -DIST_EPSILON && b > -DIST_EPSILON)
{
ADD_RIGHT();
// Near miss?
if((a >= SHORT_HEDGE_EPSILON && b >= SHORT_HEDGE_EPSILON) ||
(a <= DIST_EPSILON && b >= SHORT_HEDGE_EPSILON) ||
(b <= DIST_EPSILON && a >= SHORT_HEDGE_EPSILON))
{
// No.
return;
}
cost.nearMiss += 1;
/**
* Near misses are bad, since they have the potential to cause really short
* minihedges to be created in future processing. Thus the closer the near
* miss, the higher the cost.
*/
double qnty;
if(a <= DIST_EPSILON || b <= DIST_EPSILON)
qnty = SHORT_HEDGE_EPSILON / MAX_OF(a, b);
else
qnty = SHORT_HEDGE_EPSILON / MIN_OF(a, b);
cost.total += (int) (100 * costFactorMultiplier * (qnty * qnty - 1.0));
return;
}
// Off to the left?
if(a < DIST_EPSILON && b < DIST_EPSILON)
{
ADD_LEFT();
// Near miss?
if((a <= -SHORT_HEDGE_EPSILON && b <= -SHORT_HEDGE_EPSILON) ||
(a >= -DIST_EPSILON && b <= -SHORT_HEDGE_EPSILON) ||
(b >= -DIST_EPSILON && a <= -SHORT_HEDGE_EPSILON))
{
// No.
return;
}
cost.nearMiss += 1;
// The closer the miss, the higher the cost (see note above).
double qnty;
if(a >= -DIST_EPSILON || b >= -DIST_EPSILON)
qnty = SHORT_HEDGE_EPSILON / -MIN_OF(a, b);
else
qnty = SHORT_HEDGE_EPSILON / -MAX_OF(a, b);
cost.total += (int) (70 * costFactorMultiplier * (qnty * qnty - 1.0));
return;
}
/**
* When we reach here, we have a and b non-zero and opposite sign,
* hence this half-edge will be split by the partition line.
*/
cost.splits += 1;
cost.total += 100 * costFactorMultiplier;
/**
* If the split point is very close to one end, which is quite an undesirable
* situation (producing really short edges), thus a rather hefty surcharge.
*/
if(fa < SHORT_HEDGE_EPSILON || fb < SHORT_HEDGE_EPSILON)
{
cost.iffy += 1;
// The closer to the end, the higher the cost.
double qnty = SHORT_HEDGE_EPSILON / MIN_OF(fa, fb);
cost.total += (int) (140 * costFactorMultiplier * (qnty * qnty - 1.0));
}
#undef ADD_RIGHT
#undef ADD_LEFT
}
/**
* @param best Best half-edge found thus far.
* @param bestCost Running cost total result for the best half-edge found thus far.
* @param hedge The candidate half-edge to be evaluated.
* @param cost PartitionCost analysis to be completed for this candidate. Must have
* been initialized prior to calling this.
* @return @c true iff this half-edge is suitable for use as a partition.
*/
int evalPartitionCostForSuperBlock(const SuperBlock& block, int splitCostFactor,
HEdge* best, const PartitionCost& bestCost, HEdge* hedge, PartitionCost& cost)
{
/**
* Test the whole block against the partition line to quickly handle all the
* half-edges within it at once. Only when the partition line intercepts the
* box do we need to go deeper into it.
*/
const HEdgeInfo& hInfo = hedgeInfo(*hedge);
const AABox& blockBounds = block.bounds();
AABoxd bounds;
/// @todo Why are we extending the bounding box for this test? Also, there is
/// no need to changed from integer to floating-point each time this is
/// tested. (If we intend to do this with floating-point then we should
/// return that representation in SuperBlock::bounds() ).
bounds.minX = (double)blockBounds.minX - SHORT_HEDGE_EPSILON * 1.5;