-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMeshEntity.cpp
1821 lines (1690 loc) · 66.6 KB
/
MeshEntity.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 MeshEntity.cpp
* Implements the MeshEntity class.
* @ingroup meshtex-core
*/
/*
* Copyright 2012 Joel Baxter
*
* This file is part of MeshTex.
*
* MeshTex 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.
*
* MeshTex 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 MeshTex. If not, see <http://www.gnu.org/licenses/>.
*/
#include <cmath>
#include "MeshEntity.h"
#include "MeshEntityMessages.h"
#include "ishaders.h"
#include "texturelib.h"
/**
* Size of buffer for composing messages to send to the info callback.
*/
#define INFO_BUFFER_SIZE 1024
/**
* Stop successive refinement of path length estimates when the change in values
* is equal to or less than this tolerance.
*/
#define UNITS_ERROR_BOUND 0.5
/**
* Macro to get ROW_SLICE_TYPE from COL_SLICE_TYPE and vice versa, used in
* code that can operate on either kind of slice. This does mean that the
* numerical values assigned to ROW_SLICE_TYPE and COL_SLICE_TYPE are
* meaningful.
*
* @param sliceType Kind of slice to find the other of, so to speak.
*/
#define OtherSliceType(sliceType) (1 - (sliceType))
/**
* Macro to find the number of control points in a slice, which is equal to
* the number of slices of the other kind.
*
* @param sliceType Kind of slice to measure.
*/
#define SliceSize(sliceType) (_numSlices[OtherSliceType(sliceType)])
/**
* Macro to get rid of negative-zero values.
*
* @param floatnum Number to be sanitized.
*/
#define SanitizeFloat(floatnum) ((floatnum) == -0.0f ? 0.0f : (floatnum))
/**
* For a given slice kind, which texture axis (S or T) normally changes
* along it.
*/
MeshEntity::TextureAxis MeshEntity::_naturalAxis[NUM_SLICE_TYPES] =
{ S_TEX_AXIS, T_TEX_AXIS };
/**
* For a given slice kind, whether Radiant's "natural" scale along a texture
* axis is backwards compared to the progression of the indices of the
* orthogonal slices.
*/
bool MeshEntity::_radiantScaleInverted[NUM_SLICE_TYPES] = { false, true };
/**
* For a given slice kind, whether Radiant's interpretation of tiling along a
* texture axis is backwards compared to the progression of the indices of
* the orthogonal slices.
*/
bool MeshEntity::_radiantTilesInverted[NUM_SLICE_TYPES] = { false, false };
/**
* Message format strings for describing texture mapping on a slice.
*/
const char *MeshEntity::_infoSliceFormatString[NUM_SLICE_TYPES] =
{ INFO_ROW_FORMAT, INFO_COL_FORMAT };
/**
* Message format strings for describing texture mapping on a slice in the
* unusual case where the scale value is infinite.
*/
const char *MeshEntity::_infoSliceInfscaleFormatString[NUM_SLICE_TYPES] =
{ INFO_ROW_INFSCALE_FORMAT, INFO_COL_INFSCALE_FORMAT };
/**
* Message format strings for warning that a scale value is infinite and
* cannot be transferred to the Set S/T Scale dialog.
*/
const char *MeshEntity::_warningSliceInfscaleFormatString[NUM_SLICE_TYPES] =
{ WARNING_ROW_INFSCALE, WARNING_COL_INFSCALE };
/**
* Message format strings for an illegal slice number error.
*/
const char *MeshEntity::_errorBadSliceString[NUM_SLICE_TYPES] =
{ ERROR_BAD_ROW, ERROR_BAD_COL };
/**
* Message format strings for a scale = 0 error.
*/
const char *MeshEntity::_errorSliceZeroscaleString[NUM_SLICE_TYPES] =
{ ERROR_ROW_ZEROSCALE, ERROR_COL_ZEROSCALE };
/**
* Message format strings for a tiles = 0 error.
*/
const char *MeshEntity::_errorSliceZerotilesString[NUM_SLICE_TYPES] =
{ ERROR_ROW_ZEROTILES, ERROR_COL_ZEROTILES };
/**
* Constructor. If the constructor is unable to process the input mesh, then
* the internal valid flag (queryable through IsValid) is set false, and the
* errorReportCallback is invoked.
*
* @param mesh The patch mesh to construct a wrapper for.
* @param infoReportCallback Callback for future informational messages.
* @param warningReportCallback Callback for future warning messages.
* @param errorReportCallback Callback for future error messages.
*/
MeshEntity::MeshEntity(scene::Node& mesh,
const MessageCallback& infoReportCallback,
const MessageCallback& warningReportCallback,
const MessageCallback& errorReportCallback) :
_mesh(mesh),
_infoReportCallback(infoReportCallback),
_warningReportCallback(warningReportCallback),
_errorReportCallback(errorReportCallback)
{
// Get a handle on the control points, for future manipulation.
_meshData = GlobalPatchCreator().Patch_getControlPoints(_mesh);
// Record some useful characteristics of the mesh.
_numSlices[ROW_SLICE_TYPE] = static_cast<int>(_meshData.x());
_numSlices[COL_SLICE_TYPE] = static_cast<int>(_meshData.y());
const char *shaderName = GlobalPatchCreator().Patch_getShader(_mesh);
IShader *shader = GlobalShaderSystem().getShaderForName(shaderName);
qtexture_t *texture = shader->getTexture();
if (texture != NULL)
{
_naturalTexUnits[S_TEX_AXIS] = texture->width / 2.0f;
_naturalTexUnits[T_TEX_AXIS] = texture->height / 2.0f;
}
// We don't need the shader for anything else now.
shader->DecRef();
// Check for valid mesh; bail if not.
if (_numSlices[ROW_SLICE_TYPE] < 3 ||
_numSlices[COL_SLICE_TYPE] < 3 ||
texture == NULL)
{
_valid = false;
_errorReportCallback(ERROR_BAD_MESH);
return;
}
_valid = true;
// Find the worldspace extents of the mesh now... they won't change during
// the lifetime of this object.
UpdatePosMinMax(X_POS_AXIS);
UpdatePosMinMax(Y_POS_AXIS);
UpdatePosMinMax(Z_POS_AXIS);
// We'll calculate the S/T extents lazily.
_texMinMaxDirty[S_TEX_AXIS] = true;
_texMinMaxDirty[T_TEX_AXIS] = true;
}
/**
* Destructor. Note that this only destroys the wrapper object, not the patch
* mesh itself.
*/
MeshEntity::~MeshEntity()
{
}
/**
* Query if the patch mesh is valid, in the characteristics that this wrapper
* class cares about. If not valid then the results of operations on this
* wrapper object are undefined.
*
* @return true if valid, false if not.
*/
bool
MeshEntity::IsValid() const
{
return _valid;
}
/**
* Get information about the patch mesh.
*
* A message string describing general mesh information (number of rows/cols,
* min/max texture coords, extent in worldspace) will be composed and sent to
* the infoReportCallback that was specified when this wrapper object was
* constructed.
*
* Optionally this method can do additional reporting on a specific
* "reference row" and "reference column". If a reference row and/or column
* is specified, then information about the reference slice(s) will be added
* to the information message. If a reference row/col is specified AND a
* corresponding row/col TexInfoCallback is specified, then the scale and
* tiling values for the reference slice will also be passed to the relevant
* callback.
*
* @param refRow Pointer to reference row number; NULL if none.
* @param refCol Pointer to reference column number; NULL if none.
* @param rowTexInfoCallback Pointer to callback for reference row info; NULL
* if none.
* @param colTexInfoCallback Pointer to callback for reference column info; NULL
* if none.
*/
void
MeshEntity::GetInfo(const int *refRow,
const int *refCol,
const TexInfoCallback *rowTexInfoCallback,
const TexInfoCallback *colTexInfoCallback)
{
// Prep a message buffer to compose the response.
char messageBuffer[INFO_BUFFER_SIZE + 1];
messageBuffer[INFO_BUFFER_SIZE] = 0;
size_t bufferOffset = 0;
// Get reference row info if requested; this will be written into the message
// buffer as well as sent to the row callback (if any).
if (refRow != NULL)
{
ReportSliceTexInfo(ROW_SLICE_TYPE, *refRow, _naturalAxis[ROW_SLICE_TYPE],
messageBuffer + bufferOffset,
INFO_BUFFER_SIZE - bufferOffset,
rowTexInfoCallback);
// Move the message buffer pointer along.
bufferOffset = strlen(messageBuffer);
}
// Get reference column info if requested; this will be written into the
// message buffer as well as sent to the column callback (if any).
if (refCol != NULL)
{
ReportSliceTexInfo(COL_SLICE_TYPE, *refCol, _naturalAxis[COL_SLICE_TYPE],
messageBuffer + bufferOffset,
INFO_BUFFER_SIZE - bufferOffset,
colTexInfoCallback);
// Move the message buffer pointer along.
bufferOffset = strlen(messageBuffer);
}
// Make sure we have up-to-date S/T extents.
UpdateTexMinMax(S_TEX_AXIS);
UpdateTexMinMax(T_TEX_AXIS);
// Add general mesh info to the message.
snprintf(messageBuffer + bufferOffset, INFO_BUFFER_SIZE - bufferOffset,
INFO_MESH_FORMAT,
_numSlices[ROW_SLICE_TYPE],
SanitizeFloat(_texMin[S_TEX_AXIS]), SanitizeFloat(_texMax[S_TEX_AXIS]),
_numSlices[COL_SLICE_TYPE],
SanitizeFloat(_texMin[T_TEX_AXIS]), SanitizeFloat(_texMax[T_TEX_AXIS]),
SanitizeFloat(_posMin[X_POS_AXIS]), SanitizeFloat(_posMax[X_POS_AXIS]),
SanitizeFloat(_posMin[Y_POS_AXIS]), SanitizeFloat(_posMax[Y_POS_AXIS]),
SanitizeFloat(_posMin[Z_POS_AXIS]), SanitizeFloat(_posMax[Z_POS_AXIS]));
// Send the response.
_infoReportCallback(messageBuffer);
}
/**
* For each of the specified texture axes, shift the lowest-valued texture
* coordinates off of the mesh until an integral texture coordinate (texture
* boundary) is on the mesh edge.
*
* @param axes The texture axes to align.
*/
void
MeshEntity::MinAlign(TextureAxisSelection axes)
{
// Implement this by applying MinAlignInt to each specified axis.
ProcessForAxes(&MeshEntity::MinAlignInt, axes);
}
/**
* For each of the specified texture axes, shift the highest-valued texture
* coordinates off of the mesh until an integral texture coordinate (texture
* boundary) is on the mesh edge.
*
* @param axes The texture axes to align.
*/
void
MeshEntity::MaxAlign(TextureAxisSelection axes)
{
// Implement this by applying MaxAlignInt to each specified axis.
ProcessForAxes(&MeshEntity::MaxAlignInt, axes);
}
/**
* For each of the specified texture axes, perform either MinMaxAlignStretch
* or MinMaxAlignShrink; the chosen operation will be the one with the least
* absolute change in the value of the texture scale.
*
* @param axes The texture axes to align.
*/
void
MeshEntity::MinMaxAlignAutoScale(TextureAxisSelection axes)
{
// Implement this by applying MinMaxAlignAutoScaleInt to each specified axis.
ProcessForAxes(&MeshEntity::MinMaxAlignAutoScaleInt, axes);
}
/**
* For each of the specified texture axes, align a texture boundary to one
* edge of the mesh, then increase the texture scale to align a texture
* boundary to the other edge of the mesh as well.
*
* @param axes The texture axes to align.
*/
void
MeshEntity::MinMaxAlignStretch(TextureAxisSelection axes)
{
// Implement this by applying MinMaxAlignStretchInt to each specified axis.
ProcessForAxes(&MeshEntity::MinMaxAlignStretchInt, axes);
}
/**
* For each of the specified texture axes, align a texture boundary to one
* edge of the mesh, then decrease the texture scale to align a texture
* boundary to the other edge of the mesh as well.
*
* @param axes The texture axes to align.
*/
void
MeshEntity::MinMaxAlignShrink(TextureAxisSelection axes)
{
// Implement this by applying MinMaxAlignShrinkInt to each specified axis.
ProcessForAxes(&MeshEntity::MinMaxAlignShrinkInt, axes);
}
/**
* Set the texture scaling along the rows or columns of the mesh. This
* affects only the texture axis that is naturally associated with rows (S)
* or columns (T) according to the chosen sliceType.
*
* The scaling may be input either as a multiple of the natural scale that
* Radiant would choose for this texture, or as the number of tiles of the
* texture that should fit on the mesh's row/column.
*
* Among the slices perpendicular to the direction of scaling, an alignment
* slice is used to fix the position of the texture boundary.
*
* A reference slice may optionally be chosen among the slices parallel to
* the scaling direction. If a reference slice is not specified, then the
* texture coordinates are independently determined for each slice. If a
* reference slice is specified, its texture coordinates are calculated first
* and used to affect the other slices. The reference slice's amount of
* texture tiling will be re-used for all other slices; optionally, the
* texture coordinate at each control point within the reference slice can be
* copied to the corresponding control point in every other slice.
*
* @param sliceType Choose to scale along rows or columns.
* @param alignSlice Pointer to alignment slice description; if NULL,
* slice 0 is assumed.
* @param refSlice Pointer to reference slice description,
* including how to use the reference; NULL if no
* reference.
* @param naturalScale true if naturalScaleOrTiles is a factor of the
* Radiant natural scale; false if
* naturalScaleOrTiles is a number of tiles.
* @param naturalScaleOrTiles Scaling determinant, interpreted according to
* the naturalScale parameter.
*/
void
MeshEntity::SetScale(SliceType sliceType,
const SliceDesignation *alignSlice,
const RefSliceDescriptor *refSlice,
bool naturalScale,
float naturalScaleOrTiles)
{
// We're about to make changes!
CreateUndoPoint();
// Check for bad inputs. Also convert from natural scale to raw scale.
if (alignSlice != NULL && !alignSlice->maxSlice)
{
if (alignSlice->index < 0 ||
alignSlice->index >= (int)SliceSize(sliceType))
{
_errorReportCallback(_errorBadSliceString[OtherSliceType(sliceType)]);
return;
}
}
if (refSlice != NULL && !refSlice->designation.maxSlice)
{
if (refSlice->designation.index < 0 ||
refSlice->designation.index >= (int)_numSlices[sliceType])
{
_errorReportCallback(_errorBadSliceString[sliceType]);
return;
}
}
TextureAxis axis = _naturalAxis[sliceType];
float rawScaleOrTiles = naturalScaleOrTiles;
if (naturalScale)
{
// In this case, naturalScaleOrTiles (copied to rawScaleOrTiles) was a
// natural-scale factor.
if (rawScaleOrTiles == 0)
{
_errorReportCallback(_errorSliceZeroscaleString[sliceType]);
return;
}
// If Radiant's internal orientation is backwards, account for that.
if (_radiantScaleInverted[sliceType])
{
rawScaleOrTiles = -rawScaleOrTiles;
}
// Raw scale is the divisor necessary to get texture coordinate from
// worldspace distance, so we can derive that from the "natural" scale.
rawScaleOrTiles *= _naturalTexUnits[axis];
}
else
{
// In this case, naturalScaleOrTiles (copied to rawScaleOrTiles) was a
// tiling amount.
if (rawScaleOrTiles == 0)
{
// XXX We could try to make zero-tiles work ("infinite scale": all
// values for this axis are the same along the slice). Need to sort
// out divide-by-zero dangers down the road.
_errorReportCallback(_errorSliceZerotilesString[sliceType]);
return;
}
// If Radiant's internal orientation is backwards, account for that.
if (_radiantTilesInverted[sliceType])
{
rawScaleOrTiles = -rawScaleOrTiles;
}
}
// Make sure we have a definite number for the alignment slice, and for the
// reference slice if any.
int alignSliceInt =
InternalSliceDesignation(alignSlice, (SliceType)OtherSliceType(sliceType));
RefSliceDescriptorInt descriptor;
RefSliceDescriptorInt *refSliceInt = // will be NULL if no reference
InternalRefSliceDescriptor(refSlice, sliceType, descriptor);
// Generate the surface texture coordinates using the mesh control points
// and the designated scaling/tiling.
AllocatedMatrix<float> surfaceValues(_meshData.x(), _meshData.y());
GenScaledDistanceValues(sliceType, alignSliceInt, refSliceInt,
naturalScale, rawScaleOrTiles,
surfaceValues);
// Derive the control point values necessary to achieve those surface values.
GenControlTexFromSurface(axis, surfaceValues);
// Done!
CommitChanges();
}
/**
* Set the mesh's texture coordinates according to a linear combination of
* factors. This equation can be used to set the texture coordinates at the
* control points themselves, or to directly set the texture coordinates at
* the locations on the mesh surface that correspond to each half-patch
* interval.
*
* An alignment row is used as the zero-point for any calculations of row
* number or of distance along a column surface when processing the equation.
* An alignment column is similarly used. (Note that the number identifying
* the alignment row/column is the real number used to index into the mesh;
* it's not the modified number as affected by the alignment column/row when
* processing the equation. We don't want to be stuck in a chicken-and-egg
* situation.)
*
* Calculations of distance along row/col surface may optionally be affected
* by a designated reference row/col. The reference row/col can be used as a
* source of end-to-end distance only, in which case the proportional spacing
* of the control points within the affected row/col will determine the
* distance value to be used for each control point. Or, the distance value
* for every control point in the reference row/col can be copied to each
* corresponding control point in the other rows/cols.
*
* @param sFactors Factors to determine the S texture coords; NULL if S
* axis unaffected.
* @param tFactors Factors to determine the T texture coords; NULL if T
* axis unaffected.
* @param alignRow Pointer to zero-point row; if NULL, row 0 is assumed.
* @param alignCol Pointer to zero-point column; if NULL, column 0 is
* assumed.
* @param refRow Pointer to reference row description, including how
* to use the reference; NULL if no reference.
* @param refCol Pointer to reference column description, including
* how to use the reference; NULL if no reference.
* @param surfaceValues true if calculations are for S/T values on the mesh
* surface; false if calculations are for S/T values at
* the control points.
*/
void
MeshEntity::GeneralFunction(const GeneralFunctionFactors *sFactors,
const GeneralFunctionFactors *tFactors,
const SliceDesignation *alignRow,
const SliceDesignation *alignCol,
const RefSliceDescriptor *refRow,
const RefSliceDescriptor *refCol,
bool surfaceValues)
{
// We're about to make changes!
CreateUndoPoint();
// Make sure we have a definite number for the alignment slices, and for the
// reference slices if any.
int alignRowInt = InternalSliceDesignation(alignRow, ROW_SLICE_TYPE);
int alignColInt = InternalSliceDesignation(alignRow, COL_SLICE_TYPE);
RefSliceDescriptorInt rowDescriptor;
RefSliceDescriptorInt *refRowInt = // will be NULL if no row reference
InternalRefSliceDescriptor(refRow, ROW_SLICE_TYPE, rowDescriptor);
RefSliceDescriptorInt colDescriptor;
RefSliceDescriptorInt *refColInt = // will be NULL if no column reference
InternalRefSliceDescriptor(refCol, COL_SLICE_TYPE, colDescriptor);
// Get the surface row/col distance values at each half-patch interval, if
// the input factors care about distances.
AllocatedMatrix<float> rowDistances(_meshData.x(), _meshData.y());
AllocatedMatrix<float> colDistances(_meshData.x(), _meshData.y());
if ((sFactors != NULL && sFactors->rowDistance != 0.0f) ||
(tFactors != NULL && tFactors->rowDistance != 0.0f))
{
GenScaledDistanceValues(ROW_SLICE_TYPE,
alignColInt,
refRowInt,
true,
1.0f,
rowDistances);
}
if ((sFactors != NULL && sFactors->colDistance != 0.0f) ||
(tFactors != NULL && tFactors->colDistance != 0.0f))
{
GenScaledDistanceValues(COL_SLICE_TYPE,
alignRowInt,
refColInt,
true,
1.0f,
colDistances);
}
// Modify the S axis if requested.
if (sFactors != NULL)
{
GeneralFunctionInt(*sFactors, S_TEX_AXIS, alignRowInt, alignColInt, surfaceValues,
rowDistances, colDistances);
}
// Modify the T axis if requested.
if (tFactors != NULL)
{
GeneralFunctionInt(*tFactors, T_TEX_AXIS, alignRowInt, alignColInt, surfaceValues,
rowDistances, colDistances);
}
// Done!
CommitChanges();
}
/**
* Update the internally stored information for the min and max extent of the
* mesh on the specified worldspace axis.
*
* @param axis The worldspace axis.
*/
void
MeshEntity::UpdatePosMinMax(PositionAxis axis)
{
// Iterate over all control points to find the min and max values.
_posMin[axis] = _meshData(0, 0).m_vertex[axis];
_posMax[axis] = _posMin[axis];
for (unsigned rowIndex = 0; rowIndex < _numSlices[ROW_SLICE_TYPE]; rowIndex++)
{
for (unsigned colIndex = 0; colIndex < _numSlices[COL_SLICE_TYPE]; colIndex++)
{
float current = _meshData(rowIndex, colIndex).m_vertex[axis];
if (current < _posMin[axis])
{
_posMin[axis] = current;
}
if (current > _posMax[axis])
{
_posMax[axis] = current;
}
}
}
}
/**
* Update the internally stored information for the min and max extent of the
* mesh on the specified texture axis.
*
* @param axis The texture axis.
*/
void
MeshEntity::UpdateTexMinMax(TextureAxis axis)
{
// Bail out if no operations have possibly changed these values.
if (!_texMinMaxDirty[axis])
{
return;
}
// Iterate over all control points to find the min and max values.
_texMin[axis] = _meshData(0, 0).m_texcoord[axis];
_texMax[axis] = _texMin[axis];
for (unsigned rowIndex = 0; rowIndex < _numSlices[ROW_SLICE_TYPE]; rowIndex++)
{
for (unsigned colIndex = 0; colIndex < _numSlices[COL_SLICE_TYPE]; colIndex++)
{
float current = _meshData(rowIndex, colIndex).m_texcoord[axis];
if (current < _texMin[axis])
{
_texMin[axis] = current;
}
if (current > _texMax[axis])
{
_texMax[axis] = current;
}
}
}
// See if the min and max are on texture boundaries.
_texMinAligned[axis] = (floorf(_texMin[axis]) == _texMin[axis]);
_texMaxAligned[axis] = (floorf(_texMax[axis]) == _texMax[axis]);
// Values are good until next relevant operation.
_texMinMaxDirty[axis] = false;
}
/**
* Interface to the Radiant undo buffer; save the current state of the mesh
* to allow rollback to this point by an undo operation.
*/
void
MeshEntity::CreateUndoPoint()
{
GlobalPatchCreator().Patch_undoSave(_mesh);
}
/**
* Commit the changes to the mesh so that they will be reflected in Radiant.
*/
void
MeshEntity::CommitChanges()
{
GlobalPatchCreator().Patch_controlPointsChanged(_mesh);
// Radiant undo-buffer behavior requires this:
CreateUndoPoint();
}
/**
* Convert from SliceDesignation to a slice number. Interpret max slice if
* necessary, and fall back to slice 0 if unspecified.
*
* @param sliceDesignation Pointer to slice description; may be NULL.
* @param sliceType Slice kind (row or column).
*
* @return The slice number.
*/
int
MeshEntity::InternalSliceDesignation(const SliceDesignation *sliceDesignation,
SliceType sliceType)
{
if (sliceDesignation != NULL)
{
// Interpret "max slice" if necessary.
if (sliceDesignation->maxSlice)
{
return _numSlices[sliceType] - 1;
}
else
{
return sliceDesignation->index;
}
}
else
{
// 0 if unspecified.
return 0;
}
}
/**
* Convert from RefSliceDescriptor to RefSliceDescriptorInt. Interpret max
* slice if necessary. Populate specified RefSliceDescriptorInt if input is
* non-NULL and return pointer to it; otherwise return NULL.
*
* @param refSlice Pointer to reference slice description; may be
* NULL.
* @param sliceType Slice kind (row or column).
* @param [out] refSliceInt RefSliceDescriptorInt to populate.
*
* @return NULL if input RefSliceDescriptor is NULL; else, pointer to populated
* RefSliceDescriptorInt.
*/
MeshEntity::RefSliceDescriptorInt *
MeshEntity::InternalRefSliceDescriptor(const RefSliceDescriptor *refSlice,
SliceType sliceType,
RefSliceDescriptorInt& refSliceInt)
{
if (refSlice != NULL)
{
// Preserve totalLengthOnly.
refSliceInt.totalLengthOnly = refSlice->totalLengthOnly;
// Convert slice designator to a slice number.
refSliceInt.index = InternalSliceDesignation(&(refSlice->designation), sliceType);
return &refSliceInt;
}
else
{
// NULL if unspecified.
return NULL;
}
}
/**
* Given a slice and a number of times that its texture should tile along it,
* find the appropriate texture scale. This result is determined by the
* surface length along the slice.
*
* @param sliceType Slice kind (row or column).
* @param slice Slice number, among slices of that kind in mesh.
* @param axis The texture axis of interest.
* @param tiles Number of times the texture tiles.
*
* @return The texture scale corresponding to the tiling amount.
*/
float
MeshEntity::GetSliceTexScale(SliceType sliceType,
int slice,
TextureAxis axis,
float tiles)
{
// XXX Similar to GenScaledDistanceValues; refactor for shared code?
// We're going to be walking patches along the mesh, choosing the patches
// that surround/affect the slice we are interested in. We'll calculate
// the length of the slice's surface across each patch & add those up.
// A SlicePatchContext will contain all the necessary information to
// evaluate our slice's surface length within each patch. Some aspects of
// the SlicePatchContext will vary as we move from patch to patch, but we
// can go ahead and calculate now any stuff that is invariant along the
// slice's direction.
SlicePatchContext context;
context.sliceType = sliceType;
if (slice != 0)
{
// This is the position of the slice within each patch, in the direction
// orthogonal to the slice. Even-numbered slices are at the edge of the
// patch (position 1.0), while odd-numbered slices are in the middle
// (position 0.5).
context.position = 1.0f - ((float)(slice & 0x1) / 2.0f);
}
else
{
// For the first slice, we can't give it the usual treatment for even-
// numbered slices (since there is no patch "before" it), so it gets
// position 0.0 instead.
context.position = 0.0f;
}
// This is the slice of the same kind that defines the 0.0 edge of the
// patch. It will be the next lowest even-numbered slice. (Note the
// integer division here.)
context.edgeSlice[sliceType] = 2 * ((slice - 1) / 2);
// Now it's time to walk the patches.
// We start off with no cumulative distance yet.
float cumulativeDistance = 0.0f;
// By iterating over the number of control points in this slice by
// increments of 2, we'll be walking the slice in patch-sized steps. Since
// we are only interested in the total length, we don't need to check in at
// finer granularities.
for (unsigned halfPatch = 2; halfPatch < SliceSize(sliceType); halfPatch += 2)
{
// Find the slice-of-other-kind that defines the patch edge orthogonal
// to our slice.
context.edgeSlice[OtherSliceType(sliceType)] = 2 * ((halfPatch - 1) / 2);
// Estimate the slice length along the surface of the patch.
float segmentLengthEstimate = EstimateSegmentLength(0.0f, 1.0f, context);
// Recursively refine that estimate until it is good enough, then add it
// to our cumulative distance.
cumulativeDistance += RefineSegmentLength(0.0f, 1.0f, context,
segmentLengthEstimate,
UNITS_ERROR_BOUND);
}
// The scale along this slice is defined as the surface length divided by
// the "natural" number of texture units along that length.
return cumulativeDistance / (tiles * _naturalTexUnits[axis]);
}
/**
* Populate the SliceTexInfo for the indicated slice and texture axis.
*
* @param sliceType Slice kind (row or column).
* @param slice Slice number, among slices of that kind in mesh.
* @param axis The texture axis of interest.
* @param [out] info Information on scale, tiles, and min/max for the
* specified texture axis.
*
* @return true on success, false if slice cannot be processed.
*/
bool
MeshEntity::GetSliceTexInfo(SliceType sliceType,
int slice,
TextureAxis axis,
SliceTexInfo& info)
{
// Bail out now if slice # is bad.
if (slice < 0 ||
slice >= (int)_numSlices[sliceType])
{
_errorReportCallback(_errorBadSliceString[sliceType]);
return false;
}
// Calculate the # of times the texture is tiled along the specified axis
// on this slice, and find the min and max values for that axis.
float texBegin =
MatrixElement(_meshData, sliceType, slice, 0).m_texcoord[axis];
float texEnd =
MatrixElement(_meshData, sliceType, slice, SliceSize(sliceType) - 1).m_texcoord[axis];
info.tiles = texEnd - texBegin;
if (texBegin < texEnd)
{
info.min = texBegin;
info.max = texEnd;
}
else
{
info.min = texEnd;
info.max = texBegin;
}
// Calculate the texture scale along this slice, using the tiling info
// along with the texture size and the length of the slice's surface.
info.scale = GetSliceTexScale(sliceType, slice, axis, info.tiles);
return true;
}
/**
* Take the information from GetSliceTexInfo and sanitize it for reporting.
* Optionally print to a provided message buffer and/or supply data to a
* provided TexInfoCallback.
*
* @param sliceType Slice kind (row or column).
* @param slice Slice number, among slices of that kind in mesh.
* @param axis The texture axis of interest.
* @param messageBuffer Buffer for message data; NULL if none.
* @param messageBufferSize Size of the message buffer.
* @param texInfoCallback Callback for passing texture scale/tiles info;
* NULL if none.
*/
void
MeshEntity::ReportSliceTexInfo(SliceType sliceType,
int slice,
TextureAxis axis,
char *messageBuffer,
unsigned messageBufferSize,
const TexInfoCallback *texInfoCallback)
{
// Fetch the raw info.
SliceTexInfo info;
if (!GetSliceTexInfo(sliceType, slice, axis, info))
{
return;
}
// Account for Radiant-inverted.
if (_radiantScaleInverted[sliceType])
{
info.scale = -info.scale;
}
if (_radiantTilesInverted[sliceType])
{
info.tiles = -info.tiles;
}
// Send texture info to callback if one is provided.
bool infscale = (info.scale > FLT_MAX || info.scale < -FLT_MAX);
if (texInfoCallback != NULL)
{
if (!infscale)
{
(*texInfoCallback)(SanitizeFloat(info.scale), SanitizeFloat(info.tiles));
}
else
{
// "Infinite scale" prevents us from invoking the callback, so
// raise a warning about that.
_warningReportCallback(_warningSliceInfscaleFormatString[sliceType]);
}
}
// Write texture info to buffer if one is provided.
if (messageBuffer != NULL)
{
if (!infscale)
{
snprintf(messageBuffer, messageBufferSize,
_infoSliceFormatString[sliceType], slice,
SanitizeFloat(info.scale), SanitizeFloat(info.tiles),
SanitizeFloat(info.min), SanitizeFloat(info.max));
}
else
{
// Special handling for "infinite scale".
snprintf(messageBuffer, messageBufferSize,
_infoSliceInfscaleFormatString[sliceType], slice,
SanitizeFloat(info.tiles),
SanitizeFloat(info.min), SanitizeFloat(info.max));
}
}
}
/**
* Apply some function with the InternalImpl signature to each of the
* designated texture axes. The undo point and state commit operations
* are handled here for such functions.
*
* @param internalImpl The function to apply.
* @param axes The texture axes to affect.
*/
void
MeshEntity::ProcessForAxes(InternalImpl internalImpl,
TextureAxisSelection axes)
{
// We're about to make changes!
CreateUndoPoint();
// Apply the function to the requested axes.
bool sChanged = false;
bool tChanged = false;
if (axes != T_TEX_AXIS_ONLY)
{
sChanged = (*this.*internalImpl)(S_TEX_AXIS);
}
if (axes != S_TEX_AXIS_ONLY)
{
tChanged = (*this.*internalImpl)(T_TEX_AXIS);
}
// Done! Commit changes if necessary.
if (sChanged || tChanged)
{
CommitChanges();
}
}
/**
* Add an offset to all control point values for the given texture axis.
*
* @param axis The texture axis to affect.
* @param shift The offset to add.
*/
void
MeshEntity::Shift(TextureAxis axis,
float shift)
{
// Iterate over all control points and add the offset.
for (unsigned rowIndex = 0; rowIndex < _numSlices[ROW_SLICE_TYPE]; rowIndex++)
{
for (unsigned colIndex = 0; colIndex < _numSlices[COL_SLICE_TYPE]; colIndex++)
{
_meshData(rowIndex, colIndex).m_texcoord[axis] += shift;
}
}
// This operation might have changed texture min/max.
_texMinMaxDirty[axis] = true;
}
/**
* On the given texture axis, find the distance of all control point values
* from the current minimum value and multiply that distance by the given
* scale factor.
*
* @param axis The texture axis to affect.
* @param scale The scale factor.
*/