Fix from sparky for compile problem with older GCC
[blender.git] / intern / mikktspace / mikktspace.c
1 /**
2  *  Copyright (C) 2011 by Morten S. Mikkelsen
3  *
4  *  This software is provided 'as-is', without any express or implied
5  *  warranty.  In no event will the authors be held liable for any damages
6  *  arising from the use of this software.
7  *
8  *  Permission is granted to anyone to use this software for any purpose,
9  *  including commercial applications, and to alter it and redistribute it
10  *  freely, subject to the following restrictions:
11  *
12  *  1. The origin of this software must not be misrepresented; you must not
13  *     claim that you wrote the original software. If you use this software
14  *     in a product, an acknowledgment in the product documentation would be
15  *     appreciated but is not required.
16  *  2. Altered source versions must be plainly marked as such, and must not be
17  *     misrepresented as being the original software.
18  *  3. This notice may not be removed or altered from any source distribution.
19  */
20
21 #include <assert.h>
22 #include <stdio.h>
23 #include <math.h>
24 #include <string.h>
25 #include <float.h>
26 #include <malloc.h>
27 #include "mikktspace.h"
28
29 #define TFALSE          0
30 #define TTRUE           1
31
32 #ifndef M_PI
33 #define M_PI    3.1415926535897932384626433832795
34 #endif
35
36 #define INTERNAL_RND_SORT_SEED          39871946
37
38 // internal structure
39 typedef struct
40 {
41         float x, y, z;
42 } SVec3;
43
44 static tbool                    veq( const SVec3 v1, const SVec3 v2 )
45 {
46         return (v1.x == v2.x) && (v1.y == v2.y) && (v1.z == v2.z);
47 }
48
49 static const SVec3              vadd( const SVec3 v1, const SVec3 v2 )
50 {
51         SVec3 vRes;
52
53         vRes.x = v1.x + v2.x;
54         vRes.y = v1.y + v2.y;
55         vRes.z = v1.z + v2.z;
56
57         return vRes;
58 }
59
60
61 static const SVec3              vsub( const SVec3 v1, const SVec3 v2 )
62 {
63         SVec3 vRes;
64
65         vRes.x = v1.x - v2.x;
66         vRes.y = v1.y - v2.y;
67         vRes.z = v1.z - v2.z;
68
69         return vRes;
70 }
71
72 static const SVec3              vscale(const float fS, const SVec3 v)
73 {
74         SVec3 vRes;
75
76         vRes.x = fS * v.x;
77         vRes.y = fS * v.y;
78         vRes.z = fS * v.z;
79
80         return vRes;
81 }
82
83 static float                    LengthSquared( const SVec3 v )
84 {
85         return v.x*v.x + v.y*v.y + v.z*v.z;
86 }
87
88 static float                    Length( const SVec3 v )
89 {
90         return sqrtf(LengthSquared(v));
91 }
92
93 static const SVec3              Normalize( const SVec3 v )
94 {
95         return vscale(1 / Length(v), v);
96 }
97
98 static const float              vdot( const SVec3 v1, const SVec3 v2)
99 {
100         return v1.x*v2.x + v1.y*v2.y + v1.z*v2.z;
101 }
102
103
104 static tbool NotZero(const float fX)
105 {
106         // could possibly use FLT_EPSILON instead
107         return fabsf(fX) > FLT_MIN;
108 }
109
110 static tbool VNotZero(const SVec3 v)
111 {
112         // might change this to an epsilon based test
113         return NotZero(v.x) || NotZero(v.y) || NotZero(v.z);
114 }
115
116
117
118 typedef struct
119 {
120         int iNrFaces;
121         int * pTriMembers;
122 } SSubGroup;
123
124 typedef struct
125 {
126         int iNrFaces;
127         int * pFaceIndices;
128         int iVertexRepresentitive;
129         tbool bOrientPreservering;
130 } SGroup;
131
132 // 
133 #define MARK_DEGENERATE                         1
134 #define QUAD_ONE_DEGEN_TRI                      2
135 #define GROUP_WITH_ANY                          4
136 #define ORIENT_PRESERVING                       8
137
138
139
140 typedef struct
141 {
142         int FaceNeighbors[3];
143         SGroup * AssignedGroup[3];
144         
145         // normalized first order face derivatives
146         SVec3 vOs, vOt;
147         float fMagS, fMagT;     // original magnitudes
148
149         // determines if the current and the next triangle are a quad.
150         int iOrgFaceNumber;
151         int iFlag, iTSpacesOffs;
152         unsigned char vert_num[4];
153 } STriInfo;
154
155 typedef struct
156 {
157         SVec3 vOs;
158         float fMagS;
159         SVec3 vOt;
160         float fMagT;
161         int iCounter;   // this is to average back into quads.
162         tbool bOrient;
163 } STSpace;
164
165 int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
166 void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
167 void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
168 int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn);
169 tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[],
170                                          const int iNrActiveGroups, const int piTriListIn[], const float fThresCos,
171                                          const SMikkTSpaceContext * pContext);
172
173 static int MakeIndex(const int iFace, const int iVert)
174 {
175         assert(iVert>=0 && iVert<4 && iFace>=0);
176         return (iFace<<2) | (iVert&0x3);
177 }
178
179 static void IndexToData(int * piFace, int * piVert, const int iIndexIn)
180 {
181         piVert[0] = iIndexIn&0x3;
182         piFace[0] = iIndexIn>>2;
183 }
184
185 static const STSpace AvgTSpace(const STSpace * pTS0, const STSpace * pTS1)
186 {
187         STSpace ts_res;
188
189         // this if is important. Due to floating point precision
190         // averaging when ts0==ts1 will cause a slight difference
191         // which results in tangent space splits later on
192         if(pTS0->fMagS==pTS1->fMagS && pTS0->fMagT==pTS1->fMagT &&
193            veq(pTS0->vOs,pTS1->vOs)     && veq(pTS0->vOt, pTS1->vOt))
194         {
195                 ts_res.fMagS = pTS0->fMagS;
196                 ts_res.fMagT = pTS0->fMagT;
197                 ts_res.vOs = pTS0->vOs;
198                 ts_res.vOt = pTS0->vOt;
199         }
200         else
201         {
202                 ts_res.fMagS = 0.5f*(pTS0->fMagS+pTS1->fMagS);
203                 ts_res.fMagT = 0.5f*(pTS0->fMagT+pTS1->fMagT);
204                 ts_res.vOs = vadd(pTS0->vOs,pTS1->vOs);
205                 ts_res.vOt = vadd(pTS0->vOt,pTS1->vOt);
206                 if( VNotZero(ts_res.vOs) ) ts_res.vOs = Normalize(ts_res.vOs);
207                 if( VNotZero(ts_res.vOt) ) ts_res.vOt = Normalize(ts_res.vOt);
208         }
209
210         return ts_res;
211 }
212
213
214
215 const SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index);
216 const SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index);
217 const SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index);
218
219
220 // degen triangles
221 void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris);
222 void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris);
223
224
225 tbool genTangSpaceDefault(const SMikkTSpaceContext * pContext)
226 {
227         return genTangSpace(pContext, 180.0f);
228 }
229
230 tbool genTangSpace(const SMikkTSpaceContext * pContext, const float fAngularThreshold)
231 {
232         // count nr_triangles
233         int * piTriListIn = NULL, * piGroupTrianglesBuffer = NULL;
234         STriInfo * pTriInfos = NULL;
235         SGroup * pGroups = NULL;
236         STSpace * psTspace = NULL;
237         int iNrTrianglesIn = 0, f=0, t=0, i=0;
238         int iNrTSPaces = 0, iTotTris = 0, iDegenTriangles = 0, iNrMaxGroups = 0;
239         int iNrActiveGroups = 0, index = 0;
240         const int iNrFaces = pContext->m_pInterface->m_getNumFaces(pContext);
241         tbool bRes = TFALSE;
242         const float fThresCos = (const float) cos((fAngularThreshold*M_PI)/180);
243
244         // verify all call-backs have been set
245         if( pContext->m_pInterface->m_getNumFaces==NULL ||
246                 pContext->m_pInterface->m_getNumVerticesOfFace==NULL ||
247                 pContext->m_pInterface->m_getPosition==NULL ||
248                 pContext->m_pInterface->m_getNormal==NULL ||
249                 pContext->m_pInterface->m_getTexCoord==NULL )
250                 return TFALSE;
251
252         // count triangles on supported faces
253         for(f=0; f<iNrFaces; f++)
254         {
255                 const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);
256                 if(verts==3) ++iNrTrianglesIn;
257                 else if(verts==4) iNrTrianglesIn += 2;
258         }
259         if(iNrTrianglesIn<=0) return TFALSE;
260
261         // allocate memory for an index list
262         piTriListIn = (int *) malloc(sizeof(int)*3*iNrTrianglesIn);
263         pTriInfos = (STriInfo *) malloc(sizeof(STriInfo)*iNrTrianglesIn);
264         if(piTriListIn==NULL || pTriInfos==NULL)
265         {
266                 if(piTriListIn!=NULL) free(piTriListIn);
267                 if(pTriInfos!=NULL) free(pTriInfos);
268                 return TFALSE;
269         }
270
271         // make an initial triangle --> face index list
272         iNrTSPaces = GenerateInitialVerticesIndexList(pTriInfos, piTriListIn, pContext, iNrTrianglesIn);
273
274         // make a welded index list of identical positions and attributes (pos, norm, texc)
275         //printf("gen welded index list begin\n");
276         GenerateSharedVerticesIndexList(piTriListIn, pContext, iNrTrianglesIn);
277         //printf("gen welded index list end\n");
278
279         // Mark all degenerate triangles
280         iTotTris = iNrTrianglesIn;
281         iNrTrianglesIn = 0;
282         iDegenTriangles = 0;
283         for(t=0; t<iTotTris; t++)
284         {
285                 const int i0 = piTriListIn[t*3+0];
286                 const int i1 = piTriListIn[t*3+1];
287                 const int i2 = piTriListIn[t*3+2];
288                 const SVec3 p0 = GetPosition(pContext, i0);
289                 const SVec3 p1 = GetPosition(pContext, i1);
290                 const SVec3 p2 = GetPosition(pContext, i2);
291                 if(veq(p0,p1) || veq(p0,p2) || veq(p1,p2))      // degenerate
292                 {
293                         pTriInfos[t].iFlag |= MARK_DEGENERATE;
294                         ++iDegenTriangles;
295                 }
296         }
297         iNrTrianglesIn = iTotTris - iDegenTriangles;
298
299         // mark all triangle pairs that belong to a quad with only one
300         // good triangle. These need special treatment in DegenEpilogue().
301         // Additionally, move all good triangles to the start of
302         // pTriInfos[] and piTriListIn[] without changing order and
303         // put the degenerate triangles last.
304         DegenPrologue(pTriInfos, piTriListIn, iNrTrianglesIn, iTotTris);
305
306         
307         // evaluate triangle level attributes and neighbor list
308         //printf("gen neighbors list begin\n");
309         InitTriInfo(pTriInfos, piTriListIn, pContext, iNrTrianglesIn);
310         //printf("gen neighbors list end\n");
311
312         
313         // based on the 4 rules, identify groups based on connectivity
314         iNrMaxGroups = iNrTrianglesIn*3;
315         pGroups = (SGroup *) malloc(sizeof(SGroup)*iNrMaxGroups);
316         piGroupTrianglesBuffer = (int *) malloc(sizeof(int)*iNrTrianglesIn*3);
317         if(pGroups==NULL || piGroupTrianglesBuffer==NULL)
318         {
319                 if(pGroups!=NULL) free(pGroups);
320                 if(piGroupTrianglesBuffer!=NULL) free(piGroupTrianglesBuffer);
321                 free(piTriListIn);
322                 free(pTriInfos);
323                 return TFALSE;
324         }
325         //printf("gen 4rule groups begin\n");
326         iNrActiveGroups =
327                 Build4RuleGroups(pTriInfos, pGroups, piGroupTrianglesBuffer, piTriListIn, iNrTrianglesIn);
328         //printf("gen 4rule groups end\n");
329
330         //
331
332         psTspace = (STSpace *) malloc(sizeof(STSpace)*iNrTSPaces);
333         if(psTspace==NULL)
334         {
335                 free(piTriListIn);
336                 free(pTriInfos);
337                 free(pGroups);
338                 free(piGroupTrianglesBuffer);
339                 return TFALSE;
340         }
341         memset(psTspace, 0, sizeof(STSpace)*iNrTSPaces);
342         for(t=0; t<iNrTSPaces; t++)
343         {
344                 psTspace[t].vOs.x=1.0f; psTspace[t].vOs.y=0.0f; psTspace[t].vOs.z=0.0f; psTspace[t].fMagS = 1.0f;
345                 psTspace[t].vOt.x=0.0f; psTspace[t].vOt.y=1.0f; psTspace[t].vOt.z=0.0f; psTspace[t].fMagT = 1.0f;
346         }
347
348         // make tspaces, each group is split up into subgroups if necessary
349         // based on fAngularThreshold. Finally a tangent space is made for
350         // every resulting subgroup
351         //printf("gen tspaces begin\n");
352         bRes = GenerateTSpaces(psTspace, pTriInfos, pGroups, iNrActiveGroups, piTriListIn, fThresCos, pContext);
353         //printf("gen tspaces end\n");
354         
355         // clean up
356         free(pGroups);
357         free(piGroupTrianglesBuffer);
358
359         if(!bRes)       // if an allocation in GenerateTSpaces() failed
360         {
361                 // clean up and return false
362                 free(pTriInfos); free(piTriListIn); free(psTspace);
363                 return TFALSE;
364         }
365
366
367         // degenerate quads with one good triangle will be fixed by copying a space from
368         // the good triangle to the coinciding vertex.
369         // all other degenerate triangles will just copy a space from any good triangle
370         // with the same welded index in piTriListIn[].
371         DegenEpilogue(psTspace, pTriInfos, piTriListIn, pContext, iNrTrianglesIn, iTotTris);
372
373         free(pTriInfos); free(piTriListIn);
374
375         index = 0;
376         for(f=0; f<iNrFaces; f++)
377         {
378                 const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);
379                 if(verts!=3 && verts!=4) continue;
380                 
381
382                 // I've decided to let degenerate triangles and group-with-anythings
383                 // vary between left/right hand coordinate systems at the vertices.
384                 // All healthy triangles on the other hand are built to always be either or.
385
386                 /*// force the coordinate system orientation to be uniform for every face.
387                 // (this is already the case for good triangles but not for
388                 // degenerate ones and those with bGroupWithAnything==true)
389                 bool bOrient = psTspace[index].bOrient;
390                 if(psTspace[index].iCounter == 0)       // tspace was not derived from a group
391                 {
392                         // look for a space created in GenerateTSpaces() by iCounter>0
393                         bool bNotFound = true;
394                         int i=1;
395                         while(i<verts && bNotFound)
396                         {
397                                 if(psTspace[index+i].iCounter > 0) bNotFound=false;
398                                 else ++i;
399                         }
400                         if(!bNotFound) bOrient = psTspace[index+i].bOrient;
401                 }*/
402
403                 // set data
404                 for(i=0; i<verts; i++)
405                 {
406                         const STSpace * pTSpace = &psTspace[index];
407                         float tang[] = {pTSpace->vOs.x, pTSpace->vOs.y, pTSpace->vOs.z};
408                         float bitang[] = {pTSpace->vOt.x, pTSpace->vOt.y, pTSpace->vOt.z};
409                         if(pContext->m_pInterface->m_setTSpace!=NULL)
410                                 pContext->m_pInterface->m_setTSpace(pContext, tang, bitang, pTSpace->fMagS, pTSpace->fMagT, pTSpace->bOrient, f, i);
411                         if(pContext->m_pInterface->m_setTSpaceBasic!=NULL)
412                                 pContext->m_pInterface->m_setTSpaceBasic(pContext, tang, pTSpace->bOrient==TTRUE ? 1.0f : (-1.0f), f, i);
413
414                         ++index;
415                 }
416         }
417
418         free(psTspace);
419
420         
421         return TTRUE;
422 }
423
424 ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
425
426 typedef struct
427 {
428         float vert[3];
429         int index;
430 } STmpVert;
431
432 static const int g_iCells = 2048;
433
434 // it is IMPORTANT that this function is called to evaluate the hash since
435 // inlining could potentially reorder instructions and generate different
436 // results for the same effective input value fVal.
437 #if defined(_MSC_VER) && !defined(FREE_WINDOWS)
438         #define NOINLINE __declspec(noinline)
439 #else
440         #define NOINLINE __attribute__((noinline))
441 #endif
442 static NOINLINE int FindGridCell(const float fMin, const float fMax, const float fVal)
443 {
444         const float fIndex = (g_iCells-1) * ((fVal-fMin)/(fMax-fMin));
445         const int iIndex = fIndex<0?0:((int) (fIndex+0.5f));
446         return iIndex<g_iCells?iIndex:(g_iCells-1);
447 }
448
449 void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in);
450 void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries);
451 void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn);
452
453 void GenerateSharedVerticesIndexList(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
454 {
455
456         // Generate bounding box
457         int * piHashTable=NULL, * piHashCount=NULL, * piHashOffsets=NULL, * piHashCount2=NULL;
458         STmpVert * pTmpVert = NULL;
459         int i=0, iChannel=0, k=0, e=0;
460         int iMaxCount=0;
461         SVec3 vMin = GetPosition(pContext, 0), vMax = vMin, vDim;
462         float fMin, fMax;
463         for(i=1; i<(iNrTrianglesIn*3); i++)
464         {
465                 const int index = piTriList_in_and_out[i];
466
467                 const SVec3 vP = GetPosition(pContext, index);
468                 if(vMin.x > vP.x) vMin.x = vP.x;
469                 else if(vMax.x < vP.x) vMax.x = vP.x;
470                 if(vMin.y > vP.y) vMin.y = vP.y;
471                 else if(vMax.y < vP.y) vMax.y = vP.y;
472                 if(vMin.z > vP.z) vMin.z = vP.z;
473                 else if(vMax.z < vP.z) vMax.z = vP.z;
474         }
475
476         vDim = vsub(vMax,vMin);
477         iChannel = 0;
478         fMin = vMin.x; fMax=vMax.x;
479         if(vDim.y>vDim.x && vDim.y>vDim.z)
480         {
481                 iChannel=1;
482                 fMin = vMin.y, fMax=vMax.y;
483         }
484         else if(vDim.z>vDim.x)
485         {
486                 iChannel=2;
487                 fMin = vMin.z, fMax=vMax.z;
488         }
489
490         // make allocations
491         piHashTable = (int *) malloc(sizeof(int)*iNrTrianglesIn*3);
492         piHashCount = (int *) malloc(sizeof(int)*g_iCells);
493         piHashOffsets = (int *) malloc(sizeof(int)*g_iCells);
494         piHashCount2 = (int *) malloc(sizeof(int)*g_iCells);
495
496         if(piHashTable==NULL || piHashCount==NULL || piHashOffsets==NULL || piHashCount2==NULL)
497         {
498                 if(piHashTable!=NULL) free(piHashTable);
499                 if(piHashCount!=NULL) free(piHashCount);
500                 if(piHashOffsets!=NULL) free(piHashOffsets);
501                 if(piHashCount2!=NULL) free(piHashCount2);
502                 GenerateSharedVerticesIndexListSlow(piTriList_in_and_out, pContext, iNrTrianglesIn);
503                 return;
504         }
505         memset(piHashCount, 0, sizeof(int)*g_iCells);
506         memset(piHashCount2, 0, sizeof(int)*g_iCells);
507
508         // count amount of elements in each cell unit
509         for(i=0; i<(iNrTrianglesIn*3); i++)
510         {
511                 const int index = piTriList_in_and_out[i];
512                 const SVec3 vP = GetPosition(pContext, index);
513                 const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z);
514                 const int iCell = FindGridCell(fMin, fMax, fVal);
515                 ++piHashCount[iCell];
516         }
517
518         // evaluate start index of each cell.
519         piHashOffsets[0]=0;
520         for(k=1; k<g_iCells; k++)
521                 piHashOffsets[k]=piHashOffsets[k-1]+piHashCount[k-1];
522
523         // insert vertices
524         for(i=0; i<(iNrTrianglesIn*3); i++)
525         {
526                 const int index = piTriList_in_and_out[i];
527                 const SVec3 vP = GetPosition(pContext, index);
528                 const float fVal = iChannel==0 ? vP.x : (iChannel==1 ? vP.y : vP.z);
529                 const int iCell = FindGridCell(fMin, fMax, fVal);
530                 int * pTable = NULL;
531
532                 assert(piHashCount2[iCell]<piHashCount[iCell]);
533                 pTable = &piHashTable[piHashOffsets[iCell]];
534                 pTable[piHashCount2[iCell]] = i;        // vertex i has been inserted.
535                 ++piHashCount2[iCell];
536         }
537         for(k=0; k<g_iCells; k++)
538                 assert(piHashCount2[k] == piHashCount[k]);      // verify the count
539         free(piHashCount2);
540
541         // find maximum amount of entries in any hash entry
542         iMaxCount = piHashCount[0];
543         for(k=1; k<g_iCells; k++)
544                 if(iMaxCount<piHashCount[k])
545                         iMaxCount=piHashCount[k];
546         pTmpVert = (STmpVert *) malloc(sizeof(STmpVert)*iMaxCount);
547         
548
549         // complete the merge
550         for(k=0; k<g_iCells; k++)
551         {
552                 // extract table of cell k and amount of entries in it
553                 int * pTable = &piHashTable[piHashOffsets[k]];
554                 const int iEntries = piHashCount[k];
555                 if(iEntries < 2) continue;
556
557                 if(pTmpVert!=NULL)
558                 {
559                         for(e=0; e<iEntries; e++)
560                         {
561                                 int i = pTable[e];
562                                 const SVec3 vP = GetPosition(pContext, piTriList_in_and_out[i]);
563                                 pTmpVert[e].vert[0] = vP.x; pTmpVert[e].vert[1] = vP.y;
564                                 pTmpVert[e].vert[2] = vP.z; pTmpVert[e].index = i;
565                         }
566                         MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, 0, iEntries-1);
567                 }
568                 else
569                         MergeVertsSlow(piTriList_in_and_out, pContext, pTable, iEntries);
570         }
571
572         if(pTmpVert!=NULL) { free(pTmpVert); }
573         free(piHashTable);
574         free(piHashCount);
575         free(piHashOffsets);
576 }
577
578 void MergeVertsFast(int piTriList_in_and_out[], STmpVert pTmpVert[], const SMikkTSpaceContext * pContext, const int iL_in, const int iR_in)
579 {
580         // make bbox
581         int c=0, l=0, channel=0;
582         float fvMin[3], fvMax[3];
583         float dx=0, dy=0, dz=0, fSep=0;
584         for(c=0; c<3; c++)
585         {       fvMin[c]=pTmpVert[iL_in].vert[c]; fvMax[c]=fvMin[c];    }
586         for(l=(iL_in+1); l<=iR_in; l++)
587                 for(c=0; c<3; c++)
588                         if(fvMin[c]>pTmpVert[l].vert[c]) fvMin[c]=pTmpVert[l].vert[c];
589                         else if(fvMax[c]<pTmpVert[l].vert[c]) fvMax[c]=pTmpVert[l].vert[c];
590
591         dx = fvMax[0]-fvMin[0];
592         dy = fvMax[1]-fvMin[1];
593         dz = fvMax[2]-fvMin[2];
594
595         channel = 0;
596         if(dy>dx && dy>dz) channel=1;
597         else if(dz>dx) channel=2;
598
599         fSep = 0.5f*(fvMax[channel]+fvMin[channel]);
600
601         // terminate recursion when the separation/average value
602         // is no longer strictly between fMin and fMax values.
603         if(fSep>=fvMax[channel] || fSep<=fvMin[channel])
604         {
605                 // complete the weld
606                 for(l=iL_in; l<=iR_in; l++)
607                 {
608                         int i = pTmpVert[l].index;
609                         const int index = piTriList_in_and_out[i];
610                         const SVec3 vP = GetPosition(pContext, index);
611                         const SVec3 vN = GetNormal(pContext, index);
612                         const SVec3 vT = GetTexCoord(pContext, index);
613
614                         tbool bNotFound = TTRUE;
615                         int l2=iL_in, i2rec=-1;
616                         while(l2<l && bNotFound)
617                         {
618                                 const int i2 = pTmpVert[l2].index;
619                                 const int index2 = piTriList_in_and_out[i2];
620                                 const SVec3 vP2 = GetPosition(pContext, index2);
621                                 const SVec3 vN2 = GetNormal(pContext, index2);
622                                 const SVec3 vT2 = GetTexCoord(pContext, index2);
623                                 i2rec=i2;
624
625                                 //if(vP==vP2 && vN==vN2 && vT==vT2)
626                                 if(vP.x==vP2.x && vP.y==vP2.y && vP.z==vP2.z &&
627                                         vN.x==vN2.x && vN.y==vN2.y && vN.z==vN2.z &&
628                                         vT.x==vT2.x && vT.y==vT2.y && vT.z==vT2.z)
629                                         bNotFound = TFALSE;
630                                 else
631                                         ++l2;
632                         }
633                         
634                         // merge if previously found
635                         if(!bNotFound)
636                                 piTriList_in_and_out[i] = piTriList_in_and_out[i2rec];
637                 }
638         }
639         else
640         {
641                 int iL=iL_in, iR=iR_in;
642                 assert((iR_in-iL_in)>0);        // at least 2 entries
643
644                 // seperate (by fSep) all points between iL_in and iR_in in pTmpVert[]
645                 while(iL < iR)
646                 {
647                         tbool bReadyLeftSwap = TFALSE, bReadyRightSwap = TFALSE;
648                         while((!bReadyLeftSwap) && iL<iR)
649                         {
650                                 assert(iL>=iL_in && iL<=iR_in);
651                                 bReadyLeftSwap = !(pTmpVert[iL].vert[channel]<fSep);
652                                 if(!bReadyLeftSwap) ++iL;
653                         }
654                         while((!bReadyRightSwap) && iL<iR)
655                         {
656                                 assert(iR>=iL_in && iR<=iR_in);
657                                 bReadyRightSwap = pTmpVert[iR].vert[channel]<fSep;
658                                 if(!bReadyRightSwap) --iR;
659                         }
660                         assert( (iL<iR) || !(bReadyLeftSwap && bReadyRightSwap) );
661
662                         if(bReadyLeftSwap && bReadyRightSwap)
663                         {
664                                 const STmpVert sTmp = pTmpVert[iL];
665                                 assert(iL<iR);
666                                 pTmpVert[iL] = pTmpVert[iR];
667                                 pTmpVert[iR] = sTmp;
668                                 ++iL; --iR;
669                         }
670                 }
671
672                 assert(iL==(iR+1) || (iL==iR));
673                 if(iL==iR)
674                 {
675                         const tbool bReadyRightSwap = pTmpVert[iR].vert[channel]<fSep;
676                         if(bReadyRightSwap) ++iL;
677                         else --iR;
678                 }
679
680                 // only need to weld when there is more than 1 instance of the (x,y,z)
681                 if(iL_in < iR)
682                         MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, iL_in, iR);    // weld all left of fSep
683                 if(iL < iR_in)
684                         MergeVertsFast(piTriList_in_and_out, pTmpVert, pContext, iL, iR_in);    // weld all right of (or equal to) fSep
685         }
686 }
687
688 void MergeVertsSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int pTable[], const int iEntries)
689 {
690         // this can be optimized further using a tree structure or more hashing.
691         int e=0;
692         for(e=0; e<iEntries; e++)
693         {
694                 int i = pTable[e];
695                 const int index = piTriList_in_and_out[i];
696                 const SVec3 vP = GetPosition(pContext, index);
697                 const SVec3 vN = GetNormal(pContext, index);
698                 const SVec3 vT = GetTexCoord(pContext, index);
699
700                 tbool bNotFound = TTRUE;
701                 int e2=0, i2rec=-1;
702                 while(e2<e && bNotFound)
703                 {
704                         const int i2 = pTable[e2];
705                         const int index2 = piTriList_in_and_out[i2];
706                         const SVec3 vP2 = GetPosition(pContext, index2);
707                         const SVec3 vN2 = GetNormal(pContext, index2);
708                         const SVec3 vT2 = GetTexCoord(pContext, index2);
709                         i2rec = i2;
710
711                         if(veq(vP,vP2) && veq(vN,vN2) && veq(vT,vT2))
712                                 bNotFound = TFALSE;
713                         else
714                                 ++e2;
715                 }
716                 
717                 // merge if previously found
718                 if(!bNotFound)
719                         piTriList_in_and_out[i] = piTriList_in_and_out[i2rec];
720         }
721 }
722
723 void GenerateSharedVerticesIndexListSlow(int piTriList_in_and_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
724 {
725         int iNumUniqueVerts = 0, t=0, i=0;
726         for(t=0; t<iNrTrianglesIn; t++)
727         {
728                 for(i=0; i<3; i++)
729                 {
730                         const int offs = t*3 + i;
731                         const int index = piTriList_in_and_out[offs];
732
733                         const SVec3 vP = GetPosition(pContext, index);
734                         const SVec3 vN = GetNormal(pContext, index);
735                         const SVec3 vT = GetTexCoord(pContext, index);
736
737                         tbool bFound = TFALSE;
738                         int t2=0, index2rec=-1;
739                         while(!bFound && t2<=t)
740                         {
741                                 int j=0;
742                                 while(!bFound && j<3)
743                                 {
744                                         const int index2 = piTriList_in_and_out[t2*3 + j];
745                                         const SVec3 vP2 = GetPosition(pContext, index2);
746                                         const SVec3 vN2 = GetNormal(pContext, index2);
747                                         const SVec3 vT2 = GetTexCoord(pContext, index2);
748                                         
749                                         if(veq(vP,vP2) && veq(vN,vN2) && veq(vT,vT2))
750                                                 bFound = TTRUE;
751                                         else
752                                                 ++j;
753                                 }
754                                 if(!bFound) ++t2;
755                         }
756
757                         assert(bFound);
758                         // if we found our own
759                         if(index2rec == index) { ++iNumUniqueVerts; }
760
761                         piTriList_in_and_out[offs] = index2rec;
762                 }
763         }
764 }
765
766 int GenerateInitialVerticesIndexList(STriInfo pTriInfos[], int piTriList_out[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
767 {
768         int iTSpacesOffs = 0, f=0, t=0;
769         int iDstTriIndex = 0;
770         for(f=0; f<pContext->m_pInterface->m_getNumFaces(pContext); f++)
771         {
772                 const int verts = pContext->m_pInterface->m_getNumVerticesOfFace(pContext, f);
773                 if(verts!=3 && verts!=4) continue;
774
775                 pTriInfos[iDstTriIndex].iOrgFaceNumber = f;
776                 pTriInfos[iDstTriIndex].iTSpacesOffs = iTSpacesOffs;
777
778                 if(verts==3)
779                 {
780                         unsigned char * pVerts = pTriInfos[iDstTriIndex].vert_num;
781                         pVerts[0]=0; pVerts[1]=1; pVerts[2]=2;
782                         piTriList_out[iDstTriIndex*3+0] = MakeIndex(f, 0);
783                         piTriList_out[iDstTriIndex*3+1] = MakeIndex(f, 1);
784                         piTriList_out[iDstTriIndex*3+2] = MakeIndex(f, 2);
785                         ++iDstTriIndex; // next
786                 }
787                 else
788                 {
789                         {
790                                 pTriInfos[iDstTriIndex+1].iOrgFaceNumber = f;
791                                 pTriInfos[iDstTriIndex+1].iTSpacesOffs = iTSpacesOffs;
792                         }
793
794                         {
795                                 // need an order independent way to evaluate
796                                 // tspace on quads. This is done by splitting
797                                 // along the shortest diagonal.
798                                 const int i0 = MakeIndex(f, 0);
799                                 const int i1 = MakeIndex(f, 1);
800                                 const int i2 = MakeIndex(f, 2);
801                                 const int i3 = MakeIndex(f, 3);
802                                 const SVec3 T0 = GetTexCoord(pContext, i0);
803                                 const SVec3 T1 = GetTexCoord(pContext, i1);
804                                 const SVec3 T2 = GetTexCoord(pContext, i2);
805                                 const SVec3 T3 = GetTexCoord(pContext, i3);
806                                 const float distSQ_02 = LengthSquared(vsub(T2,T0));
807                                 const float distSQ_13 = LengthSquared(vsub(T3,T1));
808                                 tbool bQuadDiagIs_02;
809                                 if(distSQ_02<distSQ_13)
810                                         bQuadDiagIs_02 = TTRUE;
811                                 else if(distSQ_13<distSQ_02)
812                                         bQuadDiagIs_02 = TFALSE;
813                                 else
814                                 {
815                                         const SVec3 P0 = GetPosition(pContext, i0);
816                                         const SVec3 P1 = GetPosition(pContext, i1);
817                                         const SVec3 P2 = GetPosition(pContext, i2);
818                                         const SVec3 P3 = GetPosition(pContext, i3);
819                                         const float distSQ_02 = LengthSquared(vsub(P2,P0));
820                                         const float distSQ_13 = LengthSquared(vsub(P3,P1));
821
822                                         bQuadDiagIs_02 = distSQ_13<distSQ_02 ? TFALSE : TTRUE;
823                                 }
824
825                                 if(bQuadDiagIs_02)
826                                 {
827                                         {
828                                                 unsigned char * pVerts_A = pTriInfos[iDstTriIndex].vert_num;
829                                                 pVerts_A[0]=0; pVerts_A[1]=1; pVerts_A[2]=2;
830                                         }
831                                         piTriList_out[iDstTriIndex*3+0] = i0;
832                                         piTriList_out[iDstTriIndex*3+1] = i1;
833                                         piTriList_out[iDstTriIndex*3+2] = i2;
834                                         ++iDstTriIndex; // next
835                                         {
836                                                 unsigned char * pVerts_B = pTriInfos[iDstTriIndex].vert_num;
837                                                 pVerts_B[0]=0; pVerts_B[1]=2; pVerts_B[2]=3;
838                                         }
839                                         piTriList_out[iDstTriIndex*3+0] = i0;
840                                         piTriList_out[iDstTriIndex*3+1] = i2;
841                                         piTriList_out[iDstTriIndex*3+2] = i3;
842                                         ++iDstTriIndex; // next
843                                 }
844                                 else
845                                 {
846                                         {
847                                                 unsigned char * pVerts_A = pTriInfos[iDstTriIndex].vert_num;
848                                                 pVerts_A[0]=0; pVerts_A[1]=1; pVerts_A[2]=3;
849                                         }
850                                         piTriList_out[iDstTriIndex*3+0] = i0;
851                                         piTriList_out[iDstTriIndex*3+1] = i1;
852                                         piTriList_out[iDstTriIndex*3+2] = i3;
853                                         ++iDstTriIndex; // next
854                                         {
855                                                 unsigned char * pVerts_B = pTriInfos[iDstTriIndex].vert_num;
856                                                 pVerts_B[0]=1; pVerts_B[1]=2; pVerts_B[2]=3;
857                                         }
858                                         piTriList_out[iDstTriIndex*3+0] = i1;
859                                         piTriList_out[iDstTriIndex*3+1] = i2;
860                                         piTriList_out[iDstTriIndex*3+2] = i3;
861                                         ++iDstTriIndex; // next
862                                 }
863                         }
864                 }
865
866                 iTSpacesOffs += verts;
867                 assert(iDstTriIndex<=iNrTrianglesIn);
868         }
869
870         for(t=0; t<iNrTrianglesIn; t++)
871                 pTriInfos[t].iFlag = 0;
872
873         // return total amount of tspaces
874         return iTSpacesOffs;
875 }
876
877 const SVec3 GetPosition(const SMikkTSpaceContext * pContext, const int index)
878 {
879         int iF, iI;
880         SVec3 res; float pos[3];
881         IndexToData(&iF, &iI, index);
882         pContext->m_pInterface->m_getPosition(pContext, pos, iF, iI);
883         res.x=pos[0]; res.y=pos[1]; res.z=pos[2];
884         return res;
885 }
886
887 const SVec3 GetNormal(const SMikkTSpaceContext * pContext, const int index)
888 {
889         int iF, iI;
890         SVec3 res; float norm[3];
891         IndexToData(&iF, &iI, index);
892         pContext->m_pInterface->m_getNormal(pContext, norm, iF, iI);
893         res.x=norm[0]; res.y=norm[1]; res.z=norm[2];
894         return res;
895 }
896
897 const SVec3 GetTexCoord(const SMikkTSpaceContext * pContext, const int index)
898 {
899         int iF, iI;
900         SVec3 res; float texc[2];
901         IndexToData(&iF, &iI, index);
902         pContext->m_pInterface->m_getTexCoord(pContext, texc, iF, iI);
903         res.x=texc[0]; res.y=texc[1]; res.z=1.0f;
904         return res;
905 }
906
907 /////////////////////////////////////////////////////////////////////////////////////////////////////
908 /////////////////////////////////////////////////////////////////////////////////////////////////////
909
910 typedef union
911 {
912         struct
913         {
914                 int i0, i1, f;
915         };
916         int array[3];
917 } SEdge;
918
919 void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn);
920 void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn);
921
922 // returns the texture area times 2
923 static float CalcTexArea(const SMikkTSpaceContext * pContext, const int indices[])
924 {
925         const SVec3 t1 = GetTexCoord(pContext, indices[0]);
926         const SVec3 t2 = GetTexCoord(pContext, indices[1]);
927         const SVec3 t3 = GetTexCoord(pContext, indices[2]);
928
929         const float t21x = t2.x-t1.x;
930         const float t21y = t2.y-t1.y;
931         const float t31x = t3.x-t1.x;
932         const float t31y = t3.y-t1.y;
933
934         const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x;
935
936         return fSignedAreaSTx2<0 ? (-fSignedAreaSTx2) : fSignedAreaSTx2;
937 }
938
939 void InitTriInfo(STriInfo pTriInfos[], const int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn)
940 {
941         int f=0, i=0, t=0;
942         // pTriInfos[f].iFlag is cleared in GenerateInitialVerticesIndexList() which is called before this function.
943
944         // generate neighbor info list
945         for(f=0; f<iNrTrianglesIn; f++)
946                 for(i=0; i<3; i++)
947                 {
948                         pTriInfos[f].FaceNeighbors[i] = -1;
949                         pTriInfos[f].AssignedGroup[i] = NULL;
950
951                         pTriInfos[f].vOs.x=0.0f; pTriInfos[f].vOs.y=0.0f; pTriInfos[f].vOs.z=0.0f;
952                         pTriInfos[f].vOt.x=0.0f; pTriInfos[f].vOt.y=0.0f; pTriInfos[f].vOt.z=0.0f;
953                         pTriInfos[f].fMagS = 0;
954                         pTriInfos[f].fMagT = 0;
955
956                         // assumed bad
957                         pTriInfos[f].iFlag |= GROUP_WITH_ANY;
958                 }
959
960         // evaluate first order derivatives
961         for(f=0; f<iNrTrianglesIn; f++)
962         {
963                 // initial values
964                 const SVec3 v1 = GetPosition(pContext, piTriListIn[f*3+0]);
965                 const SVec3 v2 = GetPosition(pContext, piTriListIn[f*3+1]);
966                 const SVec3 v3 = GetPosition(pContext, piTriListIn[f*3+2]);
967                 const SVec3 t1 = GetTexCoord(pContext, piTriListIn[f*3+0]);
968                 const SVec3 t2 = GetTexCoord(pContext, piTriListIn[f*3+1]);
969                 const SVec3 t3 = GetTexCoord(pContext, piTriListIn[f*3+2]);
970
971                 const float t21x = t2.x-t1.x;
972                 const float t21y = t2.y-t1.y;
973                 const float t31x = t3.x-t1.x;
974                 const float t31y = t3.y-t1.y;
975                 const SVec3 d1 = vsub(v2,v1);
976                 const SVec3 d2 = vsub(v3,v1);
977
978                 const float fSignedAreaSTx2 = t21x*t31y - t21y*t31x;
979                 //assert(fSignedAreaSTx2!=0);
980                 SVec3 vOs = vsub(vscale(t31y,d1), vscale(t21y,d2));     // eq 18
981                 SVec3 vOt = vadd(vscale(-t31x,d1), vscale(t21x,d2)); // eq 19
982
983                 pTriInfos[f].iFlag |= (fSignedAreaSTx2>0 ? ORIENT_PRESERVING : 0);
984
985                 if( NotZero(fSignedAreaSTx2) )
986                 {
987                         const float fAbsArea = fabsf(fSignedAreaSTx2);
988                         const float fLenOs = Length(vOs);
989                         const float fLenOt = Length(vOt);
990                         const float fS = (pTriInfos[f].iFlag&ORIENT_PRESERVING)==0 ? (-1.0f) : 1.0f;
991                         if( NotZero(fLenOs) ) pTriInfos[f].vOs = vscale(fS/fLenOs, vOs);
992                         if( NotZero(fLenOt) ) pTriInfos[f].vOt = vscale(fS/fLenOt, vOt);
993
994                         // evaluate magnitudes prior to normalization of vOs and vOt
995                         pTriInfos[f].fMagS = fLenOs / fAbsArea;
996                         pTriInfos[f].fMagT = fLenOt / fAbsArea;
997
998                         // if this is a good triangle
999                         if( NotZero(pTriInfos[f].fMagS) && NotZero(pTriInfos[f].fMagT))
1000                                 pTriInfos[f].iFlag &= (~GROUP_WITH_ANY);
1001                 }
1002         }
1003
1004         // force otherwise healthy quads to a fixed orientation
1005         while(t<(iNrTrianglesIn-1))
1006         {
1007                 const int iFO_a = pTriInfos[t].iOrgFaceNumber;
1008                 const int iFO_b = pTriInfos[t+1].iOrgFaceNumber;
1009                 if(iFO_a==iFO_b)        // this is a quad
1010                 {
1011                         const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;
1012                         const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;
1013                         
1014                         // bad triangles should already have been removed by
1015                         // DegenPrologue(), but just in case check bIsDeg_a and bIsDeg_a are false
1016                         if((bIsDeg_a||bIsDeg_b)==TFALSE)
1017                         {
1018                                 const tbool bOrientA = (pTriInfos[t].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1019                                 const tbool bOrientB = (pTriInfos[t+1].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1020                                 // if this happens the quad has extremely bad mapping!!
1021                                 if(bOrientA!=bOrientB)
1022                                 {
1023                                         //printf("found quad with bad mapping\n");
1024                                         tbool bChooseOrientFirstTri = TFALSE;
1025                                         if((pTriInfos[t+1].iFlag&GROUP_WITH_ANY)!=0) bChooseOrientFirstTri = TTRUE;
1026                                         else if( CalcTexArea(pContext, &piTriListIn[t*3+0]) >= CalcTexArea(pContext, &piTriListIn[(t+1)*3+0]) )
1027                                                 bChooseOrientFirstTri = TTRUE;
1028
1029                                         // force match
1030                                         {
1031                                                 const int t0 = bChooseOrientFirstTri ? t : (t+1);
1032                                                 const int t1 = bChooseOrientFirstTri ? (t+1) : t;
1033                                                 pTriInfos[t1].iFlag &= (~ORIENT_PRESERVING);    // clear first
1034                                                 pTriInfos[t1].iFlag |= (pTriInfos[t0].iFlag&ORIENT_PRESERVING); // copy bit
1035                                         }
1036                                 }
1037                         }
1038                         t += 2;
1039                 }
1040                 else
1041                         ++t;
1042         }
1043         
1044         // match up edge pairs
1045         {
1046                 SEdge * pEdges = (SEdge *) malloc(sizeof(SEdge)*iNrTrianglesIn*3);
1047                 if(pEdges==NULL)
1048                         BuildNeighborsSlow(pTriInfos, piTriListIn, iNrTrianglesIn);
1049                 else
1050                 {
1051                         BuildNeighborsFast(pTriInfos, pEdges, piTriListIn, iNrTrianglesIn);
1052         
1053                         free(pEdges);
1054                 }
1055         }
1056 }
1057
1058 /////////////////////////////////////////////////////////////////////////////////////////////////////
1059 /////////////////////////////////////////////////////////////////////////////////////////////////////
1060
1061 tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[], const int iMyTriIndex, SGroup * pGroup);
1062 void AddTriToGroup(SGroup * pGroup, const int iTriIndex);
1063
1064 int Build4RuleGroups(STriInfo pTriInfos[], SGroup pGroups[], int piGroupTrianglesBuffer[], const int piTriListIn[], const int iNrTrianglesIn)
1065 {
1066         const int iNrMaxGroups = iNrTrianglesIn*3;
1067         int iNrActiveGroups = 0;
1068         int iOffset = 0, f=0, i=0;
1069         for(f=0; f<iNrTrianglesIn; f++)
1070         {
1071                 for(i=0; i<3; i++)
1072                 {
1073                         // if not assigned to a group
1074                         if((pTriInfos[f].iFlag&GROUP_WITH_ANY)==0 && pTriInfos[f].AssignedGroup[i]==NULL)
1075                         {
1076                                 tbool bOrPre;
1077                                 int neigh_indexL, neigh_indexR;
1078                                 const int vert_index = piTriListIn[f*3+i];
1079                                 assert(iNrActiveGroups<iNrMaxGroups);
1080                                 pTriInfos[f].AssignedGroup[i] = &pGroups[iNrActiveGroups];
1081                                 pTriInfos[f].AssignedGroup[i]->iVertexRepresentitive = vert_index;
1082                                 pTriInfos[f].AssignedGroup[i]->bOrientPreservering = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0;
1083                                 pTriInfos[f].AssignedGroup[i]->iNrFaces = 0;
1084                                 pTriInfos[f].AssignedGroup[i]->pFaceIndices = &piGroupTrianglesBuffer[iOffset];
1085                                 ++iNrActiveGroups;
1086
1087                                 AddTriToGroup(pTriInfos[f].AssignedGroup[i], f);
1088                                 bOrPre = (pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1089                                 neigh_indexL = pTriInfos[f].FaceNeighbors[i];
1090                                 neigh_indexR = pTriInfos[f].FaceNeighbors[i>0?(i-1):2];
1091                                 if(neigh_indexL>=0) // neighbor
1092                                 {
1093                                         const tbool bAnswer =
1094                                                 AssignRecur(piTriListIn, pTriInfos, neigh_indexL,
1095                                                                         pTriInfos[f].AssignedGroup[i] );
1096                                         
1097                                         const tbool bOrPre2 = (pTriInfos[neigh_indexL].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1098                                         const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE;
1099                                         assert(bAnswer || bDiff);
1100                                 }
1101                                 if(neigh_indexR>=0) // neighbor
1102                                 {
1103                                         const tbool bAnswer =
1104                                                 AssignRecur(piTriListIn, pTriInfos, neigh_indexR,
1105                                                                         pTriInfos[f].AssignedGroup[i] );
1106
1107                                         const tbool bOrPre2 = (pTriInfos[neigh_indexR].iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1108                                         const tbool bDiff = bOrPre!=bOrPre2 ? TTRUE : TFALSE;
1109                                         assert(bAnswer || bDiff);
1110                                 }
1111
1112                                 // update offset
1113                                 iOffset += pTriInfos[f].AssignedGroup[i]->iNrFaces;
1114                                 // since the groups are disjoint a triangle can never
1115                                 // belong to more than 3 groups. Subsequently something
1116                                 // is completely screwed if this assertion ever hits.
1117                                 assert(iOffset <= iNrMaxGroups);
1118                         }
1119                 }
1120         }
1121
1122         return iNrActiveGroups;
1123 }
1124
1125 void AddTriToGroup(SGroup * pGroup, const int iTriIndex)
1126 {
1127         pGroup->pFaceIndices[pGroup->iNrFaces] = iTriIndex;
1128         ++pGroup->iNrFaces;
1129 }
1130
1131 tbool AssignRecur(const int piTriListIn[], STriInfo psTriInfos[],
1132                                  const int iMyTriIndex, SGroup * pGroup)
1133 {
1134         STriInfo * pMyTriInfo = &psTriInfos[iMyTriIndex];
1135
1136         // track down vertex
1137         const int iVertRep = pGroup->iVertexRepresentitive;
1138         const int * pVerts = &piTriListIn[3*iMyTriIndex+0];
1139         int i=-1;
1140         if(pVerts[0]==iVertRep) i=0;
1141         else if(pVerts[1]==iVertRep) i=1;
1142         else if(pVerts[2]==iVertRep) i=2;
1143         assert(i>=0 && i<3);
1144
1145         // early out
1146         if(pMyTriInfo->AssignedGroup[i] == pGroup) return TTRUE;
1147         else if(pMyTriInfo->AssignedGroup[i]!=NULL) return TFALSE;
1148         if((pMyTriInfo->iFlag&GROUP_WITH_ANY)!=0)
1149         {
1150                 // first to group with a group-with-anything triangle
1151                 // determines it's orientation.
1152                 // This is the only existing order dependency in the code!!
1153                 if( pMyTriInfo->AssignedGroup[0] == NULL &&
1154                         pMyTriInfo->AssignedGroup[1] == NULL &&
1155                         pMyTriInfo->AssignedGroup[2] == NULL )
1156                 {
1157                         pMyTriInfo->iFlag &= (~ORIENT_PRESERVING);
1158                         pMyTriInfo->iFlag |= (pGroup->bOrientPreservering ? ORIENT_PRESERVING : 0);
1159                 }
1160         }
1161         {
1162                 const tbool bOrient = (pMyTriInfo->iFlag&ORIENT_PRESERVING)!=0 ? TTRUE : TFALSE;
1163                 if(bOrient != pGroup->bOrientPreservering) return TFALSE;
1164         }
1165
1166         AddTriToGroup(pGroup, iMyTriIndex);
1167         pMyTriInfo->AssignedGroup[i] = pGroup;
1168
1169         {
1170                 const int neigh_indexL = pMyTriInfo->FaceNeighbors[i];
1171                 const int neigh_indexR = pMyTriInfo->FaceNeighbors[i>0?(i-1):2];
1172                 if(neigh_indexL>=0)
1173                         AssignRecur(piTriListIn, psTriInfos, neigh_indexL, pGroup);
1174                 if(neigh_indexR>=0)
1175                         AssignRecur(piTriListIn, psTriInfos, neigh_indexR, pGroup);
1176         }
1177
1178
1179
1180         return TTRUE;
1181 }
1182
1183 /////////////////////////////////////////////////////////////////////////////////////////////////////
1184 /////////////////////////////////////////////////////////////////////////////////////////////////////
1185
1186 tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2);
1187 void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed);
1188 STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[], const SMikkTSpaceContext * pContext, const int iVertexRepresentitive);
1189
1190 tbool GenerateTSpaces(STSpace psTspace[], const STriInfo pTriInfos[], const SGroup pGroups[],
1191                                          const int iNrActiveGroups, const int piTriListIn[], const float fThresCos,
1192                                          const SMikkTSpaceContext * pContext)
1193 {
1194         STSpace * pSubGroupTspace = NULL;
1195         SSubGroup * pUniSubGroups = NULL;
1196         int * pTmpMembers = NULL;
1197         int iMaxNrFaces=0, iUniqueTspaces=0, g=0, i=0;
1198         for(g=0; g<iNrActiveGroups; g++)
1199                 if(iMaxNrFaces < pGroups[g].iNrFaces)
1200                         iMaxNrFaces = pGroups[g].iNrFaces;
1201
1202         if(iMaxNrFaces == 0) return TTRUE;
1203
1204         // make initial allocations
1205         pSubGroupTspace = (STSpace *) malloc(sizeof(STSpace)*iMaxNrFaces);
1206         pUniSubGroups = (SSubGroup *) malloc(sizeof(SSubGroup)*iMaxNrFaces);
1207         pTmpMembers = (int *) malloc(sizeof(int)*iMaxNrFaces);
1208         if(pSubGroupTspace==NULL || pUniSubGroups==NULL || pTmpMembers==NULL)
1209         {
1210                 if(pSubGroupTspace!=NULL) free(pSubGroupTspace);        
1211                 if(pUniSubGroups!=NULL) free(pUniSubGroups);    
1212                 if(pTmpMembers!=NULL) free(pTmpMembers);        
1213                 return TFALSE;
1214         }
1215
1216
1217         iUniqueTspaces = 0;
1218         for(g=0; g<iNrActiveGroups; g++)
1219         {
1220                 const SGroup * pGroup = &pGroups[g];
1221                 int iUniqueSubGroups = 0, s=0;
1222
1223                 for(i=0; i<pGroup->iNrFaces; i++)       // triangles
1224                 {
1225                         const int f = pGroup->pFaceIndices[i];  // triangle number
1226                         int index=-1, iVertIndex=-1, iOF_1=-1, iMembers=0, j=0, l=0;
1227                         SSubGroup tmp_group;
1228                         tbool bFound;
1229                         SVec3 n, vOs, vOt;
1230                         if(pTriInfos[f].AssignedGroup[0]==pGroup) index=0;
1231                         else if(pTriInfos[f].AssignedGroup[1]==pGroup) index=1;
1232                         else if(pTriInfos[f].AssignedGroup[2]==pGroup) index=2;
1233                         assert(index>=0 && index<3);
1234
1235                         iVertIndex = piTriListIn[f*3+index];
1236                         assert(iVertIndex==pGroup->iVertexRepresentitive);
1237
1238                         // is normalized already
1239                         n = GetNormal(pContext, iVertIndex);
1240                         
1241                         // project
1242                         vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n));
1243                         vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n));
1244                         if( VNotZero(vOs) ) vOs = Normalize(vOs);
1245                         if( VNotZero(vOt) ) vOt = Normalize(vOt);
1246
1247                         // original face number
1248                         iOF_1 = pTriInfos[f].iOrgFaceNumber;
1249                         
1250                         iMembers = 0;
1251                         for(j=0; j<pGroup->iNrFaces; j++)
1252                         {
1253                                 const int t = pGroup->pFaceIndices[j];  // triangle number
1254                                 const int iOF_2 = pTriInfos[t].iOrgFaceNumber;
1255
1256                                 // project
1257                                 SVec3 vOs2 = vsub(pTriInfos[t].vOs, vscale(vdot(n,pTriInfos[t].vOs), n));
1258                                 SVec3 vOt2 = vsub(pTriInfos[t].vOt, vscale(vdot(n,pTriInfos[t].vOt), n));
1259                                 if( VNotZero(vOs2) ) vOs2 = Normalize(vOs2);
1260                                 if( VNotZero(vOt2) ) vOt2 = Normalize(vOt2);
1261
1262                                 {
1263                                         const tbool bAny = ( (pTriInfos[f].iFlag | pTriInfos[t].iFlag) & GROUP_WITH_ANY )!=0 ? TTRUE : TFALSE;
1264                                         // make sure triangles which belong to the same quad are joined.
1265                                         const tbool bSameOrgFace = iOF_1==iOF_2 ? TTRUE : TFALSE;
1266
1267                                         const float fCosS = vdot(vOs,vOs2);
1268                                         const float fCosT = vdot(vOt,vOt2);
1269
1270                                         assert(f!=t || bSameOrgFace);   // sanity check
1271                                         if(bAny || bSameOrgFace || (fCosS>fThresCos && fCosT>fThresCos))
1272                                                 pTmpMembers[iMembers++] = t;
1273                                 }
1274                         }
1275
1276                         // sort pTmpMembers
1277                         tmp_group.iNrFaces = iMembers;
1278                         tmp_group.pTriMembers = pTmpMembers;
1279                         if(iMembers>1)
1280                         {
1281                                 unsigned int uSeed = INTERNAL_RND_SORT_SEED;    // could replace with a random seed?
1282                                 QuickSort(pTmpMembers, 0, iMembers-1, uSeed);
1283                         }
1284
1285                         // look for an existing match
1286                         bFound = TFALSE;
1287                         l=0;
1288                         while(l<iUniqueSubGroups && !bFound)
1289                         {
1290                                 bFound = CompareSubGroups(&tmp_group, &pUniSubGroups[l]);
1291                                 if(!bFound) ++l;
1292                         }
1293                         
1294                         // assign tangent space index
1295                         assert(bFound || l==iUniqueSubGroups);
1296                         //piTempTangIndices[f*3+index] = iUniqueTspaces+l;
1297
1298                         // if no match was found we allocate a new subgroup
1299                         if(!bFound)
1300                         {
1301                                 // insert new subgroup
1302                                 int * pIndices = (int *) malloc(sizeof(int)*iMembers);
1303                                 if(pIndices==NULL)
1304                                 {
1305                                         // clean up and return false
1306                                         int s=0;
1307                                         for(s=0; s<iUniqueSubGroups; s++)
1308                                                 free(pUniSubGroups[s].pTriMembers);
1309                                         free(pUniSubGroups);
1310                                         free(pTmpMembers);
1311                                         free(pSubGroupTspace);
1312                                         return TFALSE;
1313                                 }
1314                                 pUniSubGroups[iUniqueSubGroups].iNrFaces = iMembers;
1315                                 pUniSubGroups[iUniqueSubGroups].pTriMembers = pIndices;
1316                                 memcpy(pIndices, tmp_group.pTriMembers, iMembers*sizeof(int));
1317                                 pSubGroupTspace[iUniqueSubGroups] =
1318                                         EvalTspace(tmp_group.pTriMembers, iMembers, piTriListIn, pTriInfos, pContext, pGroup->iVertexRepresentitive);
1319                                 ++iUniqueSubGroups;
1320                         }
1321
1322                         // output tspace
1323                         {
1324                                 const int iOffs = pTriInfos[f].iTSpacesOffs;
1325                                 const int iVert = pTriInfos[f].vert_num[index];
1326                                 STSpace * pTS_out = &psTspace[iOffs+iVert];
1327                                 assert(pTS_out->iCounter<2);
1328                                 assert(((pTriInfos[f].iFlag&ORIENT_PRESERVING)!=0) == pGroup->bOrientPreservering);
1329                                 if(pTS_out->iCounter==1)
1330                                 {
1331                                         *pTS_out = AvgTSpace(pTS_out, &pSubGroupTspace[l]);
1332                                         pTS_out->iCounter = 2;  // update counter
1333                                         pTS_out->bOrient = pGroup->bOrientPreservering;
1334                                 }
1335                                 else
1336                                 {
1337                                         assert(pTS_out->iCounter==0);
1338                                         *pTS_out = pSubGroupTspace[l];
1339                                         pTS_out->iCounter = 1;  // update counter
1340                                         pTS_out->bOrient = pGroup->bOrientPreservering;
1341                                 }
1342                         }
1343                 }
1344
1345                 // clean up and offset iUniqueTspaces
1346                 for(s=0; s<iUniqueSubGroups; s++)
1347                         free(pUniSubGroups[s].pTriMembers);
1348                 iUniqueTspaces += iUniqueSubGroups;
1349                 iUniqueSubGroups = 0;
1350         }
1351
1352         // clean up
1353         free(pUniSubGroups);
1354         free(pTmpMembers);
1355         free(pSubGroupTspace);
1356
1357         return TTRUE;
1358 }
1359
1360 STSpace EvalTspace(int face_indices[], const int iFaces, const int piTriListIn[], const STriInfo pTriInfos[],
1361                                    const SMikkTSpaceContext * pContext, const int iVertexRepresentitive)
1362 {
1363         STSpace res;
1364         float fAngleSum = 0;
1365         int face=0;
1366         res.vOs.x=0.0f; res.vOs.y=0.0f; res.vOs.z=0.0f;
1367         res.vOt.x=0.0f; res.vOt.y=0.0f; res.vOt.z=0.0f;
1368         res.fMagS = 0; res.fMagT = 0;
1369
1370         for(face=0; face<iFaces; face++)
1371         {
1372                 const int f = face_indices[face];
1373
1374                 // only valid triangles get to add their contribution
1375                 if( (pTriInfos[f].iFlag&GROUP_WITH_ANY)==0 )
1376                 {
1377                         SVec3 n, vOs, vOt, p0, p1, p2, v1, v2;
1378                         float fCos, fAngle, fMagS, fMagT;
1379                         int i=-1, index=-1, i0=-1, i1=-1, i2=-1;
1380                         if(piTriListIn[3*f+0]==iVertexRepresentitive) i=0;
1381                         else if(piTriListIn[3*f+1]==iVertexRepresentitive) i=1;
1382                         else if(piTriListIn[3*f+2]==iVertexRepresentitive) i=2;
1383                         assert(i>=0 && i<3);
1384
1385                         // project
1386                         index = piTriListIn[3*f+i];
1387                         n = GetNormal(pContext, index);
1388                         vOs = vsub(pTriInfos[f].vOs, vscale(vdot(n,pTriInfos[f].vOs), n));
1389                         vOt = vsub(pTriInfos[f].vOt, vscale(vdot(n,pTriInfos[f].vOt), n));
1390                         if( VNotZero(vOs) ) vOs = Normalize(vOs);
1391                         if( VNotZero(vOt) ) vOt = Normalize(vOt);
1392
1393                         i2 = piTriListIn[3*f + (i<2?(i+1):0)];
1394                         i1 = piTriListIn[3*f + i];
1395                         i0 = piTriListIn[3*f + (i>0?(i-1):2)];
1396
1397                         p0 = GetPosition(pContext, i0);
1398                         p1 = GetPosition(pContext, i1);
1399                         p2 = GetPosition(pContext, i2);
1400                         v1 = vsub(p0,p1);
1401                         v2 = vsub(p2,p1);
1402
1403                         // project
1404                         v1 = vsub(v1, vscale(vdot(n,v1),n)); if( VNotZero(v1) ) v1 = Normalize(v1);
1405                         v2 = vsub(v2, vscale(vdot(n,v2),n)); if( VNotZero(v2) ) v2 = Normalize(v2);
1406
1407                         // weight contribution by the angle
1408                         // between the two edge vectors
1409                         fCos = vdot(v1,v2); fCos=fCos>1?1:(fCos<(-1) ? (-1) : fCos);
1410                         fAngle = (const float) acos(fCos);
1411                         fMagS = pTriInfos[f].fMagS;
1412                         fMagT = pTriInfos[f].fMagT;
1413
1414                         res.vOs=vadd(res.vOs, vscale(fAngle,vOs));
1415                         res.vOt=vadd(res.vOt,vscale(fAngle,vOt));
1416                         res.fMagS+=(fAngle*fMagS);
1417                         res.fMagT+=(fAngle*fMagT);
1418                         fAngleSum += fAngle;
1419                 }
1420         }
1421
1422         // normalize
1423         if( VNotZero(res.vOs) ) res.vOs = Normalize(res.vOs);
1424         if( VNotZero(res.vOt) ) res.vOt = Normalize(res.vOt);
1425         if(fAngleSum>0)
1426         {
1427                 res.fMagS /= fAngleSum;
1428                 res.fMagT /= fAngleSum;
1429         }
1430
1431         return res;
1432 }
1433
1434 tbool CompareSubGroups(const SSubGroup * pg1, const SSubGroup * pg2)
1435 {
1436         tbool bStillSame=TTRUE;
1437         int i=0;
1438         if(pg1->iNrFaces!=pg2->iNrFaces) return TFALSE;
1439         while(i<pg1->iNrFaces && bStillSame)
1440         {
1441                 bStillSame = pg1->pTriMembers[i]==pg2->pTriMembers[i] ? TTRUE : TFALSE;
1442                 if(bStillSame) ++i;
1443         }
1444         return bStillSame;
1445 }
1446
1447 void QuickSort(int* pSortBuffer, int iLeft, int iRight, unsigned int uSeed)
1448 {
1449         int iL, iR, n, index, iMid, iTmp;
1450
1451         // Random
1452         unsigned int t=uSeed&31;
1453         t=(uSeed<<t)|(uSeed>>(32-t));
1454         uSeed=uSeed+t+3;
1455         // Random end
1456
1457         iL=iLeft; iR=iRight;
1458         n = (iR-iL)+1;
1459         assert(n>=0);
1460         index = (int) (uSeed%n);
1461
1462         iMid=pSortBuffer[index + iL];
1463
1464
1465         do
1466         {
1467                 while(pSortBuffer[iL] < iMid)
1468                         ++iL;
1469                 while(pSortBuffer[iR] > iMid)
1470                         --iR;
1471
1472                 if(iL <= iR)
1473                 {
1474                         iTmp = pSortBuffer[iL];
1475                         pSortBuffer[iL] = pSortBuffer[iR];
1476                         pSortBuffer[iR] = iTmp;
1477                         ++iL; --iR;
1478                 }
1479         }
1480         while(iL <= iR);
1481
1482         if(iLeft < iR)
1483                 QuickSort(pSortBuffer, iLeft, iR, uSeed);
1484         if(iL < iRight)
1485                 QuickSort(pSortBuffer, iL, iRight, uSeed);
1486 }
1487
1488 /////////////////////////////////////////////////////////////////////////////////////////////
1489 /////////////////////////////////////////////////////////////////////////////////////////////
1490
1491 void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed);
1492 void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in);
1493
1494 void BuildNeighborsFast(STriInfo pTriInfos[], SEdge * pEdges, const int piTriListIn[], const int iNrTrianglesIn)
1495 {
1496         // build array of edges
1497         unsigned int uSeed = INTERNAL_RND_SORT_SEED;                            // could replace with a random seed?
1498         int iEntries=0, iCurStartIndex=-1, f=0, i=0;
1499         for(f=0; f<iNrTrianglesIn; f++)
1500                 for(i=0; i<3; i++)
1501                 {
1502                         const int i0 = piTriListIn[f*3+i];
1503                         const int i1 = piTriListIn[f*3+(i<2?(i+1):0)];
1504                         pEdges[f*3+i].i0 = i0 < i1 ? i0 : i1;                   // put minimum index in i0
1505                         pEdges[f*3+i].i1 = !(i0 < i1) ? i0 : i1;                // put maximum index in i1
1506                         pEdges[f*3+i].f = f;                                                    // record face number
1507                 }
1508
1509         // sort over all edges by i0, this is the pricy one.
1510         QuickSortEdges(pEdges, 0, iNrTrianglesIn*3-1, 0, uSeed);        // sort channel 0 which is i0
1511
1512         // sub sort over i1, should be fast.
1513         // could replace this with a 64 bit int sort over (i0,i1)
1514         // with i0 as msb in the quicksort call above.
1515         iEntries = iNrTrianglesIn*3;
1516         iCurStartIndex = 0;
1517         for(i=1; i<iEntries; i++)
1518         {
1519                 if(pEdges[iCurStartIndex].i0 != pEdges[i].i0)
1520                 {
1521                         const int iL = iCurStartIndex;
1522                         const int iR = i-1;
1523                         //const int iElems = i-iL;
1524                         iCurStartIndex = i;
1525                         QuickSortEdges(pEdges, iL, iR, 1, uSeed);       // sort channel 1 which is i1
1526                 }
1527         }
1528
1529         // sub sort over f, which should be fast.
1530         // this step is to remain compliant with BuildNeighborsSlow() when
1531         // more than 2 triangles use the same edge (such as a butterfly topology).
1532         iCurStartIndex = 0;
1533         for(i=1; i<iEntries; i++)
1534         {
1535                 if(pEdges[iCurStartIndex].i0 != pEdges[i].i0 || pEdges[iCurStartIndex].i1 != pEdges[i].i1)
1536                 {
1537                         const int iL = iCurStartIndex;
1538                         const int iR = i-1;
1539                         //const int iElems = i-iL;
1540                         iCurStartIndex = i;
1541                         QuickSortEdges(pEdges, iL, iR, 2, uSeed);       // sort channel 2 which is f
1542                 }
1543         }
1544
1545         // pair up, adjacent triangles
1546         for(i=0; i<iEntries; i++)
1547         {
1548                 const int i0=pEdges[i].i0;
1549                 const int i1=pEdges[i].i1;
1550                 const int f = pEdges[i].f;
1551                 tbool bUnassigned_A;
1552
1553                 int i0_A, i1_A;
1554                 int edgenum_A, edgenum_B=0;     // 0,1 or 2
1555                 GetEdge(&i0_A, &i1_A, &edgenum_A, &piTriListIn[f*3], i0, i1);   // resolve index ordering and edge_num
1556                 bUnassigned_A = pTriInfos[f].FaceNeighbors[edgenum_A] == -1 ? TTRUE : TFALSE;
1557
1558                 if(bUnassigned_A)
1559                 {
1560                         // get true index ordering
1561                         int j=i+1, t;
1562                         tbool bNotFound = TTRUE;
1563                         while(j<iEntries && i0==pEdges[j].i0 && i1==pEdges[j].i1 && bNotFound)
1564                         {
1565                                 tbool bUnassigned_B;
1566                                 int i0_B, i1_B;
1567                                 t = pEdges[j].f;
1568                                 // flip i0_B and i1_B
1569                                 GetEdge(&i1_B, &i0_B, &edgenum_B, &piTriListIn[t*3], pEdges[j].i0, pEdges[j].i1);       // resolve index ordering and edge_num
1570                                 //assert(!(i0_A==i1_B && i1_A==i0_B));
1571                                 bUnassigned_B =  pTriInfos[t].FaceNeighbors[edgenum_B]==-1 ? TTRUE : TFALSE;
1572                                 if(i0_A==i0_B && i1_A==i1_B && bUnassigned_B)
1573                                         bNotFound = TFALSE;
1574                                 else
1575                                         ++j;
1576                         }
1577
1578                         if(!bNotFound)
1579                         {
1580                                 int t = pEdges[j].f;
1581                                 pTriInfos[f].FaceNeighbors[edgenum_A] = t;
1582                                 //assert(pTriInfos[t].FaceNeighbors[edgenum_B]==-1);
1583                                 pTriInfos[t].FaceNeighbors[edgenum_B] = f;
1584                         }
1585                 }
1586         }
1587 }
1588
1589 void BuildNeighborsSlow(STriInfo pTriInfos[], const int piTriListIn[], const int iNrTrianglesIn)
1590 {
1591         int f=0, i=0;
1592         for(f=0; f<iNrTrianglesIn; f++)
1593         {
1594                 for(i=0; i<3; i++)
1595                 {
1596                         // if unassigned
1597                         if(pTriInfos[f].FaceNeighbors[i] == -1)
1598                         {
1599                                 const int i0_A = piTriListIn[f*3+i];
1600                                 const int i1_A = piTriListIn[f*3+(i<2?(i+1):0)];
1601
1602                                 // search for a neighbor
1603                                 tbool bFound = TFALSE;
1604                                 int t=0, j=0;
1605                                 while(!bFound && t<iNrTrianglesIn)
1606                                 {
1607                                         if(t!=f)
1608                                         {
1609                                                 j=0;
1610                                                 while(!bFound && j<3)
1611                                                 {
1612                                                         // in rev order
1613                                                         const int i1_B = piTriListIn[t*3+j];
1614                                                         const int i0_B = piTriListIn[t*3+(j<2?(j+1):0)];
1615                                                         //assert(!(i0_A==i1_B && i1_A==i0_B));
1616                                                         if(i0_A==i0_B && i1_A==i1_B)
1617                                                                 bFound = TTRUE;
1618                                                         else
1619                                                                 ++j;
1620                                                 }
1621                                         }
1622                                         
1623                                         if(!bFound) ++t;
1624                                 }
1625
1626                                 // assign neighbors
1627                                 if(bFound)
1628                                 {
1629                                         pTriInfos[f].FaceNeighbors[i] = t;
1630                                         //assert(pTriInfos[t].FaceNeighbors[j]==-1);
1631                                         pTriInfos[t].FaceNeighbors[j] = f;
1632                                 }
1633                         }
1634                 }
1635         }
1636 }
1637
1638 void QuickSortEdges(SEdge * pSortBuffer, int iLeft, int iRight, const int channel, unsigned int uSeed)
1639 {
1640         unsigned int t;
1641         int iL, iR, n, index, iMid;
1642
1643         // early out
1644         SEdge sTmp;
1645         const int iElems = iRight-iLeft+1;
1646         if(iElems<2) return;
1647         else if(iElems==2)
1648         {
1649                 if(pSortBuffer[iLeft].array[channel] > pSortBuffer[iRight].array[channel])
1650                 {
1651                         sTmp = pSortBuffer[iLeft];
1652                         pSortBuffer[iLeft] = pSortBuffer[iRight];
1653                         pSortBuffer[iRight] = sTmp;
1654                 }
1655                 return;
1656         }
1657
1658         // Random
1659         t=uSeed&31;
1660         t=(uSeed<<t)|(uSeed>>(32-t));
1661         uSeed=uSeed+t+3;
1662         // Random end
1663
1664         iL=iLeft, iR=iRight;
1665         n = (iR-iL)+1;
1666         assert(n>=0);
1667         index = (int) (uSeed%n);
1668
1669         iMid=pSortBuffer[index + iL].array[channel];
1670
1671         do
1672         {
1673                 while(pSortBuffer[iL].array[channel] < iMid)
1674                         ++iL;
1675                 while(pSortBuffer[iR].array[channel] > iMid)
1676                         --iR;
1677
1678                 if(iL <= iR)
1679                 {
1680                         sTmp = pSortBuffer[iL];
1681                         pSortBuffer[iL] = pSortBuffer[iR];
1682                         pSortBuffer[iR] = sTmp;
1683                         ++iL; --iR;
1684                 }
1685         }
1686         while(iL <= iR);
1687
1688         if(iLeft < iR)
1689                 QuickSortEdges(pSortBuffer, iLeft, iR, channel, uSeed);
1690         if(iL < iRight)
1691                 QuickSortEdges(pSortBuffer, iL, iRight, channel, uSeed);
1692 }
1693
1694 // resolve ordering and edge number
1695 void GetEdge(int * i0_out, int * i1_out, int * edgenum_out, const int indices[], const int i0_in, const int i1_in)
1696 {
1697         *edgenum_out = -1;
1698         
1699         // test if first index is on the edge
1700         if(indices[0]==i0_in || indices[0]==i1_in)
1701         {
1702                 // test if second index is on the edge
1703                 if(indices[1]==i0_in || indices[1]==i1_in)
1704                 {
1705                         edgenum_out[0]=0;       // first edge
1706                         i0_out[0]=indices[0];
1707                         i1_out[0]=indices[1];
1708                 }
1709                 else
1710                 {
1711                         edgenum_out[0]=2;       // third edge
1712                         i0_out[0]=indices[2];
1713                         i1_out[0]=indices[0];
1714                 }
1715         }
1716         else
1717         {
1718                 // only second and third index is on the edge
1719                 edgenum_out[0]=1;       // second edge
1720                 i0_out[0]=indices[1];
1721                 i1_out[0]=indices[2];
1722         }
1723 }
1724
1725
1726 /////////////////////////////////////////////////////////////////////////////////////////////
1727 /////////////////////////////////// Degenerate triangles ////////////////////////////////////
1728
1729 void DegenPrologue(STriInfo pTriInfos[], int piTriList_out[], const int iNrTrianglesIn, const int iTotTris)
1730 {
1731         int iNextGoodTriangleSearchIndex=-1;
1732         tbool bStillFindingGoodOnes;
1733
1734         // locate quads with only one good triangle
1735         int t=0;
1736         while(t<(iTotTris-1))
1737         {
1738                 const int iFO_a = pTriInfos[t].iOrgFaceNumber;
1739                 const int iFO_b = pTriInfos[t+1].iOrgFaceNumber;
1740                 if(iFO_a==iFO_b)        // this is a quad
1741                 {
1742                         const tbool bIsDeg_a = (pTriInfos[t].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;
1743                         const tbool bIsDeg_b = (pTriInfos[t+1].iFlag&MARK_DEGENERATE)!=0 ? TTRUE : TFALSE;
1744                         if((bIsDeg_a^bIsDeg_b)!=0)
1745                         {
1746                                 pTriInfos[t].iFlag |= QUAD_ONE_DEGEN_TRI;
1747                                 pTriInfos[t+1].iFlag |= QUAD_ONE_DEGEN_TRI;
1748                         }
1749                         t += 2;
1750                 }
1751                 else
1752                         ++t;
1753         }
1754
1755         // reorder list so all degen triangles are moved to the back
1756         // without reordering the good triangles
1757         iNextGoodTriangleSearchIndex = 1;
1758         t=0;
1759         bStillFindingGoodOnes = TTRUE;
1760         while(t<iNrTrianglesIn && bStillFindingGoodOnes)
1761         {
1762                 const tbool bIsGood = (pTriInfos[t].iFlag&MARK_DEGENERATE)==0 ? TTRUE : TFALSE;
1763                 if(bIsGood)
1764                 {
1765                         if(iNextGoodTriangleSearchIndex < (t+2))
1766                                 iNextGoodTriangleSearchIndex = t+2;
1767                 }
1768                 else
1769                 {
1770                         int t0, t1;
1771                         // search for the first good triangle.
1772                         tbool bJustADegenerate = TTRUE;
1773                         while(bJustADegenerate && iNextGoodTriangleSearchIndex<iTotTris)
1774                         {
1775                                 const tbool bIsGood = (pTriInfos[iNextGoodTriangleSearchIndex].iFlag&MARK_DEGENERATE)==0 ? TTRUE : TFALSE;
1776                                 if(bIsGood) bJustADegenerate=TFALSE;
1777                                 else ++iNextGoodTriangleSearchIndex;
1778                         }
1779
1780                         t0 = t;
1781                         t1 = iNextGoodTriangleSearchIndex;
1782                         ++iNextGoodTriangleSearchIndex;
1783                         assert(iNextGoodTriangleSearchIndex > (t+1));
1784
1785                         // swap triangle t0 and t1
1786                         if(!bJustADegenerate)
1787                         {
1788                                 int i=0;
1789                                 for(i=0; i<3; i++)
1790                                 {
1791                                         const int index = piTriList_out[t0*3+i];
1792                                         piTriList_out[t0*3+i] = piTriList_out[t1*3+i];
1793                                         piTriList_out[t1*3+i] = index;
1794                                 }
1795                                 {
1796                                         const STriInfo tri_info = pTriInfos[t0];
1797                                         pTriInfos[t0] = pTriInfos[t1];
1798                                         pTriInfos[t1] = tri_info;
1799                                 }
1800                         }
1801                         else
1802                                 bStillFindingGoodOnes = TFALSE; // this is not supposed to happen
1803                 }
1804
1805                 if(bStillFindingGoodOnes) ++t;
1806         }
1807
1808         assert(bStillFindingGoodOnes);  // code will still work.
1809         assert(iNrTrianglesIn == t);
1810 }
1811
1812 void DegenEpilogue(STSpace psTspace[], STriInfo pTriInfos[], int piTriListIn[], const SMikkTSpaceContext * pContext, const int iNrTrianglesIn, const int iTotTris)
1813 {
1814         int t=0, i=0;
1815         // deal with degenerate triangles
1816         // punishment for degenerate triangles is O(N^2)
1817         for(t=iNrTrianglesIn; t<iTotTris; t++)
1818         {
1819                 // degenerate triangles on a quad with one good triangle are skipped
1820                 // here but processed in the next loop
1821                 const tbool bSkip = (pTriInfos[t].iFlag&QUAD_ONE_DEGEN_TRI)!=0 ? TTRUE : TFALSE;
1822
1823                 if(!bSkip)
1824                 {
1825                         for(i=0; i<3; i++)
1826                         {
1827                                 const int index1 = piTriListIn[t*3+i];
1828                                 // search through the good triangles
1829                                 tbool bNotFound = TTRUE;
1830                                 int j=0;
1831                                 while(bNotFound && j<(3*iNrTrianglesIn))
1832                                 {
1833                                         const int index2 = piTriListIn[j];
1834                                         if(index1==index2) bNotFound=TFALSE;
1835                                         else ++j;
1836                                 }
1837
1838                                 if(!bNotFound)
1839                                 {
1840                                         const int iTri = j/3;
1841                                         const int iVert = j%3;
1842                                         const int iSrcVert=pTriInfos[iTri].vert_num[iVert];
1843                                         const int iSrcOffs=pTriInfos[iTri].iTSpacesOffs;
1844                                         const int iDstVert=pTriInfos[t].vert_num[i];
1845                                         const int iDstOffs=pTriInfos[t].iTSpacesOffs;
1846                                         
1847                                         // copy tspace
1848                                         psTspace[iDstOffs+iDstVert] = psTspace[iSrcOffs+iSrcVert];
1849                                 }
1850                         }
1851                 }
1852         }
1853
1854         // deal with degenerate quads with one good triangle
1855         for(t=0; t<iNrTrianglesIn; t++)
1856         {
1857                 // this triangle belongs to a quad where the
1858                 // other triangle is degenerate
1859                 if( (pTriInfos[t].iFlag&QUAD_ONE_DEGEN_TRI)!=0 )
1860                 {
1861                         SVec3 vDstP;
1862                         int iOrgF=-1, i=0;
1863                         tbool bNotFound;
1864                         unsigned char * pV = pTriInfos[t].vert_num;
1865                         int iFlag = (1<<pV[0]) | (1<<pV[1]) | (1<<pV[2]);
1866                         int iMissingIndex = 0;
1867                         if((iFlag&2)==0) iMissingIndex=1;
1868                         else if((iFlag&4)==0) iMissingIndex=2;
1869                         else if((iFlag&8)==0) iMissingIndex=3;
1870
1871                         iOrgF = pTriInfos[t].iOrgFaceNumber;
1872                         vDstP = GetPosition(pContext, MakeIndex(iOrgF, iMissingIndex));
1873                         bNotFound = TTRUE;
1874                         i=0;
1875                         while(bNotFound && i<3)
1876                         {
1877                                 const int iVert = pV[i];
1878                                 const SVec3 vSrcP = GetPosition(pContext, MakeIndex(iOrgF, iVert));
1879                                 if(veq(vSrcP, vDstP)==TTRUE)
1880                                 {
1881                                         const int iOffs = pTriInfos[t].iTSpacesOffs;
1882                                         psTspace[iOffs+iMissingIndex] = psTspace[iOffs+iVert];
1883                                         bNotFound=TFALSE;
1884                                 }
1885                                 else
1886                                         ++i;
1887                         }
1888                         assert(!bNotFound);
1889                 }
1890         }
1891 }