-
Notifications
You must be signed in to change notification settings - Fork 32
/
mikktspace.c
1899 lines (1642 loc) · 56.1 KB
/
mikktspace.c
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 mikktspace/mikktspace.c
* \ingroup mikktspace
*/
/**
* Copyright (C) 2011 by Morten S. Mikkelsen
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
*
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
*
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include <assert.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
#include <float.h>
#include <stdlib.h>
#include "mikktspace.h"
#define TFALSE 0
#define TTRUE 1
#ifndef M_PI
#define M_PI 3.1415926535897932384626433832795
#endif
#define INTERNAL_RND_SORT_SEED 39871946
// internal structure
typedef struct {
float x, y, z;
} SVec3;
static tbool veq( const SVec3 v1, const SVec3 v2 )
{
return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z);
}
static SVec3 vadd( const SVec3 v1, const SVec3 v2 )
{
SVec3 vRes;
vRes.x = v1.x + v2.x;
vRes.y = v1.y + v2.y;
vRes.z = v1.z + v2.z;
return vRes;
}
static SVec3 vsub( const SVec3 v1, const SVec3 v2 )
{
SVec3 vRes;
vRes.x = v1.x - v2.x;
vRes.y = v1.y - v2.y;
vRes.z = v1.z - v2.z;
return vRes;
}
static SVec3 vscale(const float fS, const SVec3 v)
{
SVec3 vRes;
vRes.x = fS * v.x;
vRes.y = fS * v.y;
vRes.z = fS * v.z;
return vRes;
}
static float LengthSquared( const SVec3 v )
{
return v.x*v.x + v.y*v.y + v.z*v.z;
}
static float Length( const SVec3 v )
{
return sqrtf(LengthSquared(v));
}
static SVec3 Normalize( const SVec3 v )
{
return vscale(1 / Length(v), v);
}
static float vdot( const SVec3 v1, const SVec3 v2)
{
return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
}
static tbool NotZero(const float fX)
{
// could possibly use FLT_EPSILON instead
return fabsf(fX) > FLT_MIN;
}
static tbool VNotZero(const SVec3 v)
{
// might change this to an epsilon based test
return NotZero(v.x) || NotZero(v.y) || NotZero(v.z);
}
typedef struct {
int iNrFaces;
int * pTriMembers;
} SSubGroup;
typedef struct {
int iNrFaces;
int * pFaceIndices;
int iVertexRepresentitive;
tbool bOrientPreservering;
} SGroup;
//
#define MARK_DEGENERATE 1
#define QUAD_ONE_DEGEN_TRI 2
#define GROUP_WITH_ANY 4
#define ORIENT_PRESERVING 8
typedef struct {
int FaceNeighbors[3];
SGroup * AssignedGroup[3];
// normalized first order face derivatives
SVec3 vOs, vOt;
float fMagS, fMagT; // original magnitudes
// determines if the current and the next triangle are a quad.
int iOrgFaceNumber;
int iFlag, iTSpacesOffs;
unsigned char vert_num[4];
} STriInfo;
typedef struct {
SVec3 vOs;
float fMagS;
SVec3 vOt;
float fMagT;
int iCounter; // this is to average back into quads.
tbool bOrient;
} STSpace;
static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
static int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn);
static tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[],
const int iNrActiveGroups, const int piTriListIn[], const float fThresCos,
const SMikkTSpaceContext * pContext);
static int MakeIndex(const int iFace, const int iVert)
{
assert(iVert>=0 && iVert<4 && iFace>=0);
return (iFace<<2) | (iVert&0x3);
}
static void IndexToData(int * piFace, int * piVert, const int iIndexIn)
{
piVert[0] = iIndexIn&0x3;
piFace[0] = iIndexIn>>2;
}
static STSpace AvgTSpace(const STSpace * pTS0, const STSpace * pTS1)
{
STSpace ts_res;
// this if is important. Due to floating point precision
// averaging when ts0==ts1 will cause a slight difference
// which results in tangent space splits later on
if (pTS0->fMagS==pTS1->fMagS && pTS0->fMagT==pTS1->fMagT &&
veq(pTS0->vOs,pTS1->vOs) && veq(pTS0->vOt, pTS1->vOt))
{
ts_res.fMagS = pTS0->fMagS;
ts_res.fMagT = pTS0->fMagT;
ts_res.vOs = pTS0->vOs;
ts_res.vOt = pTS0->vOt;
}
else
{
ts_res.fMagS = 0.5f*(pTS0->fMagS+pTS1->fMagS);
ts_res.fMagT = 0.5f*(pTS0->fMagT+pTS1->fMagT);
ts_res.vOs = vadd(pTS0->vOs,pTS1->vOs);
ts_res.vOt = vadd(pTS0->vOt,pTS1->vOt);
if ( VNotZero(ts_res.vOs) ) ts_res.vOs = Normalize(ts_res.vOs);
if ( VNotZero(ts_res.vOt) ) ts_res.vOt = Normalize(ts_res.vOt);
}
return ts_res;
}
static SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index);
static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index);
static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index);
// degen triangles
static void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris);
static void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris);
tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext)
{
return genTangSpace(pContext, 180.0f);
}
tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold)
{
// count nr_triangles
int * piTriListIn = NULL, * piGroupTrianglesBuffer = NULL;
STriInfo * pTriInfos = NULL;
SGroup * pGroups = NULL;
STSpace * psTspace = NULL;
int iNrTrianglesIn = 0, f=0, t=0, i=0;
int iNrTSPaces = 0, iTotTris = 0, iDegenTriangles = 0, iNrMaxGroups = 0;
int iNrActiveGroups = 0, index = 0;
const int iNrFaces = pContext->m_pInterface->m_getNumFaces(pContext);
tbool bRes = TFALSE;
const float fThresCos = (float) cos((fAngularThreshold*(float)M_PI)/180.0f);
// verify all call-backs have been set
if ( pContext->m_pInterface->m_getNumFaces==NULL ||
pContext->m_pInterface->m_getNumVerticesOfFace==NULL ||
pContext->m_pInterface->m_getPosition==NULL ||
pContext->m_pInterface->m_getNormal==NULL ||
pContext->m_pInterface->m_getTexCoord==NULL )
return TFALSE;
// count triangles on supported faces
for (f=0; f<iNrFaces; f++)
{
const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);
if (verts==3) ++iNrTrianglesIn;
else if (verts==4) iNrTrianglesIn += 2;
}
if (iNrTrianglesIn<=0) return TFALSE;
// allocate memory for an index list
piTriListIn = (int *) malloc(sizeof(int)*3*iNrTrianglesIn);
pTriInfos = (STriInfo *) malloc(sizeof(STriInfo)*iNrTrianglesIn);
if (piTriListIn==NULL || pTriInfos==NULL)
{
if (piTriListIn!=NULL) free(piTriListIn);
if (pTriInfos!=NULL) free(pTriInfos);
return TFALSE;
}
// make an initial triangle --> face index list
iNrTSPaces = GenerateInitialVerticesIndexList(pTriInfos, piTriListIn, pContext, iNrTrianglesIn);
// make a welded index list of identical positions and attributes (pos, norm, texc)
//printf("gen welded index list begin\n");
GenerateSharedVerticesIndexList(piTriListIn, pContext, iNrTrianglesIn);
//printf("gen welded index list end\n");
// Mark all degenerate triangles
iTotTris = iNrTrianglesIn;
iDegenTriangles = 0;
for (t=0; t<iTotTris; t++)
{
const int i0 = piTriListIn[t*3+0];
const int i1 = piTriListIn[t*3+1];
const int i2 = piTriListIn[t*3+2];
const SVec3 p0 = GetPosition(pContext, i0);
const SVec3 p1 = GetPosition(pContext, i1);
const SVec3 p2 = GetPosition(pContext, i2);
if (veq(p0,p1) || veq(p0,p2) || veq(p1,p2)) // degenerate
{
pTriInfos[t].iFlag |= MARK_DEGENERATE;
++iDegenTriangles;
}
}
iNrTrianglesIn = iTotTris - iDegenTriangles;
// mark all triangle pairs that belong to a quad with only one
// good triangle. These need special treatment in DegenEpilogue().
// Additionally, move all good triangles to the start of
// pTriInfos[] and piTriListIn[] without changing order and
// put the degenerate triangles last.
DegenPrologue(pTriInfos, piTriListIn, iNrTrianglesIn, iTotTris);
// evaluate triangle level attributes and neighbor list
//printf("gen neighbors list begin\n");
InitTriInfo(pTriInfos, piTriListIn, pContext, iNrTrianglesIn);
//printf("gen neighbors list end\n");
// based on the 4 rules, identify groups based on connectivity
iNrMaxGroups = iNrTrianglesIn*3;
pGroups = (SGroup *) malloc(sizeof(SGroup)*iNrMaxGroups);
piGroupTrianglesBuffer = (int *) malloc(sizeof(int)*iNrTrianglesIn*3);
if (pGroups==NULL || piGroupTrianglesBuffer==NULL)
{
if (pGroups!=NULL) free(pGroups);
if (piGroupTrianglesBuffer!=NULL) free(piGroupTrianglesBuffer);
free(piTriListIn);
free(pTriInfos);
return TFALSE;
}
//printf("gen 4rule groups begin\n");
iNrActiveGroups =
Build4RuleGroups(pTriInfos, pGroups, piGroupTrianglesBuffer, piTriListIn, iNrTrianglesIn);
//printf("gen 4rule groups end\n");
//
psTspace = (STSpace *) malloc(sizeof(STSpace)*iNrTSPaces);
if (psTspace==NULL)
{
free(piTriListIn);
free(pTriInfos);
free(pGroups);
free(piGroupTrianglesBuffer);
return TFALSE;
}
memset(psTspace, 0, sizeof(STSpace)*iNrTSPaces);
for (t=0; t<iNrTSPaces; t++)
{
psTspace[t].vOs.x=1.0f; psTspace[t].vOs.y=0.0f; psTspace[t].vOs.z=0.0f; psTspace[t].fMagS = 1.0f;
psTspace[t].vOt.x=0.0f; psTspace[t].vOt.y=1.0f; psTspace[t].vOt.z=0.0f; psTspace[t].fMagT = 1.0f;
}
// make tspaces, each group is split up into subgroups if necessary
// based on fAngularThreshold. Finally a tangent space is made for
// every resulting subgroup
//printf("gen tspaces begin\n");
bRes = GenerateTSpaces(psTspace, pTriInfos, pGroups, iNrActiveGroups, piTriListIn, fThresCos, pContext);
//printf("gen tspaces end\n");
// clean up
free(pGroups);
free(piGroupTrianglesBuffer);
if (!bRes) // if an allocation in GenerateTSpaces() failed
{
// clean up and return false
free(pTriInfos); free(piTriListIn); free(psTspace);
return TFALSE;
}
// degenerate quads with one good triangle will be fixed by copying a space from
// the good triangle to the coinciding vertex.
// all other degenerate triangles will just copy a space from any good triangle
// with the same welded index in piTriListIn[].
DegenEpilogue(psTspace, pTriInfos, piTriListIn, pContext, iNrTrianglesIn, iTotTris);
free(pTriInfos); free(piTriListIn);
index = 0;
for (f=0; f<iNrFaces; f++)
{
const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);
if (verts!=3 && verts!=4) continue;
// I've decided to let degenerate triangles and group-with-anythings
// vary between left/right hand coordinate systems at the vertices.
// All healthy triangles on the other hand are built to always be either or.
/*// force the coordinate system orientation to be uniform for every face.
// (this is already the case for good triangles but not for
// degenerate ones and those with bGroupWithAnything==true)
bool bOrient = psTspace[index].bOrient;
if (psTspace[index].iCounter == 0) // tspace was not derived from a group
{
// look for a space created in GenerateTSpaces() by iCounter>0
bool bNotFound = true;
int i=1;
while (i<verts && bNotFound)
{
if (psTspace[index+i].iCounter > 0) bNotFound=false;
else ++i;
}
if (!bNotFound) bOrient = psTspace[index+i].bOrient;
}*/
// set data
for (i=0; i<verts; i++)
{
const STSpace * pTSpace = &psTspace[index];
float tang[] = {pTSpace->vOs.x, pTSpace->vOs.y, pTSpace->vOs.z};
float bitang[] = {pTSpace->vOt.x, pTSpace->vOt.y, pTSpace->vOt.z};
if (pContext->m_pInterface->m_setTSpace!=NULL)
pContext->m_pInterface->m_setTSpace(pContext, tang, bitang, pTSpace->fMagS, pTSpace->fMagT, pTSpace->bOrient, f, i);
if (pContext->m_pInterface->m_setTSpaceBasic!=NULL)
pContext->m_pInterface->m_setTSpaceBasic(pContext, tang, pTSpace->bOrient==TTRUE ? 1.0f : (-1.0f), f, i);
++index;
}
}
free(psTspace);
return TTRUE;
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
typedef struct {
float vert[3];
int index;
} STmpVert;
static const int g_iCells = 2048;
#ifdef _MSC_VER
# define NOINLINE __declspec(noinline)
#else
# define NOINLINE __attribute__ ((noinline))
#endif
// it is IMPORTANT that this function is called to evaluate the hash since
// inlining could potentially reorder instructions and generate different
// results for the same effective input value fVal.
static NOINLINE int FindGridCell(const float fMin, const float fMax, const float fVal)
{
const float fIndex = g_iCells * ((fVal-fMin)/(fMax-fMin));
const int iIndex = (int)fIndex;
return iIndex < g_iCells ? (iIndex >= 0 ? iIndex : 0) : (g_iCells - 1);
}
static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in);
static void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries);
static void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
static void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
{
// Generate bounding box
int * piHashTable=NULL, * piHashCount=NULL, * piHashOffsets=NULL, * piHashCount2=NULL;
STmpVert * pTmpVert = NULL;
int i=0, iChannel=0, k=0, e=0;
int iMaxCount=0;
SVec3 vMin = GetPosition(pContext, 0), vMax = vMin, vDim;
float fMin, fMax;
for (i=1; i<(iNrTrianglesIn*3); i++)
{
const int index = piTriList_in_and_out[i];
const SVec3 vP = GetPosition(pContext, index);
if (vMin.x > vP.x) vMin.x = vP.x;
else if (vMax.x < vP.x) vMax.x = vP.x;
if (vMin.y > vP.y) vMin.y = vP.y;
else if (vMax.y < vP.y) vMax.y = vP.y;
if (vMin.z > vP.z) vMin.z = vP.z;
else if (vMax.z < vP.z) vMax.z = vP.z;
}
vDim = vsub(vMax,vMin);
iChannel = 0;
fMin = vMin.x; fMax=vMax.x;
if (vDim.y>vDim.x && vDim.y>vDim.z)
{
iChannel=1;
fMin = vMin.y;
fMax = vMax.y;
}
else if (vDim.z>vDim.x)
{
iChannel=2;
fMin = vMin.z;
fMax = vMax.z;
}
// make allocations
piHashTable = (int *) malloc(sizeof(int)*iNrTrianglesIn*3);
piHashCount = (int *) malloc(sizeof(int)*g_iCells);
piHashOffsets = (int *) malloc(sizeof(int)*g_iCells);
piHashCount2 = (int *) malloc(sizeof(int)*g_iCells);
if (piHashTable==NULL || piHashCount==NULL || piHashOffsets==NULL || piHashCount2==NULL)
{
if (piHashTable!=NULL) free(piHashTable);
if (piHashCount!=NULL) free(piHashCount);
if (piHashOffsets!=NULL) free(piHashOffsets);
if (piHashCount2!=NULL) free(piHashCount2);
GenerateSharedVerticesIndexListSlow(piTriList_in_and_out, pContext, iNrTrianglesIn);
return;
}
memset(piHashCount, 0, sizeof(int)*g_iCells);
memset(piHashCount2, 0, sizeof(int)*g_iCells);
// count amount of elements in each cell unit
for (i=0; i<(iNrTrianglesIn*3); i++)
{
const int index = piTriList_in_and_out[i];
const SVec3 vP = GetPosition(pContext, index);
const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z);
const int iCell = FindGridCell(fMin, fMax, fVal);
++piHashCount[iCell];
}
// evaluate start index of each cell.
piHashOffsets[0]=0;
for (k=1; k<g_iCells; k++)
piHashOffsets[k]=piHashOffsets[k-1]+piHashCount[k-1];
// insert vertices
for (i=0; i<(iNrTrianglesIn*3); i++)
{
const int index = piTriList_in_and_out[i];
const SVec3 vP = GetPosition(pContext, index);
const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z);
const int iCell = FindGridCell(fMin, fMax, fVal);
int * pTable = NULL;
assert(piHashCount2[iCell]<piHashCount[iCell]);
pTable = &piHashTable[piHashOffsets[iCell]];
pTable[piHashCount2[iCell]] = i; // vertex i has been inserted.
++piHashCount2[iCell];
}
for (k=0; k<g_iCells; k++)
assert(piHashCount2[k] == piHashCount[k]); // verify the count
free(piHashCount2);
// find maximum amount of entries in any hash entry
iMaxCount = piHashCount[0];
for (k=1; k<g_iCells; k++)
if (iMaxCount<piHashCount[k])
iMaxCount=piHashCount[k];
pTmpVert = (STmpVert *) malloc(sizeof(STmpVert)*iMaxCount);
// complete the merge
for (k=0; k<g_iCells; k++)
{
// extract table of cell k and amount of entries in it
int * pTable = &piHashTable[piHashOffsets[k]];
const int iEntries = piHashCount[k];
if (iEntries < 2) continue;
if (pTmpVert!=NULL)
{
for (e=0; e<iEntries; e++)
{
int i = pTable[e];
const SVec3 vP = GetPosition(pContext, piTriList_in_and_out[i]);
pTmpVert[e].vert[0] = vP.x; pTmpVert[e].vert[1] = vP.y;
pTmpVert[e].vert[2] = vP.z; pTmpVert[e].index = i;
}
MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, 0, iEntries-1);
}
else
MergeVertsSlow(piTriList_in_and_out, pContext, pTable, iEntries);
}
if (pTmpVert!=NULL) { free(pTmpVert); }
free(piHashTable);
free(piHashCount);
free(piHashOffsets);
}
static void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in)
{
// make bbox
int c=0, l=0, channel=0;
float fvMin[3], fvMax[3];
float dx=0, dy=0, dz=0, fSep=0;
for (c=0; c<3; c++)
{ fvMin[c]=pTmpVert[iL_in].vert[c]; fvMax[c]=fvMin[c]; }
for (l=(iL_in+1); l<=iR_in; l++) {
for (c=0; c<3; c++) {
if (fvMin[c]>pTmpVert[l].vert[c]) fvMin[c]=pTmpVert[l].vert[c];
if (fvMax[c]<pTmpVert[l].vert[c]) fvMax[c]=pTmpVert[l].vert[c];
}
}
dx = fvMax[0]-fvMin[0];
dy = fvMax[1]-fvMin[1];
dz = fvMax[2]-fvMin[2];
channel = 0;
if (dy>dx && dy>dz) channel=1;
else if (dz>dx) channel=2;
fSep = 0.5f*(fvMax[channel]+fvMin[channel]);
// stop if all vertices are NaNs
if (!isfinite(fSep))
return;
// terminate recursion when the separation/average value
// is no longer strictly between fMin and fMax values.
if (fSep>=fvMax[channel] || fSep<=fvMin[channel])
{
// complete the weld
for (l=iL_in; l<=iR_in; l++)
{
int i = pTmpVert[l].index;
const int index = piTriList_in_and_out[i];
const SVec3 vP = GetPosition(pContext, index);
const SVec3 vN = GetNormal(pContext, index);
const SVec3 vT = GetTexCoord(pContext, index);
tbool bNotFound = TTRUE;
int l2=iL_in, i2rec=-1;
while (l2<l && bNotFound)
{
const int i2 = pTmpVert[l2].index;
const int index2 = piTriList_in_and_out[i2];
const SVec3 vP2 = GetPosition(pContext, index2);
const SVec3 vN2 = GetNormal(pContext, index2);
const SVec3 vT2 = GetTexCoord(pContext, index2);
i2rec=i2;
//if (vP==vP2 && vN==vN2 && vT==vT2)
if (vP.x==vP2.x && vP.y==vP2.y && vP.z==vP2.z &&
vN.x==vN2.x && vN.y==vN2.y && vN.z==vN2.z &&
vT.x==vT2.x && vT.y==vT2.y && vT.z==vT2.z)
bNotFound = TFALSE;
else
++l2;
}
// merge if previously found
if (!bNotFound)
piTriList_in_and_out[i] = piTriList_in_and_out[i2rec];
}
}
else
{
int iL=iL_in, iR=iR_in;
assert((iR_in-iL_in)>0); // at least 2 entries
// separate (by fSep) all points between iL_in and iR_in in pTmpVert[]
while (iL < iR)
{
tbool bReadyLeftSwap = TFALSE, bReadyRightSwap = TFALSE;
while ((!bReadyLeftSwap) && iL<iR)
{
assert(iL>=iL_in && iL<=iR_in);
bReadyLeftSwap = !(pTmpVert[iL].vert[channel]<fSep);
if (!bReadyLeftSwap) ++iL;
}
while ((!bReadyRightSwap) && iL<iR)
{
assert(iR>=iL_in && iR<=iR_in);
bReadyRightSwap = pTmpVert[iR].vert[channel]<fSep;
if (!bReadyRightSwap) --iR;
}
assert( (iL<iR) || !(bReadyLeftSwap && bReadyRightSwap) );
if (bReadyLeftSwap && bReadyRightSwap)
{
const STmpVert sTmp = pTmpVert[iL];
assert(iL<iR);
pTmpVert[iL] = pTmpVert[iR];
pTmpVert[iR] = sTmp;
++iL; --iR;
}
}
assert(iL==(iR+1) || (iL==iR));
if (iL==iR)
{
const tbool bReadyRightSwap = pTmpVert[iR].vert[channel]<fSep;
if (bReadyRightSwap) ++iL;
else --iR;
}
// only need to weld when there is more than 1 instance of the (x,y,z)
if (iL_in < iR)
MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, iL_in, iR); // weld all left of fSep
if (iL < iR_in)
MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, iL, iR_in); // weld all right of (or equal to) fSep
}
}
static void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries)
{
// this can be optimized further using a tree structure or more hashing.
int e=0;
for (e=0; e<iEntries; e++)
{
int i = pTable[e];
const int index = piTriList_in_and_out[i];
const SVec3 vP = GetPosition(pContext, index);
const SVec3 vN = GetNormal(pContext, index);
const SVec3 vT = GetTexCoord(pContext, index);
tbool bNotFound = TTRUE;
int e2=0, i2rec=-1;
while (e2<e && bNotFound)
{
const int i2 = pTable[e2];
const int index2 = piTriList_in_and_out[i2];
const SVec3 vP2 = GetPosition(pContext, index2);
const SVec3 vN2 = GetNormal(pContext, index2);
const SVec3 vT2 = GetTexCoord(pContext, index2);
i2rec = i2;
if (veq(vP,vP2) && veq(vN,vN2) && veq(vT,vT2))
bNotFound = TFALSE;
else
++e2;
}
// merge if previously found
if (!bNotFound)
piTriList_in_and_out[i] = piTriList_in_and_out[i2rec];
}
}
static void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
{
int iNumUniqueVerts = 0, t=0, i=0;
for (t=0; t<iNrTrianglesIn; t++)
{
for (i=0; i<3; i++)
{
const int offs = t*3 + i;
const int index = piTriList_in_and_out[offs];
const SVec3 vP = GetPosition(pContext, index);
const SVec3 vN = GetNormal(pContext, index);
const SVec3 vT = GetTexCoord(pContext, index);
tbool bFound = TFALSE;
int t2=0, index2rec=-1;
while (!bFound && t2<=t)
{
int j=0;
while (!bFound && j<3)
{
const int index2 = piTriList_in_and_out[t2*3 + j];
const SVec3 vP2 = GetPosition(pContext, index2);
const SVec3 vN2 = GetNormal(pContext, index2);
const SVec3 vT2 = GetTexCoord(pContext, index2);
if (veq(vP,vP2) && veq(vN,vN2) && veq(vT,vT2))
bFound = TTRUE;
else
++j;
}
if (!bFound) ++t2;
}
assert(bFound);
// if we found our own
if (index2rec == index) { ++iNumUniqueVerts; }
piTriList_in_and_out[offs] = index2rec;
}
}
}
static int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
{
int iTSpacesOffs = 0, f=0, t=0;
int iDstTriIndex = 0;
for (f=0; f<pContext->m_pInterface->m_getNumFaces(pContext); f++)
{
const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);
if (verts!=3 && verts!=4) continue;
pTriInfos[iDstTriIndex].iOrgFaceNumber = f;
pTriInfos[iDstTriIndex].iTSpacesOffs = iTSpacesOffs;
if (verts==3)
{
unsigned char * pVerts = pTriInfos[iDstTriIndex].vert_num;
pVerts[0]=0; pVerts[1]=1; pVerts[2]=2;
piTriList_out[iDstTriIndex*3+0] = MakeIndex(f, 0);
piTriList_out[iDstTriIndex*3+1] = MakeIndex(f, 1);
piTriList_out[iDstTriIndex*3+2] = MakeIndex(f, 2);
++iDstTriIndex; // next
}
else
{
{
pTriInfos[iDstTriIndex+1].iOrgFaceNumber = f;
pTriInfos[iDstTriIndex+1].iTSpacesOffs = iTSpacesOffs;
}
{
// need an order independent way to evaluate
// tspace on quads. This is done by splitting
// along the shortest diagonal.
const int i0 = MakeIndex(f, 0);
const int i1 = MakeIndex(f, 1);
const int i2 = MakeIndex(f, 2);
const int i3 = MakeIndex(f, 3);
const SVec3 T0 = GetTexCoord(pContext, i0);
const SVec3 T1 = GetTexCoord(pContext, i1);
const SVec3 T2 = GetTexCoord(pContext, i2);
const SVec3 T3 = GetTexCoord(pContext, i3);
const float distSQ_02 = LengthSquared(vsub(T2,T0));
const float distSQ_13 = LengthSquared(vsub(T3,T1));
tbool bQuadDiagIs_02;
if (distSQ_02<distSQ_13)
bQuadDiagIs_02 = TTRUE;
else if (distSQ_13<distSQ_02)
bQuadDiagIs_02 = TFALSE;
else
{
const SVec3 P0 = GetPosition(pContext, i0);
const SVec3 P1 = GetPosition(pContext, i1);
const SVec3 P2 = GetPosition(pContext, i2);
const SVec3 P3 = GetPosition(pContext, i3);
const float distSQ_02 = LengthSquared(vsub(P2,P0));
const float distSQ_13 = LengthSquared(vsub(P3,P1));
bQuadDiagIs_02 = distSQ_13<distSQ_02 ? TFALSE : TTRUE;
}
if (bQuadDiagIs_02)
{
{
unsigned char * pVerts_A = pTriInfos[iDstTriIndex].vert_num;
pVerts_A[0]=0; pVerts_A[1]=1; pVerts_A[2]=2;
}
piTriList_out[iDstTriIndex*3+0] = i0;
piTriList_out[iDstTriIndex*3+1] = i1;
piTriList_out[iDstTriIndex*3+2] = i2;
++iDstTriIndex; // next
{
unsigned char * pVerts_B = pTriInfos[iDstTriIndex].vert_num;
pVerts_B[0]=0; pVerts_B[1]=2; pVerts_B[2]=3;
}
piTriList_out[iDstTriIndex*3+0] = i0;
piTriList_out[iDstTriIndex*3+1] = i2;
piTriList_out[iDstTriIndex*3+2] = i3;
++iDstTriIndex; // next
}
else
{
{
unsigned char * pVerts_A = pTriInfos[iDstTriIndex].vert_num;
pVerts_A[0]=0; pVerts_A[1]=1; pVerts_A[2]=3;
}
piTriList_out[iDstTriIndex*3+0] = i0;
piTriList_out[iDstTriIndex*3+1] = i1;
piTriList_out[iDstTriIndex*3+2] = i3;
++iDstTriIndex; // next
{
unsigned char * pVerts_B = pTriInfos[iDstTriIndex].vert_num;
pVerts_B[0]=1; pVerts_B[1]=2; pVerts_B[2]=3;
}
piTriList_out[iDstTriIndex*3+0] = i1;
piTriList_out[iDstTriIndex*3+1] = i2;
piTriList_out[iDstTriIndex*3+2] = i3;
++iDstTriIndex; // next
}
}
}
iTSpacesOffs += verts;
assert(iDstTriIndex<=iNrTrianglesIn);
}
for (t=0; t<iNrTrianglesIn; t++)
pTriInfos[t].iFlag = 0;
// return total amount of tspaces
return iTSpacesOffs;
}
static SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index)
{
int iF, iI;
SVec3 res; float pos[3];
IndexToData(&iF, &iI, index);
pContext->m_pInterface->m_getPosition(pContext, pos, iF, iI);
res.x=pos[0]; res.y=pos[1]; res.z=pos[2];
return res;
}
static SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index)
{
int iF, iI;
SVec3 res; float norm[3];
IndexToData(&iF, &iI, index);
pContext->m_pInterface->m_getNormal(pContext, norm, iF, iI);
res.x=norm[0]; res.y=norm[1]; res.z=norm[2];
return res;
}
static SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index)
{
int iF, iI;
SVec3 res; float texc[2];
IndexToData(&iF, &iI, index);
pContext->m_pInterface->m_getTexCoord(pContext, texc, iF, iI);
res.x=texc[0]; res.y=texc[1]; res.z=1.0f;
return res;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////
typedef union {
struct
{
int i0, i1, f;
};
int array[3];
} SEdge;
static void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn);
static void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn);
// returns the texture area times 2
static float CalcTexArea(const SMikkTSpaceContext * pContext, const int indices[])
{
const SVec3 t1 = GetTexCoord(pContext, indices[0]);
const SVec3 t2 = GetTexCoord(pContext, indices[1]);
const SVec3 t3 = GetTexCoord(pContext, indices[2]);
const float t21x = t2.x-t1.x;
const float t21y = t2.y-t1.y;
const float t31x = t3.x-t1.x;
const float t31y = t3.y-t1.y;
const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x;
return fSignedAreaSTx2<0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2;
}
static void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
{
int f=0, i=0, t=0;
// pTriInfos[f].iFlag is cleared in GenerateInitialVerticesIndexList() which is called before this function.
// generate neighbor info list
for (f=0; f<iNrTrianglesIn; f++)
for (i=0; i<3; i++)
{
pTriInfos[f].FaceNeighbors[i] = -1;
pTriInfos[f].AssignedGroup[i] = NULL;
pTriInfos[f].vOs.x=0.0f; pTriInfos[f].vOs.y=0.0f; pTriInfos[f].vOs.z=0.0f;
pTriInfos[f].vOt.x=0.0f; pTriInfos[f].vOt.y=0.0f; pTriInfos[f].vOt.z=0.0f;
pTriInfos[f].fMagS = 0;
pTriInfos[f].fMagT = 0;
// assumed bad
pTriInfos[f].iFlag |= GROUP_WITH_ANY;
}
// evaluate first order derivatives
for (f=0; f<iNrTrianglesIn; f++)
{
// initial values
const SVec3 v1 = GetPosition(pContext, piTriListIn[f*3+0]);
const SVec3 v2 = GetPosition(pContext, piTriListIn[f*3+1]);
const SVec3 v3 = GetPosition(pContext, piTriListIn[f*3+2]);
const SVec3 t1 = GetTexCoord(pContext, piTriListIn[f*3+0]);
const SVec3 t2 = GetTexCoord(pContext, piTriListIn[f*3+1]);
const SVec3 t3 = GetTexCoord(pContext, piTriListIn[f*3+2]);
const float t21x = t2.x-t1.x;
const float t21y = t2.y-t1.y;
const float t31x = t3.x-t1.x;
const float t31y = t3.y-t1.y;
const SVec3 d1 = vsub(v2,v1);
const SVec3 d2 = vsub(v3,v1);
const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x;
//assert(fSignedAreaSTx2!=0);
SVec3 vOs = vsub(vscale(t31y,d1), vscale(t21y,d2)); // eq 18
SVec3 vOt = vadd(vscale(-t31x,d1), vscale(t21x,d2)); // eq 19
pTriInfos[f].iFlag |= (fSignedAreaSTx2>0 ? ORIENT_PRESERVING : 0);
if ( NotZero(fSignedAreaSTx2) )
{
const float fAbsArea = fabsf(fSignedAreaSTx2);
const float fLenOs = Length(vOs);
const float fLenOt = Length(vOt);
const float fS = (pTriInfos[f].iFlag&ORIENT_PRESERVING)==0 ? (-1.0f) : 1.0f;
if ( NotZero(fLenOs) ) pTriInfos[f].vOs = vscale(fS/fLenOs, vOs);
if ( NotZero(fLenOt) ) pTriInfos[f].vOt = vscale(fS/fLenOt, vOt);
// evaluate magnitudes prior to normalization of vOs and vOt
pTriInfos[f].fMagS = fLenOs / fAbsArea;