/
Patch.cpp
2631 lines (2148 loc) · 80.2 KB
/
Patch.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
#include "Patch.h"
#include "i18n.h"
#include "ipatch.h"
#include "shaderlib.h"
#include "irenderable.h"
#include "itextstream.h"
#include "iselectiontest.h"
#include "registry/registry.h"
#include "math/Frustum.h"
#include "math/Ray.h"
#include "texturelib.h"
#include "brush/TextureProjection.h"
#include "brush/Winding.h"
#include "command/ExecutionFailure.h"
#include "selection/algorithm/Shader.h"
#include "selection/algorithm/Texturing.h"
#include "PatchSavedState.h"
#include "PatchNode.h"
// ====== Helper Functions ==================================================================
inline VertexPointer vertexpointer_Meshvertex(const MeshVertex* array) {
return VertexPointer(&array->vertex, sizeof(MeshVertex));
}
inline const Colour4b colour_for_index(std::size_t i, std::size_t width)
{
static const Vector3& cornerColourVec = GlobalPatchModule().getSettings().getVertexColour(patch::PatchEditVertexType::Corners);
static const Vector3& insideColourVec = GlobalPatchModule().getSettings().getVertexColour(patch::PatchEditVertexType::Inside);
const Colour4b colour_corner(int(cornerColourVec[0]*255), int(cornerColourVec[1]*255),
int(cornerColourVec[2]*255), 255);
const Colour4b colour_inside(int(insideColourVec[0]*255), int(insideColourVec[1]*255),
int(insideColourVec[2]*255), 255);
return (i%2 || (i/width)%2) ? colour_inside : colour_corner;
}
inline bool double_valid(double f) {
return f == f;
}
// ====== Patch Implementation =========================================================================
// Constructor
Patch::Patch(PatchNode& node) :
_node(node),
_undoStateSaver(nullptr),
_transformChanged(false),
_tesselationChanged(true),
_shader(texdef_name_default())
{
construct();
}
// Copy constructor (create this patch from another patch)
Patch::Patch(const Patch& other, PatchNode& node) :
IPatch(other),
Bounded(other),
Snappable(other),
IUndoable(other),
_node(node),
_undoStateSaver(nullptr),
_transformChanged(false),
_tesselationChanged(true),
_shader(other._shader.getMaterialName())
{
// Initalise the default values
construct();
// Copy over the definitions from the <other> patch
_patchDef3 = other._patchDef3;
_subDivisions = other._subDivisions;
setDims(other._width, other._height);
copy_ctrl(_ctrl.begin(), other._ctrl.begin(), other._ctrl.begin()+(_width*_height));
_shader.setMaterialName(other._shader.getMaterialName());
controlPointsChanged();
}
void Patch::construct()
{
_width = _height = 0;
_patchDef3 = false;
_subDivisions = Subdivisions(0, 0);
// Check, if the shader name is correct
check_shader();
}
// Get the current control point array
PatchControlArray& Patch::getControlPoints() {
return _ctrl;
}
// Same as above, just for const arguments
const PatchControlArray& Patch::getControlPoints() const {
return _ctrl;
}
// Get the (temporary) transformed control point array, not the saved ones
PatchControlArray& Patch::getControlPointsTransformed() {
return _ctrlTransformed;
}
const PatchControlArray& Patch::getControlPointsTransformed() const {
return _ctrlTransformed;
}
std::size_t Patch::getWidth() const {
return _width;
}
std::size_t Patch::getHeight() const {
return _height;
}
void Patch::setDims(std::size_t w, std::size_t h)
{
if((w%2)==0)
w -= 1;
ASSERT_MESSAGE(w <= MAX_PATCH_WIDTH, "patch too wide");
if(w > MAX_PATCH_WIDTH)
w = MAX_PATCH_WIDTH;
else if(w < MIN_PATCH_WIDTH)
w = MIN_PATCH_WIDTH;
if((h%2)==0)
_height -= 1;
ASSERT_MESSAGE(h <= MAX_PATCH_HEIGHT, "patch too tall");
if(h > MAX_PATCH_HEIGHT)
h = MAX_PATCH_HEIGHT;
else if(h < MIN_PATCH_HEIGHT)
h = MIN_PATCH_HEIGHT;
_width = w;
_height = h;
if(_width * _height != _ctrl.size())
{
_ctrl.resize(_width * _height);
_ctrlTransformed.resize(_ctrl.size());
_node.updateSelectableControls();
}
}
PatchNode& Patch::getPatchNode()
{
return _node;
}
void Patch::connectUndoSystem(IUndoSystem& undoSystem)
{
assert(!_undoStateSaver);
// Acquire a new state saver
_undoStateSaver = undoSystem.getStateSaver(*this);
}
// Remove the attached instance and decrease the counters
void Patch::disconnectUndoSystem(IUndoSystem& undoSystem)
{
assert(_undoStateSaver);
_undoStateSaver = nullptr;
undoSystem.releaseStateSaver(*this);
}
// Return the interally stored AABB
const AABB& Patch::localAABB() const
{
return _localAABB;
}
RenderSystemPtr Patch::getRenderSystem() const
{
return _renderSystem.lock();
}
void Patch::setRenderSystem(const RenderSystemPtr& renderSystem)
{
_renderSystem = renderSystem;
_shader.setRenderSystem(renderSystem);
}
// Implementation of the abstract method of SelectionTestable
// Called to test if the patch can be selected by the mouse pointer
void Patch::testSelect(Selector& selector, SelectionTest& test)
{
// ensure the tesselation is up to date
updateTesselation();
// The updateTesselation routine might have produced a degenerate patch, catch this
if (_mesh.vertices.empty()) return;
SelectionIntersection best;
IndexPointer::index_type* pIndex = &_mesh.indices.front();
for (std::size_t s=0; s<_mesh.numStrips; s++) {
test.TestQuadStrip(vertexpointer_Meshvertex(&_mesh.vertices.front()), IndexPointer(pIndex, _mesh.lenStrips), best);
pIndex += _mesh.lenStrips;
}
if (best.isValid()) {
selector.addIntersection(best);
}
}
// Transform this patch as defined by the transformation matrix <matrix>
void Patch::transform(const Matrix4& matrix)
{
// Cycle through all the patch control vertices and transform the points
for (PatchControlIter i = _ctrlTransformed.begin();
i != _ctrlTransformed.end();
++i)
{
i->vertex = matrix.transformPoint(i->vertex);
}
// Check the handedness of the matrix and invert it if needed
if(matrix.getHandedness() == Matrix4::LEFTHANDED)
{
PatchControlArray_invert(_ctrlTransformed, _width, _height);
}
// Mark this patch as changed
transformChanged();
}
// Called if the patch has changed, so that the dirty flags are set
void Patch::transformChanged()
{
_transformChanged = true;
_tesselationChanged = true;
}
// Called to evaluate the transform
void Patch::evaluateTransform()
{
// Only do something, if the patch really has changed
if (_transformChanged)
{
_transformChanged = false;
revertTransform();
_node.evaluateTransform();
}
}
// Revert the changes, fall back to the saved state in <_ctrl>
void Patch::revertTransform()
{
_ctrlTransformed = _ctrl;
}
// Apply the transformed control array, save it into <_ctrl> and overwrite the old values
void Patch::freezeTransform()
{
undoSave();
// Save the transformed working set array over _ctrl
_ctrl = _ctrlTransformed;
// Don't call controlPointsChanged() here since that one will re-apply the
// current transformation matrix, possible the second time.
transformChanged();
updateTesselation();
for (Observers::iterator i = _observers.begin(); i != _observers.end();)
{
(*i++)->onPatchControlPointsChanged();
}
}
// callback for changed control points
void Patch::controlPointsChanged()
{
transformChanged();
evaluateTransform();
updateTesselation();
_node.onControlPointsChanged();
for (Observers::iterator i = _observers.begin(); i != _observers.end();)
{
(*i++)->onPatchControlPointsChanged();
}
}
// Snaps the control points to the grid
void Patch::snapto(float snap)
{
undoSave();
for(PatchControlIter i = _ctrl.begin(); i != _ctrl.end(); ++i)
{
i->vertex.snap(snap);
}
controlPointsChanged();
}
const std::string& Patch::getShader() const
{
return _shader.getMaterialName();
}
void Patch::setShader(const std::string& name)
{
undoSave();
_shader.setMaterialName(name);
// Check if the shader is ok
check_shader();
// Call the callback functions
textureChanged();
}
const SurfaceShader& Patch::getSurfaceShader() const
{
return _shader;
}
SurfaceShader& Patch::getSurfaceShader()
{
return _shader;
}
bool Patch::hasVisibleMaterial() const
{
if (!_shader.getGLShader()) return false;
const MaterialPtr& material = _shader.getGLShader()->getMaterial();
return material && material->isVisible();
}
float Patch::getTextureAspectRatio() const
{
return _shader.getTextureAspectRatio();
}
int Patch::getShaderFlags() const
{
if (_shader.getGLShader() != 0)
{
return _shader.getGLShader()->getFlags();
}
return 0;
}
// Return a defined patch control vertex at <row>,<col>
PatchControl& Patch::ctrlAt(std::size_t row, std::size_t col) {
return _ctrl[row*_width+col];
}
// The same as above just for const
const PatchControl& Patch::ctrlAt(std::size_t row, std::size_t col) const {
return _ctrl[row*_width+col];
}
PatchControl& Patch::getTransformedCtrlAt(std::size_t row, std::size_t col)
{
if (_ctrlTransformed.empty())
{
_ctrlTransformed = _ctrl;
}
return _ctrlTransformed[row * _width + col];
}
// called just before an action to save the undo state
void Patch::undoSave()
{
// Notify the undo observer to save this patch state
if (_undoStateSaver != NULL)
{
_undoStateSaver->saveState();
}
}
// Save the current patch state into a new UndoMemento instance (allocated on heap) and return it to the undo observer
IUndoMementoPtr Patch::exportState() const
{
return IUndoMementoPtr(new SavedState(_width, _height, _ctrl, _patchDef3, _subDivisions.x(), _subDivisions.y(), _shader.getMaterialName()));
}
// Revert the state of this patch to the one that has been saved in the UndoMemento
void Patch::importState(const IUndoMementoPtr& state)
{
undoSave();
const SavedState& other = *(std::static_pointer_cast<SavedState>(state));
// begin duplicate of SavedState copy constructor, needs refactoring
// copy construct
{
_width = other.m_width;
_height = other.m_height;
_ctrl = other.m_ctrl;
_ctrlTransformed = _ctrl;
_node.updateSelectableControls();
_patchDef3 = other.m_patchDef3;
_subDivisions = Subdivisions(other.m_subdivisions_x, other.m_subdivisions_y);
_shader.setMaterialName(other._materialName);
}
// end duplicate code
// Notify that this patch has changed
textureChanged();
controlPointsChanged();
}
void Patch::check_shader()
{
if (!shader_valid(getShader().c_str()))
{
rError() << "patch has invalid texture name: '" << getShader() << "'\n";
}
}
// Patch Destructor
Patch::~Patch()
{
for (Observers::iterator i = _observers.begin(); i != _observers.end();)
{
(*i++)->onPatchDestruction();
}
}
bool Patch::isValid() const
{
if(!_width || !_height)
{
return false;
}
for(PatchControlConstIter i = _ctrl.begin(); i != _ctrl.end(); ++i)
{
if(!double_valid((*i).vertex.x())
|| !double_valid((*i).vertex.y())
|| !double_valid((*i).vertex.z())
|| !double_valid((*i).texcoord.x())
|| !double_valid((*i).texcoord.y()))
{
rError() << "patch has invalid control points\n";
return false;
}
}
return true;
}
bool Patch::isDegenerate() const {
if (!isValid()) {
// Invalid patches are also "degenerate"
return true;
}
Vector3 prev(0,0,0);
// Compare each control's 3D coordinates with the previous one and break out
// on the first non-equal one
for (PatchControlConstIter i = _ctrl.begin(); i != _ctrl.end(); ++i) {
// Skip the first comparison
if (i != _ctrl.begin() && !math::isNear(i->vertex, prev, 0.0001)) {
return false;
}
// Remember the coords of this vertex
prev = i->vertex;
}
// The loop went through, all vertices the same
return true;
}
void Patch::updateTesselation(bool force)
{
// Only do something if the tesselation has actually changed
if (!_tesselationChanged && !force) return;
_tesselationChanged = false;
if (!isValid())
{
_mesh.clear();
_localAABB = AABB();
return;
}
// Run the tesselation code
_mesh.generate(_width, _height, _ctrlTransformed, subdivisionsFixed(), getSubdivisions(), _node.getRenderEntity());
updateAABB();
_node.onTesselationChanged();
}
void Patch::invertMatrix()
{
undoSave();
PatchControlArray_invert(_ctrl, _width, _height);
controlPointsChanged();
}
void Patch::transposeMatrix()
{
undoSave();
// greebo: create a new temporary control array to hold the "old" matrix
PatchControlArray tmp = _ctrl;
std::size_t i = 0;
for (std::size_t w = 0; w < _width; ++w)
{
for (std::size_t h = 0; h < _height; ++h)
{
// Copy elements such that the columns end up as rows
_ctrl[i++] = tmp[h*_width + w];
}
}
std::swap(_width, _height);
controlPointsChanged();
}
void Patch::Redisperse(EMatrixMajor mt)
{
std::size_t w, h, width, height, row_stride, col_stride;
PatchControlIter p1, p2, p3;
undoSave();
switch(mt)
{
case COL:
width = (_width-1)>>1;
height = _height;
col_stride = 1;
row_stride = _width;
break;
case ROW:
width = (_height-1)>>1;
height = _width;
col_stride = _width;
row_stride = 1;
break;
default:
ERROR_MESSAGE("neither row-major nor column-major");
return;
}
for(h=0;h<height;h++)
{
p1 = _ctrl.begin()+(h*row_stride);
for(w=0;w<width;w++)
{
p2 = p1+col_stride;
p3 = p2+col_stride;
p2->vertex = math::midPoint(p1->vertex, p3->vertex);
p1 = p3;
}
}
controlPointsChanged();
}
void Patch::redisperseRows()
{
Redisperse(ROW);
}
void Patch::redisperseColumns()
{
Redisperse(COL);
}
void Patch::insertRemove(bool insert, bool column, bool first)
{
undoSave();
try
{
if (insert)
{
// Decide whether we should insert rows or columns
if (column) {
// The insert point is 1 for "beginning" and width-2 for "end"
insertColumns(first ? 1 : _width-2);
}
else {
// The insert point is 1 for "beginning" and height-2 for "end"
insertRows(first ? 1 : _height-2);
}
}
else {
// Col/Row Removal
if (column) {
// Column removal, pass TRUE
removePoints(true, first ? 2 : _width - 3);
}
else {
// Row removal, pass FALSE
removePoints(false, first ? 2 : _height - 3);
}
}
}
catch (const GenericPatchException& g) {
rError() << "Error manipulating patch dimensions: " << g.what() << "\n";
}
controlPointsChanged();
}
void Patch::appendPoints(bool columns, bool beginning) {
bool rows = !columns; // Shortcut for readability
if ((columns && _width + 2 > MAX_PATCH_WIDTH) ||
(rows && _height + 2 > MAX_PATCH_HEIGHT))
{
rError() << "Patch::appendPoints() error: " <<
"Cannot make patch any larger.\n";
return;
}
// Sanity check passed, now start the action
undoSave();
// Create a backup of the old control vertices
PatchControlArray oldCtrl = _ctrl;
std::size_t oldHeight = _height;
std::size_t oldWidth = _width;
// Resize this patch
setDims(columns ? oldWidth+2 : oldWidth, rows ? oldHeight+2 : oldHeight);
// Specify the target row to copy the values to
std::size_t targetColStart = (columns && beginning) ? 2 : 0;
std::size_t targetRowStart = (rows && beginning) ? 2 : 0;
// We're copying the old patch matrix into a sub-matrix of the new patch
// Fill in the control vertex values into the target area using this loop
for (std::size_t newRow = targetRowStart, oldRow = 0;
newRow < _height && oldRow < oldHeight;
newRow++, oldRow++)
{
for (std::size_t newCol = targetColStart, oldCol = 0;
oldCol < oldWidth && newCol < _width;
oldCol++, newCol++)
{
// Copy the control vertex from the old patch to the new patch
ctrlAt(newRow, newCol).vertex = oldCtrl[oldRow*oldWidth + oldCol].vertex;
ctrlAt(newRow, newCol).texcoord = oldCtrl[oldRow*oldWidth + oldCol].texcoord;
}
}
if (columns) {
// Extrapolate the vertex attributes of the columns
// These are the indices of the new columns
std::size_t newCol1 = beginning ? 0 : _width - 1; // The outermost column
std::size_t newCol2 = beginning ? 1 : _width - 2; // The nearest column
// This indicates the direction we are taking the base values from
// If we start at the beginning, we have to take the values on
// the "right", hence the +1 index
int neighbour = beginning ? +1 : -1;
for (std::size_t row = 0; row < _height; row++) {
// The distance of the two neighbouring columns,
// this is taken as extrapolation value
Vector3 vertexDiff = ctrlAt(row, newCol2 + neighbour).vertex -
ctrlAt(row, newCol2 + 2*neighbour).vertex;
Vector2 texDiff = ctrlAt(row, newCol2 + neighbour).texcoord -
ctrlAt(row, newCol2 + 2*neighbour).texcoord;
// Extrapolate the values of the nearest column
ctrlAt(row, newCol2).vertex = ctrlAt(row, newCol2 + neighbour).vertex + vertexDiff;
ctrlAt(row, newCol2).texcoord = ctrlAt(row, newCol2 + neighbour).texcoord + texDiff;
// Extrapolate once again linearly from the nearest column to the outermost column
ctrlAt(row, newCol1).vertex = ctrlAt(row, newCol2).vertex + vertexDiff;
ctrlAt(row, newCol1).texcoord = ctrlAt(row, newCol2).texcoord + texDiff;
}
}
else {
// Extrapolate the vertex attributes of the rows
// These are the indices of the new rows
std::size_t newRow1 = beginning ? 0 : _height - 1; // The outermost row
std::size_t newRow2 = beginning ? 1 : _height - 2; // The nearest row
// This indicates the direction we are taking the base values from
// If we start at the beginning, we have to take the values on
// the "right", hence the +1 index
int neighbour = beginning ? +1 : -1;
for (std::size_t col = 0; col < _width; col++) {
// The distance of the two neighbouring rows,
// this is taken as extrapolation value
Vector3 vertexDiff = ctrlAt(newRow2 + neighbour, col).vertex -
ctrlAt(newRow2 + 2*neighbour, col).vertex;
Vector2 texDiff = ctrlAt(newRow2 + neighbour, col).texcoord -
ctrlAt(newRow2 + 2*neighbour, col).texcoord;
// Extrapolate the values of the nearest row
ctrlAt(newRow2, col).vertex = ctrlAt(newRow2 + neighbour, col).vertex + vertexDiff;
ctrlAt(newRow2, col).texcoord = ctrlAt(newRow2 + neighbour, col).texcoord + texDiff;
// Extrapolate once again linearly from the nearest row to the outermost row
ctrlAt(newRow1, col).vertex = ctrlAt(newRow2, col).vertex + vertexDiff;
ctrlAt(newRow1, col).texcoord = ctrlAt(newRow2, col).texcoord + texDiff;
}
}
controlPointsChanged();
}
Patch* Patch::MakeCap(Patch* patch, patch::CapType capType, EMatrixMajor matrixMajor, bool front)
{
auto width = matrixMajor == ROW ? _width : _height;
auto height = matrixMajor == ROW ? _height : _width;
std::vector<Vector3> points(width);
auto index = front ? 0 : height-1;
for (auto i = 0; i < width; i++)
{
const auto& ctrl = matrixMajor == ROW ? ctrlAt(index, i) : ctrlAt(i, index);
points[front ? i : width - 1 - i] = ctrl.vertex;
}
// Inherit the same fixed tesselation as the source patch
if (subdivisionsFixed())
{
const auto& subdivisions = getSubdivisions();
switch (capType)
{
case patch::CapType::InvertedEndCap:
patch->setFixedSubdivisions(true, subdivisions);
break;
default:
// Flip the subdivision X/Y values for all other cap types
patch->setFixedSubdivisions(true, { subdivisions.y(), subdivisions.x() });
}
}
patch->constructSeam(capType, points, width);
// greebo: Apply natural texture to that patch, to fix the texcoord==1.#INF bug.
patch->scaleTextureNaturally();
return patch;
}
void Patch::flipTexture(int nAxis)
{
selection::algorithm::TextureFlipper::FlipPatch(*this, nAxis);
}
/** greebo: Helper function that shifts all control points in
* texture space about <s,t>
*/
void Patch::translateTexCoords(const Vector2& translation)
{
// Cycle through all control points and shift them in texture space
for (PatchControlIter i = _ctrl.begin(); i != _ctrl.end(); ++i)
{
i->texcoord += translation;
}
}
void Patch::translateTexture(float s, float t)
{
undoSave();
s = -1 * s / _shader.getWidth();
t = t / _shader.getHeight();
translateTexCoords(Vector2(s,t));
controlPointsChanged();
}
void Patch::scaleTexture(float s, float t)
{
selection::algorithm::TextureScaler::ScalePatch(*this, { s, t });
}
void Patch::rotateTexture(float angle)
{
selection::algorithm::TextureRotator::RotatePatch(*this, degrees_to_radians(angle));
}
void Patch::fitTexture(float s, float t)
{
// Save the current patch state to the undoMemento
undoSave();
/* greebo: Calculate the texture width and height increment per control point.
* If we have a 4x4 patch and want to tile it 3x3, the distance
* from one control point to the next one has to cover 3/4 of a full texture,
* hence texture_x_repeat/patch_width and texture_y_repeat/patch_height.*/
float sIncr = s / static_cast<float>(_width - 1);
float tIncr = t / static_cast<float>(_height - 1);
// Set the pointer to the first control point
PatchControlIter pDest = _ctrl.begin();
float tc = 0;
// Cycle through the patch matrix (row per row)
// Increment the <tc> counter by <tIncr> increment
for (std::size_t h=0; h < _height; h++, tc += tIncr)
{
float sc = 0;
// Cycle through the row points: reset sc to zero
// and increment it by sIncr at each step.
for (std::size_t w = 0; w < _width; w++, sc += sIncr)
{
// Set the texture coordinates
pDest->texcoord[0] = sc;
pDest->texcoord[1] = tc;
// Set the pointer to the next control point
pDest++;
}
}
// Notify the patch
controlPointsChanged();
}
void Patch::scaleTextureNaturally()
{
// Save the undo memento
undoSave();
// Retrieve the default scale from the registry
auto defaultScale = registry::getValue<float>("user/ui/textures/defaultTextureScale");
// Cycles through all the patch columns and assigns s/t coordinates.
// During each column or row cycle, the highest world distance between columns or rows
// determines the distance in UV space (longest distance is taken).
// World distances are scaled to UV space with the actual texture width/height,
// scaled by the value in the registry.
auto horizScale = 1.0f / (static_cast<float>(_shader.getWidth()) * defaultScale);
double texcoordX = 0;
// Cycle through the patch width,
for (std::size_t w = 0; w < _width; w++)
{
// Apply the currently active <tex> value to the control point texture coordinates.
for (std::size_t h = 0; h < _height; h++)
{
// Set the x-coord (or better s-coord?) of the texture to tex.
// For the first width cycle this is tex=0, so the texture is not shifted at the first vertex
ctrlAt(h, w).texcoord[0] = texcoordX;
}
// If we reached the last row (_width - 1) we are finished (all coordinates are applied)
if (w + 1 == _width) break;
// Determine the texcoord of the next column
double highestNextTexCoord = 0;
// Determine the longest distance to the next column.
// Again, cycle through the current column
for (std::size_t h = 0; h < _height; h++)
{
// v is the vector pointing from one control point to the next neighbour
auto worldDistance = ctrlAt(h, w).vertex - ctrlAt(h, w + 1).vertex;
// Scale the distance in world coordinates into texture coords
double nextTexcoordX = texcoordX + worldDistance.getLength() * horizScale;
// Use the farthest extrapolated texture cooord
highestNextTexCoord = std::max(highestNextTexCoord, nextTexcoordX);
}
// Remember the highest found texcoord, assign it to the next column
texcoordX = highestNextTexCoord;
}
// Now the same goes for the texture height, cycle through all the rows
// and calculate the longest distances, convert them to texture coordinates
// and apply them to the according texture coordinates.
auto vertScale = 1.0f / (static_cast<float>(_shader.getHeight()) * defaultScale);
double texcoordY = 0;
// Each row is visited once
for (std::size_t h = 0; h < _height; h++)
{
// Visit every vertex in this row, assigning the current texCoordY
for (std::size_t w = 0; w < _width; w++)
{
ctrlAt(h, w).texcoord[1] = -texcoordY;
}
if (h + 1 == _height) break;
double highestNextTexCoord = 0;
for (std::size_t w = 0; w < _width; w++)
{
auto worldDistance = ctrlAt(h, w).vertex - ctrlAt(h + 1, w).vertex;
double nextTexcoordY = texcoordY + worldDistance.getLength() * vertScale;
highestNextTexCoord = std::max(highestNextTexCoord, nextTexcoordY);
}
texcoordY = highestNextTexCoord;
}
// Notify the patch that it control points got changed
controlPointsChanged();
}
void Patch::updateAABB()
{
AABB aabb;
for(PatchControlIter i = _ctrlTransformed.begin(); i != _ctrlTransformed.end(); ++i)
{
aabb.includePoint(i->vertex);
}
// greebo: Only trigger the callbacks if the bounds actually changed
if (_localAABB != aabb)
{
_localAABB = aabb;
_node.boundsChanged();
}
}
// Inserts two columns before and after the column having the index <colIndex>
void Patch::insertColumns(std::size_t colIndex) {
if (colIndex == 0 || colIndex == _width) {
throw GenericPatchException("Patch::insertColumns: can't insert at this index.");
}
if (_width + 2 > MAX_PATCH_WIDTH) {
throw GenericPatchException("Patch::insertColumns: patch has too many columns.");
}
// Create a backup of the old control vertices
PatchControlArray oldCtrl = _ctrl;
std::size_t oldHeight = _height;
std::size_t oldWidth = _width;
// Resize this patch
setDims(oldWidth + 2, oldHeight);
// Now fill in the control vertex values and interpolate
// before and after the insert point.
for (std::size_t row = 0; row < _height; row++) {
for (std::size_t newCol = 0, oldCol = 0;
newCol < _width && oldCol < oldWidth;
newCol++, oldCol++)
{
// Is this the insert point?
if (oldCol == colIndex) {
// Left column (to be interpolated)
ctrlAt(row, newCol).vertex = float_mid(
oldCtrl[row*oldWidth + oldCol - 1].vertex,
oldCtrl[row*oldWidth + oldCol].vertex
);
ctrlAt(row, newCol).texcoord = float_mid(
oldCtrl[row*oldWidth + oldCol - 1].texcoord,
oldCtrl[row*oldWidth + oldCol].texcoord
);
// Set the newCol counter to the middle column
newCol++;
ctrlAt(row, newCol).vertex = oldCtrl[row*oldWidth + oldCol].vertex;
ctrlAt(row, newCol).texcoord = oldCtrl[row*oldWidth + oldCol].texcoord;
// Set newCol to the right column (to be interpolated)
newCol++;
ctrlAt(row, newCol).vertex = float_mid(
oldCtrl[row*oldWidth + oldCol].vertex,
oldCtrl[row*oldWidth + oldCol + 1].vertex
);
ctrlAt(row, newCol).texcoord = float_mid(