]> de.git.xonotic.org Git - xonotic/netradiant.git/blob - tools/quake3/q3map2/surface_meta.c
q3map2: use safe_malloc0 when safe_malloc is followed by a memset to 0 with the same...
[xonotic/netradiant.git] / tools / quake3 / q3map2 / surface_meta.c
1 /* -------------------------------------------------------------------------------
2
3    Copyright (C) 1999-2007 id Software, Inc. and contributors.
4    For a list of contributors, see the accompanying CONTRIBUTORS file.
5
6    This file is part of GtkRadiant.
7
8    GtkRadiant is free software; you can redistribute it and/or modify
9    it under the terms of the GNU General Public License as published by
10    the Free Software Foundation; either version 2 of the License, or
11    (at your option) any later version.
12
13    GtkRadiant is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with GtkRadiant; if not, write to the Free Software
20    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
21
22    ----------------------------------------------------------------------------------
23
24    This code has been altered significantly from its original form, to support
25    several games based on the Quake III Arena engine, in the form of "Q3Map2."
26
27    ------------------------------------------------------------------------------- */
28
29
30
31 /* marker */
32 #define SURFACE_META_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 #define LIGHTMAP_EXCEEDED   -1
42 #define S_EXCEEDED          -2
43 #define T_EXCEEDED          -3
44 #define ST_EXCEEDED         -4
45 #define UNSUITABLE_TRIANGLE -10
46 #define VERTS_EXCEEDED      -1000
47 #define INDEXES_EXCEEDED    -2000
48
49 #define GROW_META_VERTS     1024
50 #define GROW_META_TRIANGLES 1024
51
52 static int numMetaSurfaces, numPatchMetaSurfaces;
53
54 static int maxMetaVerts = 0;
55 static int numMetaVerts = 0;
56 static int firstSearchMetaVert = 0;
57 static bspDrawVert_t        *metaVerts = NULL;
58
59 static int maxMetaTriangles = 0;
60 static int numMetaTriangles = 0;
61 static metaTriangle_t       *metaTriangles = NULL;
62
63
64
65 /*
66    ClearMetaVertexes()
67    called before staring a new entity to clear out the triangle list
68  */
69
70 void ClearMetaTriangles( void ){
71         numMetaVerts = 0;
72         numMetaTriangles = 0;
73 }
74
75
76
77 /*
78    FindMetaVertex()
79    finds a matching metavertex in the global list, returning its index
80  */
81
82 static int FindMetaVertex( bspDrawVert_t *src ){
83         int i;
84         bspDrawVert_t   *v, *temp;
85
86
87         /* try to find an existing drawvert */
88         for ( i = firstSearchMetaVert, v = &metaVerts[ i ]; i < numMetaVerts; i++, v++ )
89         {
90                 if ( memcmp( src, v, sizeof( bspDrawVert_t ) ) == 0 ) {
91                         return i;
92                 }
93         }
94
95         /* enough space? */
96         if ( numMetaVerts >= maxMetaVerts ) {
97                 /* reallocate more room */
98                 maxMetaVerts += GROW_META_VERTS;
99                 temp = safe_malloc( maxMetaVerts * sizeof( bspDrawVert_t ) );
100                 if ( metaVerts != NULL ) {
101                         memcpy( temp, metaVerts, numMetaVerts * sizeof( bspDrawVert_t ) );
102                         free( metaVerts );
103                 }
104                 metaVerts = temp;
105         }
106
107         /* add the triangle */
108         memcpy( &metaVerts[ numMetaVerts ], src, sizeof( bspDrawVert_t ) );
109         numMetaVerts++;
110
111         /* return the count */
112         return ( numMetaVerts - 1 );
113 }
114
115
116
117 /*
118    AddMetaTriangle()
119    adds a new meta triangle, allocating more memory if necessary
120  */
121
122 static int AddMetaTriangle( void ){
123         metaTriangle_t  *temp;
124
125
126         /* enough space? */
127         if ( numMetaTriangles >= maxMetaTriangles ) {
128                 /* reallocate more room */
129                 maxMetaTriangles += GROW_META_TRIANGLES;
130                 temp = safe_malloc( maxMetaTriangles * sizeof( metaTriangle_t ) );
131                 if ( metaTriangles != NULL ) {
132                         memcpy( temp, metaTriangles, numMetaTriangles * sizeof( metaTriangle_t ) );
133                         free( metaTriangles );
134                 }
135                 metaTriangles = temp;
136         }
137
138         /* increment and return */
139         numMetaTriangles++;
140         return numMetaTriangles - 1;
141 }
142
143
144
145 /*
146    FindMetaTriangle()
147    finds a matching metatriangle in the global list,
148    otherwise adds it and returns the index to the metatriangle
149  */
150
151 int FindMetaTriangle( metaTriangle_t *src, bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *c, int planeNum ){
152         int triIndex;
153         vec3_t dir;
154
155
156
157         /* detect degenerate triangles fixme: do something proper here */
158         VectorSubtract( a->xyz, b->xyz, dir );
159         if ( VectorLength( dir ) < 0.125f ) {
160                 return -1;
161         }
162         VectorSubtract( b->xyz, c->xyz, dir );
163         if ( VectorLength( dir ) < 0.125f ) {
164                 return -1;
165         }
166         VectorSubtract( c->xyz, a->xyz, dir );
167         if ( VectorLength( dir ) < 0.125f ) {
168                 return -1;
169         }
170
171         /* find plane */
172         if ( planeNum >= 0 ) {
173                 /* because of precision issues with small triangles, try to use the specified plane */
174                 src->planeNum = planeNum;
175                 VectorCopy( mapplanes[ planeNum ].normal, src->plane );
176                 src->plane[ 3 ] = mapplanes[ planeNum ].dist;
177         }
178         else
179         {
180                 /* calculate a plane from the triangle's points (and bail if a plane can't be constructed) */
181                 src->planeNum = -1;
182                 if ( PlaneFromPoints( src->plane, a->xyz, b->xyz, c->xyz ) == qfalse ) {
183                         return -1;
184                 }
185         }
186
187         /* ydnar 2002-10-03: repair any bogus normals (busted ase import kludge) */
188         if ( VectorLength( a->normal ) <= 0.0f ) {
189                 VectorCopy( src->plane, a->normal );
190         }
191         if ( VectorLength( b->normal ) <= 0.0f ) {
192                 VectorCopy( src->plane, b->normal );
193         }
194         if ( VectorLength( c->normal ) <= 0.0f ) {
195                 VectorCopy( src->plane, c->normal );
196         }
197
198         /* ydnar 2002-10-04: set lightmap axis if not already set */
199         if ( !( src->si->compileFlags & C_VERTEXLIT ) &&
200                  src->lightmapAxis[ 0 ] == 0.0f && src->lightmapAxis[ 1 ] == 0.0f && src->lightmapAxis[ 2 ] == 0.0f ) {
201                 /* the shader can specify an explicit lightmap axis */
202                 if ( src->si->lightmapAxis[ 0 ] || src->si->lightmapAxis[ 1 ] || src->si->lightmapAxis[ 2 ] ) {
203                         VectorCopy( src->si->lightmapAxis, src->lightmapAxis );
204                 }
205
206                 /* new axis-finding code */
207                 else{
208                         CalcLightmapAxis( src->plane, src->lightmapAxis );
209                 }
210         }
211
212         /* fill out the src triangle */
213         src->indexes[ 0 ] = FindMetaVertex( a );
214         src->indexes[ 1 ] = FindMetaVertex( b );
215         src->indexes[ 2 ] = FindMetaVertex( c );
216
217         /* try to find an existing triangle */
218         #ifdef USE_EXHAUSTIVE_SEARCH
219         {
220                 int i;
221                 metaTriangle_t  *tri;
222
223
224                 for ( i = 0, tri = metaTriangles; i < numMetaTriangles; i++, tri++ )
225                 {
226                         if ( memcmp( src, tri, sizeof( metaTriangle_t ) ) == 0 ) {
227                                 return i;
228                         }
229                 }
230         }
231         #endif
232
233         /* get a new triangle */
234         triIndex = AddMetaTriangle();
235
236         /* add the triangle */
237         memcpy( &metaTriangles[ triIndex ], src, sizeof( metaTriangle_t ) );
238
239         /* return the triangle index */
240         return triIndex;
241 }
242
243
244
245 /*
246    SurfaceToMetaTriangles()
247    converts a classified surface to metatriangles
248  */
249
250 static void SurfaceToMetaTriangles( mapDrawSurface_t *ds ){
251         int i;
252         metaTriangle_t src;
253         bspDrawVert_t a, b, c;
254
255
256         /* only handle certain types of surfaces */
257         if ( ds->type != SURFACE_FACE &&
258                  ds->type != SURFACE_META &&
259                  ds->type != SURFACE_FORCED_META &&
260                  ds->type != SURFACE_DECAL ) {
261                 return;
262         }
263
264         /* speed at the expense of memory */
265         firstSearchMetaVert = numMetaVerts;
266
267         /* only handle valid surfaces */
268         if ( ds->type != SURFACE_BAD && ds->numVerts >= 3 && ds->numIndexes >= 3 ) {
269                 /* walk the indexes and create triangles */
270                 for ( i = 0; i < ds->numIndexes; i += 3 )
271                 {
272                         /* sanity check the indexes */
273                         if ( ds->indexes[ i ] == ds->indexes[ i + 1 ] ||
274                                  ds->indexes[ i ] == ds->indexes[ i + 2 ] ||
275                                  ds->indexes[ i + 1 ] == ds->indexes[ i + 2 ] ) {
276                                 //%     Sys_Printf( "%d! ", ds->numVerts );
277                                 continue;
278                         }
279
280                         /* build a metatriangle */
281                         src.si = ds->shaderInfo;
282                         src.side = ( ds->sideRef != NULL ? ds->sideRef->side : NULL );
283                         src.entityNum = ds->entityNum;
284                         src.surfaceNum = ds->surfaceNum;
285                         src.planeNum = ds->planeNum;
286                         src.castShadows = ds->castShadows;
287                         src.recvShadows = ds->recvShadows;
288                         src.fogNum = ds->fogNum;
289                         src.sampleSize = ds->sampleSize;
290                         src.shadeAngleDegrees = ds->shadeAngleDegrees;
291                         VectorCopy( ds->lightmapAxis, src.lightmapAxis );
292
293                         /* copy drawverts */
294                         memcpy( &a, &ds->verts[ ds->indexes[ i ] ], sizeof( a ) );
295                         memcpy( &b, &ds->verts[ ds->indexes[ i + 1 ] ], sizeof( b ) );
296                         memcpy( &c, &ds->verts[ ds->indexes[ i + 2 ] ], sizeof( c ) );
297                         FindMetaTriangle( &src, &a, &b, &c, ds->planeNum );
298                 }
299
300                 /* add to count */
301                 numMetaSurfaces++;
302         }
303
304         /* clear the surface (free verts and indexes, sets it to SURFACE_BAD) */
305         ClearSurface( ds );
306 }
307
308
309
310 /*
311    TriangulatePatchSurface()
312    creates triangles from a patch
313  */
314
315 void TriangulatePatchSurface( entity_t *e, mapDrawSurface_t *ds ){
316         int iterations, x, y, pw[ 5 ], r;
317         mapDrawSurface_t    *dsNew;
318         mesh_t src, *subdivided, *mesh;
319         int forcePatchMeta;
320         int patchQuality;
321         int patchSubdivision;
322
323         /* vortex: _patchMeta, _patchQuality, _patchSubdivide support */
324         forcePatchMeta = IntForKey( e, "_patchMeta" );
325         if ( !forcePatchMeta ) {
326                 forcePatchMeta = IntForKey( e, "patchMeta" );
327         }
328         patchQuality = IntForKey( e, "_patchQuality" );
329         if ( !patchQuality ) {
330                 patchQuality = IntForKey( e, "patchQuality" );
331         }
332         if ( !patchQuality ) {
333                 patchQuality = 1.0;
334         }
335         patchSubdivision = IntForKey( e, "_patchSubdivide" );
336         if ( !patchSubdivision ) {
337                 patchSubdivision = IntForKey( e, "patchSubdivide" );
338         }
339
340         /* try to early out */
341         if ( ds->numVerts == 0 || ds->type != SURFACE_PATCH || ( patchMeta == qfalse && !forcePatchMeta ) ) {
342                 return;
343         }
344
345         /* make a mesh from the drawsurf */
346         src.width = ds->patchWidth;
347         src.height = ds->patchHeight;
348         src.verts = ds->verts;
349         //%     subdivided = SubdivideMesh( src, 8, 999 );
350         if ( patchSubdivision ) {
351                 iterations = IterationsForCurve( ds->longestCurve, patchSubdivision );
352         }
353         else{
354                 iterations = IterationsForCurve( ds->longestCurve, patchSubdivisions / patchQuality );
355         }
356
357         subdivided = SubdivideMesh2( src, iterations ); //%     ds->maxIterations
358
359         /* fit it to the curve and remove colinear verts on rows/columns */
360         PutMeshOnCurve( *subdivided );
361         mesh = RemoveLinearMeshColumnsRows( subdivided );
362         FreeMesh( subdivided );
363         //% MakeMeshNormals( mesh );
364
365         /* make a copy of the drawsurface */
366         dsNew = AllocDrawSurface( SURFACE_META );
367         memcpy( dsNew, ds, sizeof( *ds ) );
368
369         /* if the patch is nonsolid, then discard it */
370         if ( !( ds->shaderInfo->compileFlags & C_SOLID ) ) {
371                 ClearSurface( ds );
372         }
373
374         /* set new pointer */
375         ds = dsNew;
376
377         /* basic transmogrification */
378         ds->type = SURFACE_META;
379         ds->numIndexes = 0;
380         ds->indexes = safe_malloc( mesh->width * mesh->height * 6 * sizeof( int ) );
381
382         /* copy the verts in */
383         ds->numVerts = ( mesh->width * mesh->height );
384         ds->verts = mesh->verts;
385
386         /* iterate through the mesh quads */
387         for ( y = 0; y < ( mesh->height - 1 ); y++ )
388         {
389                 for ( x = 0; x < ( mesh->width - 1 ); x++ )
390                 {
391                         /* set indexes */
392                         pw[ 0 ] = x + ( y * mesh->width );
393                         pw[ 1 ] = x + ( ( y + 1 ) * mesh->width );
394                         pw[ 2 ] = x + 1 + ( ( y + 1 ) * mesh->width );
395                         pw[ 3 ] = x + 1 + ( y * mesh->width );
396                         pw[ 4 ] = x + ( y * mesh->width );    /* same as pw[ 0 ] */
397
398                         /* set radix */
399                         r = ( x + y ) & 1;
400
401                         /* make first triangle */
402                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 0 ];
403                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 1 ];
404                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 2 ];
405
406                         /* make second triangle */
407                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 0 ];
408                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 2 ];
409                         ds->indexes[ ds->numIndexes++ ] = pw[ r + 3 ];
410                 }
411         }
412
413         /* free the mesh, but not the verts */
414         free( mesh );
415
416         /* add to count */
417         numPatchMetaSurfaces++;
418
419         /* classify it */
420         ClassifySurfaces( 1, ds );
421 }
422
423
424
425 #define TINY_AREA 1.0f
426 #define MAXAREA_MAXTRIES 8
427 int MaxAreaIndexes( bspDrawVert_t *vert, int cnt, int *indexes ){
428         int r, s, t, bestR = 0, bestS = 1, bestT = 2;
429         int i, j, try;
430         double A, bestA = -1, V, bestV = -1;
431         vec3_t ab, ac, bc, cross;
432         bspDrawVert_t *buf;
433         double shiftWidth;
434
435         if ( cnt < 3 ) {
436                 return 0;
437         }
438
439         /* calculate total area */
440         A = 0;
441         for ( i = 1; i + 1 < cnt; ++i )
442         {
443                 VectorSubtract( vert[i].xyz, vert[0].xyz, ab );
444                 VectorSubtract( vert[i + 1].xyz, vert[0].xyz, ac );
445                 CrossProduct( ab, ac, cross );
446                 A += VectorLength( cross );
447         }
448         V = 0;
449         for ( i = 0; i < cnt; ++i )
450         {
451                 VectorSubtract( vert[( i + 1 ) % cnt].xyz, vert[i].xyz, ab );
452                 V += VectorLength( ab );
453         }
454
455         /* calculate shift width from the area sensibly, assuming the polygon
456          * fits about 25% of the screen in both dimensions
457          * we assume 1280x1024
458          * 1 pixel is then about sqrt(A) / (0.25 * screenwidth)
459          * 8 pixels are then about sqrt(A) /  (0.25 * 1280) * 8
460          * 8 pixels are then about sqrt(A) * 0.025
461          * */
462         shiftWidth = sqrt( A ) * 0.0125;
463         /*     3->1 6->2 12->3 ... */
464         if ( A - ceil( log( cnt / 1.5 ) / log( 2 ) ) * V * shiftWidth * 2 < 0 ) {
465                 /* printf("Small triangle detected (area %f, circumference %f), adjusting shiftWidth from %f to ", A, V, shiftWidth); */
466                 shiftWidth = A / ( ceil( log( cnt / 1.5 ) / log( 2 ) ) * V * 2 );
467                 /* printf("%f\n", shiftWidth); */
468         }
469
470         /* find the triangle with highest area */
471         for ( r = 0; r + 2 < cnt; ++r )
472                 for ( s = r + 1; s + 1 < cnt; ++s )
473                         for ( t = s + 1; t < cnt; ++t )
474                         {
475                                 VectorSubtract( vert[s].xyz, vert[r].xyz, ab );
476                                 VectorSubtract( vert[t].xyz, vert[r].xyz, ac );
477                                 VectorSubtract( vert[t].xyz, vert[s].xyz, bc );
478                                 CrossProduct( ab, ac, cross );
479                                 A = VectorLength( cross );
480
481                                 V = A - ( VectorLength( ab ) - VectorLength( ac ) - VectorLength( bc ) ) * shiftWidth;
482                                 /* value = A - circumference * shiftWidth, i.e. we back out by shiftWidth units from each side, to prevent too acute triangles */
483                                 /* this kind of simulates "number of shiftWidth*shiftWidth fragments in the triangle not touched by an edge" */
484
485                                 if ( bestA < 0 || V > bestV ) {
486                                         bestA = A;
487                                         bestV = V;
488                                         bestR = r;
489                                         bestS = s;
490                                         bestT = t;
491                                 }
492                         }
493
494         /*
495            if(bestV < 0)
496             printf("value was REALLY bad\n");
497          */
498
499         for ( try = 0; try < MAXAREA_MAXTRIES; ++try )
500         {
501                 if ( try ) {
502                         bestR = rand() % cnt;
503                         bestS = rand() % cnt;
504                         bestT = rand() % cnt;
505                         if ( bestR == bestS || bestR == bestT || bestS == bestT ) {
506                                 continue;
507                         }
508                         // bubblesort inline
509                         // abc acb bac bca cab cba
510                         if ( bestR > bestS ) {
511                                 j = bestR;
512                                 bestR = bestS;
513                                 bestS = j;
514                         }
515                         // abc acb abc bca acb bca
516                         if ( bestS > bestT ) {
517                                 j = bestS;
518                                 bestS = bestT;
519                                 bestT = j;
520                         }
521                         // abc abc abc bac abc bac
522                         if ( bestR > bestS ) {
523                                 j = bestR;
524                                 bestR = bestS;
525                                 bestS = j;
526                         }
527                         // abc abc abc abc abc abc
528
529                         VectorSubtract( vert[bestS].xyz, vert[bestR].xyz, ab );
530                         VectorSubtract( vert[bestT].xyz, vert[bestR].xyz, ac );
531                         CrossProduct( ab, ac, cross );
532                         bestA = VectorLength( cross );
533                 }
534
535                 if ( bestA < TINY_AREA ) {
536                         /* the biggest triangle is degenerate - then every other is too, and the other algorithms wouldn't generate anything useful either */
537                         continue;
538                 }
539
540                 i = 0;
541                 indexes[i++] = bestR;
542                 indexes[i++] = bestS;
543                 indexes[i++] = bestT;
544                 /* uses 3 */
545
546                 /* identify the other fragments */
547
548                 /* full polygon without triangle (bestR,bestS,bestT) = three new polygons:
549                  * 1. bestR..bestS
550                  * 2. bestS..bestT
551                  * 3. bestT..bestR
552                  */
553
554                 j = MaxAreaIndexes( vert + bestR, bestS - bestR + 1, indexes + i );
555                 if ( j < 0 ) {
556                         continue;
557                 }
558                 j += i;
559                 for (; i < j; ++i )
560                         indexes[i] += bestR;
561                 /* uses 3*(bestS-bestR+1)-6 */
562                 j = MaxAreaIndexes( vert + bestS, bestT - bestS + 1, indexes + i );
563                 if ( j < 0 ) {
564                         continue;
565                 }
566                 j += i;
567                 for (; i < j; ++i )
568                         indexes[i] += bestS;
569                 /* uses 3*(bestT-bestS+1)-6 */
570
571                 /* can'bestT recurse this one directly... therefore, buffering */
572                 if ( cnt + bestR - bestT + 1 >= 3 ) {
573                         buf = safe_malloc( sizeof( *vert ) * ( cnt + bestR - bestT + 1 ) );
574                         memcpy( buf, vert + bestT, sizeof( *vert ) * ( cnt - bestT ) );
575                         memcpy( buf + ( cnt - bestT ), vert, sizeof( *vert ) * ( bestR + 1 ) );
576                         j = MaxAreaIndexes( buf, cnt + bestR - bestT + 1, indexes + i );
577                         if ( j < 0 ) {
578                                 free( buf );
579                                 continue;
580                         }
581                         j += i;
582                         for (; i < j; ++i )
583                                 indexes[i] = ( indexes[i] + bestT ) % cnt;
584                         /* uses 3*(cnt+bestR-bestT+1)-6 */
585                         free( buf );
586                 }
587
588                 /* together 3 + 3*(cnt+3) - 18 = 3*cnt-6 q.e.d. */
589                 return i;
590         }
591
592         return -1;
593 }
594
595
596
597 /*
598    MaxAreaFaceSurface() - divVerent
599    creates a triangle list using max area indexes
600  */
601
602 void MaxAreaFaceSurface( mapDrawSurface_t *ds ){
603         int n;
604         /* try to early out  */
605         if ( !ds->numVerts || ( ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL ) ) {
606                 return;
607         }
608
609         /* is this a simple triangle? */
610         if ( ds->numVerts == 3 ) {
611                 ds->numIndexes = 3;
612                 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
613                 VectorSet( ds->indexes, 0, 1, 2 );
614                 numMaxAreaSurfaces++;
615                 return;
616         }
617
618         /* do it! */
619         ds->numIndexes = 3 * ds->numVerts - 6;
620         ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
621         n = MaxAreaIndexes( ds->verts, ds->numVerts, ds->indexes );
622         if ( n < 0 ) {
623                 /* whatever we do, it's degenerate */
624                 free( ds->indexes );
625                 ds->numIndexes = 0;
626                 StripFaceSurface( ds );
627                 return;
628         }
629         ds->numIndexes = n;
630
631         /* add to count */
632         numMaxAreaSurfaces++;
633
634         /* classify it */
635         ClassifySurfaces( 1, ds );
636 }
637
638
639
640 /*
641    FanFaceSurface() - ydnar
642    creates a tri-fan from a brush face winding
643    loosely based on SurfaceAsTriFan()
644  */
645
646 void FanFaceSurface( mapDrawSurface_t *ds ){
647         int i, j, k, a, b, c, color[ MAX_LIGHTMAPS ][ 4 ];
648         bspDrawVert_t   *verts, *centroid, *dv;
649         double iv;
650
651
652         /* try to early out */
653         if ( !ds->numVerts || ( ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL ) ) {
654                 return;
655         }
656
657         /* add a new vertex at the beginning of the surface */
658         verts = safe_malloc( ( ds->numVerts + 1 ) * sizeof( bspDrawVert_t ) );
659         /* beware to only zero the new vertexi at the beginning, nor more! */
660         memset( verts, 0, sizeof( bspDrawVert_t ) );
661         memcpy( &verts[ 1 ], ds->verts, ds->numVerts * sizeof( bspDrawVert_t ) );
662         free( ds->verts );
663         ds->verts = verts;
664
665         /* add up the drawverts to create a centroid */
666         centroid = &verts[ 0 ];
667         memset( color, 0,  4 * MAX_LIGHTMAPS * sizeof( int ) );
668         for ( i = 1, dv = &verts[ 1 ]; i < ( ds->numVerts + 1 ); i++, dv++ )
669         {
670                 VectorAdd( centroid->xyz, dv->xyz, centroid->xyz );
671                 VectorAdd( centroid->normal, dv->normal, centroid->normal );
672                 for ( j = 0; j < 4; j++ )
673                 {
674                         for ( k = 0; k < MAX_LIGHTMAPS; k++ )
675                                 color[ k ][ j ] += dv->color[ k ][ j ];
676                         if ( j < 2 ) {
677                                 centroid->st[ j ] += dv->st[ j ];
678                                 for ( k = 0; k < MAX_LIGHTMAPS; k++ )
679                                         centroid->lightmap[ k ][ j ] += dv->lightmap[ k ][ j ];
680                         }
681                 }
682         }
683
684         /* average the centroid */
685         iv = 1.0f / ds->numVerts;
686         VectorScale( centroid->xyz, iv, centroid->xyz );
687         if ( VectorNormalize( centroid->normal, centroid->normal ) <= 0 ) {
688                 VectorCopy( verts[ 1 ].normal, centroid->normal );
689         }
690         for ( j = 0; j < 4; j++ )
691         {
692                 for ( k = 0; k < MAX_LIGHTMAPS; k++ )
693                 {
694                         color[ k ][ j ] /= ds->numVerts;
695                         centroid->color[ k ][ j ] = ( color[ k ][ j ] < 255.0f ? color[ k ][ j ] : 255 );
696                 }
697                 if ( j < 2 ) {
698                         centroid->st[ j ] *= iv;
699                         for ( k = 0; k < MAX_LIGHTMAPS; k++ )
700                                 centroid->lightmap[ k ][ j ] *= iv;
701                 }
702         }
703
704         /* add to vert count */
705         ds->numVerts++;
706
707         /* fill indexes in triangle fan order */
708         ds->numIndexes = 0;
709         ds->indexes = safe_malloc( ds->numVerts * 3 * sizeof( int ) );
710         for ( i = 1; i < ds->numVerts; i++ )
711         {
712                 a = 0;
713                 b = i;
714                 c = ( i + 1 ) % ds->numVerts;
715                 c = c ? c : 1;
716                 ds->indexes[ ds->numIndexes++ ] = a;
717                 ds->indexes[ ds->numIndexes++ ] = b;
718                 ds->indexes[ ds->numIndexes++ ] = c;
719         }
720
721         /* add to count */
722         numFanSurfaces++;
723
724         /* classify it */
725         ClassifySurfaces( 1, ds );
726 }
727
728
729
730 /*
731    StripFaceSurface() - ydnar
732    attempts to create a valid tri-strip w/o degenerate triangles from a brush face winding
733    based on SurfaceAsTriStrip()
734  */
735
736 #define MAX_INDEXES     1024
737
738 void StripFaceSurface( mapDrawSurface_t *ds ){
739         int i, r, least, rotate, numIndexes, ni, a, b, c, indexes[ MAX_INDEXES ];
740         vec_t       *v1, *v2;
741
742
743         /* try to early out  */
744         if ( !ds->numVerts || ( ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL ) ) {
745                 return;
746         }
747
748         /* is this a simple triangle? */
749         if ( ds->numVerts == 3 ) {
750                 numIndexes = 3;
751                 VectorSet( indexes, 0, 1, 2 );
752         }
753         else
754         {
755                 /* ydnar: find smallest coordinate */
756                 least = 0;
757                 if ( ds->shaderInfo != NULL && ds->shaderInfo->autosprite == qfalse ) {
758                         for ( i = 0; i < ds->numVerts; i++ )
759                         {
760                                 /* get points */
761                                 v1 = ds->verts[ i ].xyz;
762                                 v2 = ds->verts[ least ].xyz;
763
764                                 /* compare */
765                                 if ( v1[ 0 ] < v2[ 0 ] ||
766                                          ( v1[ 0 ] == v2[ 0 ] && v1[ 1 ] < v2[ 1 ] ) ||
767                                          ( v1[ 0 ] == v2[ 0 ] && v1[ 1 ] == v2[ 1 ] && v1[ 2 ] < v2[ 2 ] ) ) {
768                                         least = i;
769                                 }
770                         }
771                 }
772
773                 /* determine the triangle strip order */
774                 numIndexes = ( ds->numVerts - 2 ) * 3;
775                 if ( numIndexes > MAX_INDEXES ) {
776                         Error( "MAX_INDEXES exceeded for surface (%d > %d) (%d verts)", numIndexes, MAX_INDEXES, ds->numVerts );
777                 }
778
779                 /* try all possible orderings of the points looking for a non-degenerate strip order */
780                 ni = 0;
781                 for ( r = 0; r < ds->numVerts; r++ )
782                 {
783                         /* set rotation */
784                         rotate = ( r + least ) % ds->numVerts;
785
786                         /* walk the winding in both directions */
787                         for ( ni = 0, i = 0; i < ds->numVerts - 2 - i; i++ )
788                         {
789                                 /* make indexes */
790                                 a = ( ds->numVerts - 1 - i + rotate ) % ds->numVerts;
791                                 b = ( i + rotate ) % ds->numVerts;
792                                 c = ( ds->numVerts - 2 - i + rotate ) % ds->numVerts;
793
794                                 /* test this triangle */
795                                 if ( ds->numVerts > 4 && IsTriangleDegenerate( ds->verts, a, b, c ) ) {
796                                         break;
797                                 }
798                                 indexes[ ni++ ] = a;
799                                 indexes[ ni++ ] = b;
800                                 indexes[ ni++ ] = c;
801
802                                 /* handle end case */
803                                 if ( i + 1 != ds->numVerts - 1 - i ) {
804                                         /* make indexes */
805                                         a = ( ds->numVerts - 2 - i + rotate ) % ds->numVerts;
806                                         b = ( i + rotate ) % ds->numVerts;
807                                         c = ( i + 1 + rotate ) % ds->numVerts;
808
809                                         /* test triangle */
810                                         if ( ds->numVerts > 4 && IsTriangleDegenerate( ds->verts, a, b, c ) ) {
811                                                 break;
812                                         }
813                                         indexes[ ni++ ] = a;
814                                         indexes[ ni++ ] = b;
815                                         indexes[ ni++ ] = c;
816                                 }
817                         }
818
819                         /* valid strip? */
820                         if ( ni == numIndexes ) {
821                                 break;
822                         }
823                 }
824
825                 /* if any triangle in the strip is degenerate, render from a centered fan point instead */
826                 if ( ni < numIndexes ) {
827                         FanFaceSurface( ds );
828                         return;
829                 }
830         }
831
832         /* copy strip triangle indexes */
833         ds->numIndexes = numIndexes;
834         ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
835         memcpy( ds->indexes, indexes, ds->numIndexes * sizeof( int ) );
836
837         /* add to count */
838         numStripSurfaces++;
839
840         /* classify it */
841         ClassifySurfaces( 1, ds );
842 }
843
844
845
846 /*
847    EmitMetaStatictics
848    vortex: prints meta statistics in general output
849  */
850
851 void EmitMetaStats(){
852         Sys_Printf( "--- EmitMetaStats ---\n" );
853         Sys_Printf( "%9d total meta surfaces\n", numMetaSurfaces );
854         Sys_Printf( "%9d stripped surfaces\n", numStripSurfaces );
855         Sys_Printf( "%9d fanned surfaces\n", numFanSurfaces );
856         Sys_Printf( "%9d maxarea'd surfaces\n", numMaxAreaSurfaces );
857         Sys_Printf( "%9d patch meta surfaces\n", numPatchMetaSurfaces );
858         Sys_Printf( "%9d meta verts\n", numMetaVerts );
859         Sys_Printf( "%9d meta triangles\n", numMetaTriangles );
860 }
861
862
863
864 /*
865    MakeEntityMetaTriangles()
866    builds meta triangles from brush faces (tristrips and fans)
867  */
868
869 void MakeEntityMetaTriangles( entity_t *e ){
870         int i, f, fOld, start;
871         mapDrawSurface_t    *ds;
872
873
874         /* note it */
875         Sys_FPrintf( SYS_VRB, "--- MakeEntityMetaTriangles ---\n" );
876
877         /* init pacifier */
878         fOld = -1;
879         start = I_FloatTime();
880
881         /* walk the list of surfaces in the entity */
882         for ( i = e->firstDrawSurf; i < numMapDrawSurfs; i++ )
883         {
884                 /* print pacifier */
885                 f = 10 * ( i - e->firstDrawSurf ) / ( numMapDrawSurfs - e->firstDrawSurf );
886                 if ( f != fOld ) {
887                         fOld = f;
888                         Sys_FPrintf( SYS_VRB, "%d...", f );
889                 }
890
891                 /* get surface */
892                 ds = &mapDrawSurfs[ i ];
893                 if ( ds->numVerts <= 0 ) {
894                         continue;
895                 }
896
897                 /* ignore autosprite surfaces */
898                 if ( ds->shaderInfo->autosprite ) {
899                         continue;
900                 }
901
902                 /* meta this surface? */
903                 if ( meta == qfalse && ds->shaderInfo->forceMeta == qfalse ) {
904                         continue;
905                 }
906
907                 /* switch on type */
908                 switch ( ds->type )
909                 {
910                 case SURFACE_FACE:
911                 case SURFACE_DECAL:
912                         if ( maxAreaFaceSurface ) {
913                                 MaxAreaFaceSurface( ds );
914                         }
915                         else{
916                                 StripFaceSurface( ds );
917                         }
918                         SurfaceToMetaTriangles( ds );
919                         break;
920
921                 case SURFACE_PATCH:
922                         TriangulatePatchSurface( e, ds );
923                         break;
924
925                 case SURFACE_TRIANGLES:
926                         break;
927
928                 case SURFACE_FORCED_META:
929                 case SURFACE_META:
930                         SurfaceToMetaTriangles( ds );
931                         break;
932
933                 default:
934                         break;
935                 }
936         }
937
938         /* print time */
939         if ( ( numMapDrawSurfs - e->firstDrawSurf ) ) {
940                 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) ( I_FloatTime() - start ) );
941         }
942
943         /* emit some stats */
944         Sys_FPrintf( SYS_VRB, "%9d total meta surfaces\n", numMetaSurfaces );
945         Sys_FPrintf( SYS_VRB, "%9d stripped surfaces\n", numStripSurfaces );
946         Sys_FPrintf( SYS_VRB, "%9d fanned surfaces\n", numFanSurfaces );
947         Sys_FPrintf( SYS_VRB, "%9d maxarea'd surfaces\n", numMaxAreaSurfaces );
948         Sys_FPrintf( SYS_VRB, "%9d patch meta surfaces\n", numPatchMetaSurfaces );
949         Sys_FPrintf( SYS_VRB, "%9d meta verts\n", numMetaVerts );
950         Sys_FPrintf( SYS_VRB, "%9d meta triangles\n", numMetaTriangles );
951
952         /* tidy things up */
953         TidyEntitySurfaces( e );
954 }
955
956
957
958 /*
959    CreateEdge()
960    sets up an edge structure from a plane and 2 points that the edge ab falls lies in
961  */
962
963 typedef struct edge_s
964 {
965         vec3_t origin, edge;
966         vec_t length, kingpinLength;
967         int kingpin;
968         vec4_t plane;
969 }
970 edge_t;
971
972 void CreateEdge( vec4_t plane, vec3_t a, vec3_t b, edge_t *edge ){
973         /* copy edge origin */
974         VectorCopy( a, edge->origin );
975
976         /* create vector aligned with winding direction of edge */
977         VectorSubtract( b, a, edge->edge );
978
979         if ( fabs( edge->edge[ 0 ] ) > fabs( edge->edge[ 1 ] ) && fabs( edge->edge[ 0 ] ) > fabs( edge->edge[ 2 ] ) ) {
980                 edge->kingpin = 0;
981         }
982         else if ( fabs( edge->edge[ 1 ] ) > fabs( edge->edge[ 0 ] ) && fabs( edge->edge[ 1 ] ) > fabs( edge->edge[ 2 ] ) ) {
983                 edge->kingpin = 1;
984         }
985         else{
986                 edge->kingpin = 2;
987         }
988         edge->kingpinLength = edge->edge[ edge->kingpin ];
989
990         VectorNormalize( edge->edge, edge->edge );
991         edge->edge[ 3 ] = DotProduct( a, edge->edge );
992         edge->length = DotProduct( b, edge->edge ) - edge->edge[ 3 ];
993
994         /* create perpendicular plane that edge lies in */
995         CrossProduct( plane, edge->edge, edge->plane );
996         edge->plane[ 3 ] = DotProduct( a, edge->plane );
997 }
998
999
1000
1001 /*
1002    FixMetaTJunctions()
1003    fixes t-junctions on meta triangles
1004  */
1005
1006 #define TJ_PLANE_EPSILON    ( 1.0f / 8.0f )
1007 #define TJ_EDGE_EPSILON     ( 1.0f / 8.0f )
1008 #define TJ_POINT_EPSILON    ( 1.0f / 8.0f )
1009
1010 void FixMetaTJunctions( void ){
1011         int i, j, k, f, fOld, start, vertIndex, triIndex, numTJuncs;
1012         metaTriangle_t  *tri, *newTri;
1013         shaderInfo_t    *si;
1014         bspDrawVert_t   *a, *b, *c, junc;
1015         float dist, amount;
1016         vec3_t pt;
1017         vec4_t plane;
1018         edge_t edges[ 3 ];
1019
1020
1021         /* this code is crap; revisit later */
1022         return;
1023
1024         /* note it */
1025         Sys_FPrintf( SYS_VRB, "--- FixMetaTJunctions ---\n" );
1026
1027         /* init pacifier */
1028         fOld = -1;
1029         start = I_FloatTime();
1030
1031         /* walk triangle list */
1032         numTJuncs = 0;
1033         for ( i = 0; i < numMetaTriangles; i++ )
1034         {
1035                 /* get triangle */
1036                 tri = &metaTriangles[ i ];
1037
1038                 /* print pacifier */
1039                 f = 10 * i / numMetaTriangles;
1040                 if ( f != fOld ) {
1041                         fOld = f;
1042                         Sys_FPrintf( SYS_VRB, "%d...", f );
1043                 }
1044
1045                 /* attempt to early out */
1046                 si = tri->si;
1047                 if ( ( si->compileFlags & C_NODRAW ) || si->autosprite || si->notjunc ) {
1048                         continue;
1049                 }
1050
1051                 /* calculate planes */
1052                 VectorCopy( tri->plane, plane );
1053                 plane[ 3 ] = tri->plane[ 3 ];
1054                 CreateEdge( plane, metaVerts[ tri->indexes[ 0 ] ].xyz, metaVerts[ tri->indexes[ 1 ] ].xyz, &edges[ 0 ] );
1055                 CreateEdge( plane, metaVerts[ tri->indexes[ 1 ] ].xyz, metaVerts[ tri->indexes[ 2 ] ].xyz, &edges[ 1 ] );
1056                 CreateEdge( plane, metaVerts[ tri->indexes[ 2 ] ].xyz, metaVerts[ tri->indexes[ 0 ] ].xyz, &edges[ 2 ] );
1057
1058                 /* walk meta vert list */
1059                 for ( j = 0; j < numMetaVerts; j++ )
1060                 {
1061                         /* get vert */
1062                         VectorCopy( metaVerts[ j ].xyz, pt );
1063
1064                         /* determine if point lies in the triangle's plane */
1065                         dist = DotProduct( pt, plane ) - plane[ 3 ];
1066                         if ( fabs( dist ) > TJ_PLANE_EPSILON ) {
1067                                 continue;
1068                         }
1069
1070                         /* skip this point if it already exists in the triangle */
1071                         for ( k = 0; k < 3; k++ )
1072                         {
1073                                 if ( fabs( pt[ 0 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 0 ] ) <= TJ_POINT_EPSILON &&
1074                                          fabs( pt[ 1 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 1 ] ) <= TJ_POINT_EPSILON &&
1075                                          fabs( pt[ 2 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 2 ] ) <= TJ_POINT_EPSILON ) {
1076                                         break;
1077                                 }
1078                         }
1079                         if ( k < 3 ) {
1080                                 continue;
1081                         }
1082
1083                         /* walk edges */
1084                         for ( k = 0; k < 3; k++ )
1085                         {
1086                                 /* ignore bogus edges */
1087                                 if ( fabs( edges[ k ].kingpinLength ) < TJ_EDGE_EPSILON ) {
1088                                         continue;
1089                                 }
1090
1091                                 /* determine if point lies on the edge */
1092                                 dist = DotProduct( pt, edges[ k ].plane ) - edges[ k ].plane[ 3 ];
1093                                 if ( fabs( dist ) > TJ_EDGE_EPSILON ) {
1094                                         continue;
1095                                 }
1096
1097                                 /* determine how far along the edge the point lies */
1098                                 amount = ( pt[ edges[ k ].kingpin ] - edges[ k ].origin[ edges[ k ].kingpin ] ) / edges[ k ].kingpinLength;
1099                                 if ( amount <= 0.0f || amount >= 1.0f ) {
1100                                         continue;
1101                                 }
1102
1103                                 #if 0
1104                                 dist = DotProduct( pt, edges[ k ].edge ) - edges[ k ].edge[ 3 ];
1105                                 if ( dist <= -0.0f || dist >= edges[ k ].length ) {
1106                                         continue;
1107                                 }
1108                                 amount = dist / edges[ k ].length;
1109                                 #endif
1110
1111                                 /* the edge opposite the zero-weighted vertex was hit, so use that as an amount */
1112                                 a = &metaVerts[ tri->indexes[ k % 3 ] ];
1113                                 b = &metaVerts[ tri->indexes[ ( k + 1 ) % 3 ] ];
1114                                 c = &metaVerts[ tri->indexes[ ( k + 2 ) % 3 ] ];
1115
1116                                 /* make new vert */
1117                                 LerpDrawVertAmount( a, b, amount, &junc );
1118                                 VectorCopy( pt, junc.xyz );
1119
1120                                 /* compare against existing verts */
1121                                 if ( VectorCompare( junc.xyz, a->xyz ) || VectorCompare( junc.xyz, b->xyz ) || VectorCompare( junc.xyz, c->xyz ) ) {
1122                                         continue;
1123                                 }
1124
1125                                 /* see if we can just re-use the existing vert */
1126                                 if ( !memcmp( &metaVerts[ j ], &junc, sizeof( junc ) ) ) {
1127                                         vertIndex = j;
1128                                 }
1129                                 else
1130                                 {
1131                                         /* find new vertex (note: a and b are invalid pointers after this) */
1132                                         firstSearchMetaVert = numMetaVerts;
1133                                         vertIndex = FindMetaVertex( &junc );
1134                                         if ( vertIndex < 0 ) {
1135                                                 continue;
1136                                         }
1137                                 }
1138
1139                                 /* make new triangle */
1140                                 triIndex = AddMetaTriangle();
1141                                 if ( triIndex < 0 ) {
1142                                         continue;
1143                                 }
1144
1145                                 /* get triangles */
1146                                 tri = &metaTriangles[ i ];
1147                                 newTri = &metaTriangles[ triIndex ];
1148
1149                                 /* copy the triangle */
1150                                 memcpy( newTri, tri, sizeof( *tri ) );
1151
1152                                 /* fix verts */
1153                                 tri->indexes[ ( k + 1 ) % 3 ] = vertIndex;
1154                                 newTri->indexes[ k ] = vertIndex;
1155
1156                                 /* recalculate edges */
1157                                 CreateEdge( plane, metaVerts[ tri->indexes[ 0 ] ].xyz, metaVerts[ tri->indexes[ 1 ] ].xyz, &edges[ 0 ] );
1158                                 CreateEdge( plane, metaVerts[ tri->indexes[ 1 ] ].xyz, metaVerts[ tri->indexes[ 2 ] ].xyz, &edges[ 1 ] );
1159                                 CreateEdge( plane, metaVerts[ tri->indexes[ 2 ] ].xyz, metaVerts[ tri->indexes[ 0 ] ].xyz, &edges[ 2 ] );
1160
1161                                 /* debug code */
1162                                 metaVerts[ vertIndex ].color[ 0 ][ 0 ] = 255;
1163                                 metaVerts[ vertIndex ].color[ 0 ][ 1 ] = 204;
1164                                 metaVerts[ vertIndex ].color[ 0 ][ 2 ] = 0;
1165
1166                                 /* add to counter and end processing of this vert */
1167                                 numTJuncs++;
1168                                 break;
1169                         }
1170                 }
1171         }
1172
1173         /* print time */
1174         Sys_FPrintf( SYS_VRB, " (%d)\n", (int) ( I_FloatTime() - start ) );
1175
1176         /* emit some stats */
1177         Sys_FPrintf( SYS_VRB, "%9d T-junctions added\n", numTJuncs );
1178 }
1179
1180
1181
1182 /*
1183    SmoothMetaTriangles()
1184    averages coincident vertex normals in the meta triangles
1185  */
1186
1187 #define MAX_SAMPLES             256
1188 #define THETA_EPSILON           0.000001
1189 #define EQUAL_NORMAL_EPSILON    0.01
1190
1191 void SmoothMetaTriangles( void ){
1192         int i, j, k, f, fOld, start, cs, numVerts, numVotes, numSmoothed;
1193         float shadeAngle, defaultShadeAngle, maxShadeAngle, dot, testAngle;
1194         metaTriangle_t  *tri;
1195         float           *shadeAngles;
1196         byte            *smoothed;
1197         vec3_t average, diff;
1198         int indexes[ MAX_SAMPLES ];
1199         vec3_t votes[ MAX_SAMPLES ];
1200
1201         /* note it */
1202         Sys_FPrintf( SYS_VRB, "--- SmoothMetaTriangles ---\n" );
1203
1204         /* allocate shade angle table */
1205         shadeAngles = safe_malloc0( numMetaVerts * sizeof( float ) );
1206
1207         /* allocate smoothed table */
1208         cs = ( numMetaVerts / 8 ) + 1;
1209         smoothed = safe_malloc0( cs );
1210
1211         /* set default shade angle */
1212         defaultShadeAngle = DEG2RAD( npDegrees );
1213         maxShadeAngle = 0.0f;
1214
1215         /* run through every surface and flag verts belonging to non-lightmapped surfaces
1216            and set per-vertex smoothing angle */
1217         for ( i = 0, tri = &metaTriangles[ i ]; i < numMetaTriangles; i++, tri++ )
1218         {
1219                 shadeAngle = defaultShadeAngle;
1220
1221                 /* get shade angle from shader */
1222                 if ( tri->si->shadeAngleDegrees > 0.0f ) {
1223                         shadeAngle = DEG2RAD( tri->si->shadeAngleDegrees );
1224                 }
1225                 /* get shade angle from entity */
1226                 else if ( tri->shadeAngleDegrees > 0.0f ) {
1227                         shadeAngle = DEG2RAD( tri->shadeAngleDegrees );
1228                 }
1229
1230                 if ( shadeAngle <= 0.0f ) {
1231                         shadeAngle = defaultShadeAngle;
1232                 }
1233
1234                 if ( shadeAngle > maxShadeAngle ) {
1235                         maxShadeAngle = shadeAngle;
1236                 }
1237
1238                 /* flag its verts */
1239                 for ( j = 0; j < 3; j++ )
1240                 {
1241                         shadeAngles[ tri->indexes[ j ] ] = shadeAngle;
1242                         if ( shadeAngle <= 0 ) {
1243                                 smoothed[ tri->indexes[ j ] >> 3 ] |= ( 1 << ( tri->indexes[ j ] & 7 ) );
1244                         }
1245                 }
1246         }
1247
1248         /* bail if no surfaces have a shade angle */
1249         if ( maxShadeAngle <= 0 ) {
1250                 Sys_FPrintf( SYS_VRB, "No smoothing angles specified, aborting\n" );
1251                 free( shadeAngles );
1252                 free( smoothed );
1253                 return;
1254         }
1255
1256         /* init pacifier */
1257         fOld = -1;
1258         start = I_FloatTime();
1259
1260         /* go through the list of vertexes */
1261         numSmoothed = 0;
1262         for ( i = 0; i < numMetaVerts; i++ )
1263         {
1264                 /* print pacifier */
1265                 f = 10 * i / numMetaVerts;
1266                 if ( f != fOld ) {
1267                         fOld = f;
1268                         Sys_FPrintf( SYS_VRB, "%d...", f );
1269                 }
1270
1271                 /* already smoothed? */
1272                 if ( smoothed[ i >> 3 ] & ( 1 << ( i & 7 ) ) ) {
1273                         continue;
1274                 }
1275
1276                 /* clear */
1277                 VectorClear( average );
1278                 numVerts = 0;
1279                 numVotes = 0;
1280
1281                 /* build a table of coincident vertexes */
1282                 for ( j = i; j < numMetaVerts && numVerts < MAX_SAMPLES; j++ )
1283                 {
1284                         /* already smoothed? */
1285                         if ( smoothed[ j >> 3 ] & ( 1 << ( j & 7 ) ) ) {
1286                                 continue;
1287                         }
1288
1289                         /* test vertexes */
1290                         if ( VectorCompare( metaVerts[ i ].xyz, metaVerts[ j ].xyz ) == qfalse ) {
1291                                 continue;
1292                         }
1293
1294                         /* use smallest shade angle */
1295                         shadeAngle = ( shadeAngles[ i ] < shadeAngles[ j ] ? shadeAngles[ i ] : shadeAngles[ j ] );
1296
1297                         /* check shade angle */
1298                         dot = DotProduct( metaVerts[ i ].normal, metaVerts[ j ].normal );
1299                         if ( dot > 1.0 ) {
1300                                 dot = 1.0;
1301                         }
1302                         else if ( dot < -1.0 ) {
1303                                 dot = -1.0;
1304                         }
1305                         testAngle = acos( dot ) + THETA_EPSILON;
1306                         if ( testAngle >= shadeAngle ) {
1307                                 continue;
1308                         }
1309
1310                         /* add to the list */
1311                         indexes[ numVerts++ ] = j;
1312
1313                         /* flag vertex */
1314                         smoothed[ j >> 3 ] |= ( 1 << ( j & 7 ) );
1315
1316                         /* see if this normal has already been voted */
1317                         for ( k = 0; k < numVotes; k++ )
1318                         {
1319                                 VectorSubtract( metaVerts[ j ].normal, votes[ k ], diff );
1320                                 if ( fabs( diff[ 0 ] ) < EQUAL_NORMAL_EPSILON &&
1321                                          fabs( diff[ 1 ] ) < EQUAL_NORMAL_EPSILON &&
1322                                          fabs( diff[ 2 ] ) < EQUAL_NORMAL_EPSILON ) {
1323                                         break;
1324                                 }
1325                         }
1326
1327                         /* add a new vote? */
1328                         if ( k == numVotes && numVotes < MAX_SAMPLES ) {
1329                                 VectorAdd( average, metaVerts[ j ].normal, average );
1330                                 VectorCopy( metaVerts[ j ].normal, votes[ numVotes ] );
1331                                 numVotes++;
1332                         }
1333                 }
1334
1335                 /* don't average for less than 2 verts */
1336                 if ( numVerts < 2 ) {
1337                         continue;
1338                 }
1339
1340                 /* average normal */
1341                 if ( VectorNormalize( average, average ) > 0 ) {
1342                         /* smooth */
1343                         for ( j = 0; j < numVerts; j++ )
1344                                 VectorCopy( average, metaVerts[ indexes[ j ] ].normal );
1345                         numSmoothed++;
1346                 }
1347         }
1348
1349         /* free the tables */
1350         free( shadeAngles );
1351         free( smoothed );
1352
1353         /* print time */
1354         Sys_FPrintf( SYS_VRB, " (%d)\n", (int) ( I_FloatTime() - start ) );
1355
1356         /* emit some stats */
1357         Sys_FPrintf( SYS_VRB, "%9d smoothed vertexes\n", numSmoothed );
1358 }
1359
1360
1361
1362 /*
1363    AddMetaVertToSurface()
1364    adds a drawvert to a surface unless an existing vert matching already exists
1365    returns the index of that vert (or < 0 on failure)
1366  */
1367
1368 int AddMetaVertToSurface( mapDrawSurface_t *ds, bspDrawVert_t *dv1, int *coincident ){
1369         int i;
1370         bspDrawVert_t   *dv2;
1371
1372
1373         /* go through the verts and find a suitable candidate */
1374         for ( i = 0; i < ds->numVerts; i++ )
1375         {
1376                 /* get test vert */
1377                 dv2 = &ds->verts[ i ];
1378
1379                 /* compare xyz and normal */
1380                 if ( VectorCompare( dv1->xyz, dv2->xyz ) == qfalse ) {
1381                         continue;
1382                 }
1383                 if ( VectorCompare( dv1->normal, dv2->normal ) == qfalse ) {
1384                         continue;
1385                 }
1386
1387                 /* good enough at this point */
1388                 ( *coincident )++;
1389
1390                 /* compare texture coordinates and color */
1391                 if ( dv1->st[ 0 ] != dv2->st[ 0 ] || dv1->st[ 1 ] != dv2->st[ 1 ] ) {
1392                         continue;
1393                 }
1394                 if ( dv1->color[ 0 ][ 3 ] != dv2->color[ 0 ][ 3 ] ) {
1395                         continue;
1396                 }
1397
1398                 /* found a winner */
1399                 numMergedVerts++;
1400                 return i;
1401         }
1402
1403         /* overflow check */
1404         if ( ds->numVerts >= ( ( ds->shaderInfo->compileFlags & C_VERTEXLIT ) ? maxSurfaceVerts : maxLMSurfaceVerts ) ) {
1405                 return VERTS_EXCEEDED;
1406         }
1407
1408         /* made it this far, add the vert and return */
1409         dv2 = &ds->verts[ ds->numVerts++ ];
1410         *dv2 = *dv1;
1411         return ( ds->numVerts - 1 );
1412 }
1413
1414
1415
1416
1417 /*
1418    AddMetaTriangleToSurface()
1419    attempts to add a metatriangle to a surface
1420    returns the score of the triangle added
1421  */
1422
1423 #define AXIS_SCORE          100000
1424 #define AXIS_MIN            100000
1425 #define VERT_SCORE          10000
1426 #define SURFACE_SCORE           1000
1427 #define ST_SCORE            50
1428 #define ST_SCORE2           ( 2 * ( ST_SCORE ) )
1429
1430 #define DEFAULT_ADEQUATE_SCORE      ( (AXIS_MIN) +1 * ( VERT_SCORE ) )
1431 #define DEFAULT_GOOD_SCORE      ( (AXIS_MIN) +2 * (VERT_SCORE)                   +4 * ( ST_SCORE ) )
1432 #define         PERFECT_SCORE       ( (AXIS_MIN) +3 * ( VERT_SCORE ) + (SURFACE_SCORE) +4 * ( ST_SCORE ) )
1433
1434 #define ADEQUATE_SCORE          ( metaAdequateScore >= 0 ? metaAdequateScore : DEFAULT_ADEQUATE_SCORE )
1435 #define GOOD_SCORE          ( metaGoodScore     >= 0 ? metaGoodScore     : DEFAULT_GOOD_SCORE )
1436
1437 static int AddMetaTriangleToSurface( mapDrawSurface_t *ds, metaTriangle_t *tri, qboolean testAdd ){
1438         vec3_t p;
1439         int i, score, coincident, ai, bi, ci, oldTexRange[ 2 ];
1440         float lmMax;
1441         vec3_t mins, maxs;
1442         qboolean inTexRange;
1443         mapDrawSurface_t old;
1444
1445
1446         /* overflow check */
1447         if ( ds->numIndexes >= maxSurfaceIndexes ) {
1448                 return 0;
1449         }
1450
1451         /* test the triangle */
1452         if ( ds->entityNum != tri->entityNum ) { /* ydnar: added 2002-07-06 */
1453                 return 0;
1454         }
1455         if ( ds->castShadows != tri->castShadows || ds->recvShadows != tri->recvShadows ) {
1456                 return 0;
1457         }
1458         if ( ds->shaderInfo != tri->si || ds->fogNum != tri->fogNum || ds->sampleSize != tri->sampleSize ) {
1459                 return 0;
1460         }
1461         #if 0
1462         if ( !( ds->shaderInfo->compileFlags & C_VERTEXLIT ) &&
1463              //% VectorCompare( ds->lightmapAxis, tri->lightmapAxis ) == qfalse )
1464                  DotProduct( ds->lightmapAxis, tri->plane ) < 0.25f ) {
1465                 return 0;
1466         }
1467         #endif
1468
1469         /* planar surfaces will only merge with triangles in the same plane */
1470         if ( npDegrees == 0.0f && ds->shaderInfo->nonplanar == qfalse && ds->planeNum >= 0 ) {
1471                 if ( VectorCompare( mapplanes[ ds->planeNum ].normal, tri->plane ) == qfalse || mapplanes[ ds->planeNum ].dist != tri->plane[ 3 ] ) {
1472                         return 0;
1473                 }
1474                 if ( tri->planeNum >= 0 && tri->planeNum != ds->planeNum ) {
1475                         return 0;
1476                 }
1477         }
1478
1479         if ( metaMaxBBoxDistance >= 0 ) {
1480                 if ( ds->numIndexes > 0 ) {
1481                         VectorCopy( ds->mins, mins );
1482                         VectorCopy( ds->maxs, maxs );
1483                         mins[0] -= metaMaxBBoxDistance;
1484                         mins[1] -= metaMaxBBoxDistance;
1485                         mins[2] -= metaMaxBBoxDistance;
1486                         maxs[0] += metaMaxBBoxDistance;
1487                         maxs[1] += metaMaxBBoxDistance;
1488                         maxs[2] += metaMaxBBoxDistance;
1489 #define CHECK_1D( mins, v, maxs ) ( ( mins ) <= ( v ) && ( v ) <= ( maxs ) )
1490 #define CHECK_3D( mins, v, maxs ) ( CHECK_1D( ( mins )[0], ( v )[0], ( maxs )[0] ) && CHECK_1D( ( mins )[1], ( v )[1], ( maxs )[1] ) && CHECK_1D( ( mins )[2], ( v )[2], ( maxs )[2] ) )
1491                         VectorCopy( metaVerts[ tri->indexes[ 0 ] ].xyz, p );
1492                         if ( !CHECK_3D( mins, p, maxs ) ) {
1493                                 VectorCopy( metaVerts[ tri->indexes[ 1 ] ].xyz, p );
1494                                 if ( !CHECK_3D( mins, p, maxs ) ) {
1495                                         VectorCopy( metaVerts[ tri->indexes[ 2 ] ].xyz, p );
1496                                         if ( !CHECK_3D( mins, p, maxs ) ) {
1497                                                 return 0;
1498                                         }
1499                                 }
1500                         }
1501 #undef CHECK_3D
1502 #undef CHECK_1D
1503                 }
1504         }
1505
1506         /* set initial score */
1507         score = tri->surfaceNum == ds->surfaceNum ? SURFACE_SCORE : 0;
1508
1509         /* score the the dot product of lightmap axis to plane */
1510         if ( ( ds->shaderInfo->compileFlags & C_VERTEXLIT ) || VectorCompare( ds->lightmapAxis, tri->lightmapAxis ) ) {
1511                 score += AXIS_SCORE;
1512         }
1513         else{
1514                 score += AXIS_SCORE * DotProduct( ds->lightmapAxis, tri->plane );
1515         }
1516
1517         /* preserve old drawsurface if this fails */
1518         memcpy( &old, ds, sizeof( *ds ) );
1519
1520         /* attempt to add the verts */
1521         coincident = 0;
1522         ai = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 0 ] ], &coincident );
1523         bi = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 1 ] ], &coincident );
1524         ci = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 2 ] ], &coincident );
1525
1526         /* check vertex underflow */
1527         if ( ai < 0 || bi < 0 || ci < 0 ) {
1528                 memcpy( ds, &old, sizeof( *ds ) );
1529                 return 0;
1530         }
1531
1532         /* score coincident vertex count (2003-02-14: changed so this only matters on planar surfaces) */
1533         score += ( coincident * VERT_SCORE );
1534
1535         /* add new vertex bounds to mins/maxs */
1536         VectorCopy( ds->mins, mins );
1537         VectorCopy( ds->maxs, maxs );
1538         AddPointToBounds( metaVerts[ tri->indexes[ 0 ] ].xyz, mins, maxs );
1539         AddPointToBounds( metaVerts[ tri->indexes[ 1 ] ].xyz, mins, maxs );
1540         AddPointToBounds( metaVerts[ tri->indexes[ 2 ] ].xyz, mins, maxs );
1541
1542         /* check lightmap bounds overflow (after at least 1 triangle has been added) */
1543         if ( !( ds->shaderInfo->compileFlags & C_VERTEXLIT ) &&
1544                  ds->numIndexes > 0 && VectorLength( ds->lightmapAxis ) > 0.0f &&
1545                  ( VectorCompare( ds->mins, mins ) == qfalse || VectorCompare( ds->maxs, maxs ) == qfalse ) ) {
1546                 /* set maximum size before lightmap scaling (normally 2032 units) */
1547                 /* 2004-02-24: scale lightmap test size by 2 to catch larger brush faces */
1548                 /* 2004-04-11: reverting to actual lightmap size */
1549                 lmMax = ( ds->sampleSize * ( ds->shaderInfo->lmCustomWidth - 1 ) );
1550                 for ( i = 0; i < 3; i++ )
1551                 {
1552                         if ( ( maxs[ i ] - mins[ i ] ) > lmMax ) {
1553                                 memcpy( ds, &old, sizeof( *ds ) );
1554                                 return 0;
1555                         }
1556                 }
1557         }
1558
1559         /* check texture range overflow */
1560         oldTexRange[ 0 ] = ds->texRange[ 0 ];
1561         oldTexRange[ 1 ] = ds->texRange[ 1 ];
1562         inTexRange = CalcSurfaceTextureRange( ds );
1563
1564         if ( inTexRange == qfalse && ds->numIndexes > 0 ) {
1565                 memcpy( ds, &old, sizeof( *ds ) );
1566                 return UNSUITABLE_TRIANGLE;
1567         }
1568
1569         /* score texture range */
1570         if ( ds->texRange[ 0 ] <= oldTexRange[ 0 ] ) {
1571                 score += ST_SCORE2;
1572         }
1573         else if ( ds->texRange[ 0 ] > oldTexRange[ 0 ] && oldTexRange[ 1 ] > oldTexRange[ 0 ] ) {
1574                 score += ST_SCORE;
1575         }
1576
1577         if ( ds->texRange[ 1 ] <= oldTexRange[ 1 ] ) {
1578                 score += ST_SCORE2;
1579         }
1580         else if ( ds->texRange[ 1 ] > oldTexRange[ 1 ] && oldTexRange[ 0 ] > oldTexRange[ 1 ] ) {
1581                 score += ST_SCORE;
1582         }
1583
1584
1585         /* go through the indexes and try to find an existing triangle that matches abc */
1586         for ( i = 0; i < ds->numIndexes; i += 3 )
1587         {
1588                 /* 2002-03-11 (birthday!): rotate the triangle 3x to find an existing triangle */
1589                 if ( ( ai == ds->indexes[ i ] && bi == ds->indexes[ i + 1 ] && ci == ds->indexes[ i + 2 ] ) ||
1590                          ( bi == ds->indexes[ i ] && ci == ds->indexes[ i + 1 ] && ai == ds->indexes[ i + 2 ] ) ||
1591                          ( ci == ds->indexes[ i ] && ai == ds->indexes[ i + 1 ] && bi == ds->indexes[ i + 2 ] ) ) {
1592                         /* triangle already present */
1593                         memcpy( ds, &old, sizeof( *ds ) );
1594                         tri->si = NULL;
1595                         return 0;
1596                 }
1597
1598                 /* rotate the triangle 3x to find an inverse triangle (error case) */
1599                 if ( ( ai == ds->indexes[ i ] && bi == ds->indexes[ i + 2 ] && ci == ds->indexes[ i + 1 ] ) ||
1600                          ( bi == ds->indexes[ i ] && ci == ds->indexes[ i + 2 ] && ai == ds->indexes[ i + 1 ] ) ||
1601                          ( ci == ds->indexes[ i ] && ai == ds->indexes[ i + 2 ] && bi == ds->indexes[ i + 1 ] ) ) {
1602                         /* warn about it */
1603                         Sys_FPrintf( SYS_WRN, "WARNING: Flipped triangle: (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f)\n",
1604                                                 ds->verts[ ai ].xyz[ 0 ], ds->verts[ ai ].xyz[ 1 ], ds->verts[ ai ].xyz[ 2 ],
1605                                                 ds->verts[ bi ].xyz[ 0 ], ds->verts[ bi ].xyz[ 1 ], ds->verts[ bi ].xyz[ 2 ],
1606                                                 ds->verts[ ci ].xyz[ 0 ], ds->verts[ ci ].xyz[ 1 ], ds->verts[ ci ].xyz[ 2 ] );
1607
1608                         /* reverse triangle already present */
1609                         memcpy( ds, &old, sizeof( *ds ) );
1610                         tri->si = NULL;
1611                         return 0;
1612                 }
1613         }
1614
1615         /* add the triangle indexes */
1616         if ( ds->numIndexes < maxSurfaceIndexes ) {
1617                 ds->indexes[ ds->numIndexes++ ] = ai;
1618         }
1619         if ( ds->numIndexes < maxSurfaceIndexes ) {
1620                 ds->indexes[ ds->numIndexes++ ] = bi;
1621         }
1622         if ( ds->numIndexes < maxSurfaceIndexes ) {
1623                 ds->indexes[ ds->numIndexes++ ] = ci;
1624         }
1625
1626         /* check index overflow */
1627         if ( ds->numIndexes >= maxSurfaceIndexes  ) {
1628                 memcpy( ds, &old, sizeof( *ds ) );
1629                 return 0;
1630         }
1631
1632         /* sanity check the indexes */
1633         if ( ds->numIndexes >= 3 &&
1634                  ( ds->indexes[ ds->numIndexes - 3 ] == ds->indexes[ ds->numIndexes - 2 ] ||
1635                    ds->indexes[ ds->numIndexes - 3 ] == ds->indexes[ ds->numIndexes - 1 ] ||
1636                    ds->indexes[ ds->numIndexes - 2 ] == ds->indexes[ ds->numIndexes - 1 ] ) ) {
1637                 Sys_Printf( "DEG:%d! ", ds->numVerts );
1638         }
1639
1640         /* testing only? */
1641         if ( testAdd ) {
1642                 memcpy( ds, &old, sizeof( *ds ) );
1643         }
1644         else
1645         {
1646                 /* copy bounds back to surface */
1647                 VectorCopy( mins, ds->mins );
1648                 VectorCopy( maxs, ds->maxs );
1649
1650                 /* mark triangle as used */
1651                 tri->si = NULL;
1652         }
1653
1654         /* add a side reference */
1655         ds->sideRef = AllocSideRef( tri->side, ds->sideRef );
1656
1657         /* return to sender */
1658         return score;
1659 }
1660
1661
1662
1663 /*
1664    MetaTrianglesToSurface()
1665    creates map drawsurface(s) from the list of possibles
1666  */
1667
1668 static void MetaTrianglesToSurface( int numPossibles, metaTriangle_t *possibles, int *fOld, int *numAdded ){
1669         int i, j, f, best, score, bestScore;
1670         metaTriangle_t      *seed, *test;
1671         mapDrawSurface_t    *ds;
1672         bspDrawVert_t       *verts;
1673         int                 *indexes;
1674         qboolean added;
1675
1676
1677         /* allocate arrays */
1678         verts = safe_malloc( sizeof( *verts ) * maxSurfaceVerts );
1679         indexes = safe_malloc( sizeof( *indexes ) * maxSurfaceIndexes );
1680
1681         /* walk the list of triangles */
1682         for ( i = 0, seed = possibles; i < numPossibles; i++, seed++ )
1683         {
1684                 /* skip this triangle if it has already been merged */
1685                 if ( seed->si == NULL ) {
1686                         continue;
1687                 }
1688
1689                 /* -----------------------------------------------------------------
1690                    initial drawsurf construction
1691                    ----------------------------------------------------------------- */
1692
1693                 /* start a new drawsurface */
1694                 ds = AllocDrawSurface( SURFACE_META );
1695                 ds->entityNum = seed->entityNum;
1696                 ds->surfaceNum = seed->surfaceNum;
1697                 ds->castShadows = seed->castShadows;
1698                 ds->recvShadows = seed->recvShadows;
1699
1700                 ds->shaderInfo = seed->si;
1701                 ds->planeNum = seed->planeNum;
1702                 ds->fogNum = seed->fogNum;
1703                 ds->sampleSize = seed->sampleSize;
1704                 ds->shadeAngleDegrees = seed->shadeAngleDegrees;
1705                 ds->verts = verts;
1706                 ds->indexes = indexes;
1707                 VectorCopy( seed->lightmapAxis, ds->lightmapAxis );
1708                 ds->sideRef = AllocSideRef( seed->side, NULL );
1709
1710                 ClearBounds( ds->mins, ds->maxs );
1711
1712                 /* clear verts/indexes */
1713                 memset( verts, 0, sizeof( *verts ) * maxSurfaceVerts );
1714                 memset( indexes, 0, sizeof( *indexes ) * maxSurfaceIndexes );
1715
1716                 /* add the first triangle */
1717                 if ( AddMetaTriangleToSurface( ds, seed, qfalse ) ) {
1718                         ( *numAdded )++;
1719                 }
1720
1721                 /* -----------------------------------------------------------------
1722                    add triangles
1723                    ----------------------------------------------------------------- */
1724
1725                 /* progressively walk the list until no more triangles can be added */
1726                 added = qtrue;
1727                 while ( added )
1728                 {
1729                         /* print pacifier */
1730                         f = 10 * *numAdded / numMetaTriangles;
1731                         if ( f > *fOld ) {
1732                                 *fOld = f;
1733                                 Sys_FPrintf( SYS_VRB, "%d...", f );
1734                         }
1735
1736                         /* reset best score */
1737                         best = -1;
1738                         bestScore = 0;
1739                         added = qfalse;
1740
1741                         /* walk the list of possible candidates for merging */
1742                         for ( j = i + 1, test = &possibles[ j ]; j < numPossibles; j++, test++ )
1743                         {
1744                                 /* skip this triangle if it has already been merged */
1745                                 if ( test->si == NULL ) {
1746                                         continue;
1747                                 }
1748
1749                                 /* score this triangle */
1750                                 score = AddMetaTriangleToSurface( ds, test, qtrue );
1751                                 if ( score > bestScore ) {
1752                                         best = j;
1753                                         bestScore = score;
1754
1755                                         /* if we have a score over a certain threshold, just use it */
1756                                         if ( bestScore >= GOOD_SCORE ) {
1757                                                 if ( AddMetaTriangleToSurface( ds, &possibles[ best ], qfalse ) ) {
1758                                                         ( *numAdded )++;
1759                                                 }
1760
1761                                                 /* reset */
1762                                                 best = -1;
1763                                                 bestScore = 0;
1764                                                 added = qtrue;
1765                                         }
1766                                 }
1767                         }
1768
1769                         /* add best candidate */
1770                         if ( best >= 0 && bestScore > ADEQUATE_SCORE ) {
1771                                 if ( AddMetaTriangleToSurface( ds, &possibles[ best ], qfalse ) ) {
1772                                         ( *numAdded )++;
1773                                 }
1774
1775                                 /* reset */
1776                                 added = qtrue;
1777                         }
1778                 }
1779
1780                 /* copy the verts and indexes to the new surface */
1781                 ds->verts = safe_malloc( ds->numVerts * sizeof( bspDrawVert_t ) );
1782                 memcpy( ds->verts, verts, ds->numVerts * sizeof( bspDrawVert_t ) );
1783                 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
1784                 memcpy( ds->indexes, indexes, ds->numIndexes * sizeof( int ) );
1785
1786                 /* classify the surface */
1787                 ClassifySurfaces( 1, ds );
1788
1789                 /* add to count */
1790                 numMergedSurfaces++;
1791         }
1792
1793         /* free arrays */
1794         free( verts );
1795         free( indexes );
1796 }
1797
1798
1799
1800 /*
1801    CompareMetaTriangles()
1802    compare function for qsort()
1803  */
1804
1805 static int CompareMetaTriangles( const void *a, const void *b ){
1806         int i, j, av, bv;
1807         vec3_t aMins, bMins;
1808
1809
1810         /* shader first */
1811         if ( ( (const metaTriangle_t*) a )->si < ( (const metaTriangle_t*) b )->si ) {
1812                 return 1;
1813         }
1814         else if ( ( (const metaTriangle_t*) a )->si > ( (const metaTriangle_t*) b )->si ) {
1815                 return -1;
1816         }
1817
1818         /* then fog */
1819         else if ( ( (const metaTriangle_t*) a )->fogNum < ( (const metaTriangle_t*) b )->fogNum ) {
1820                 return 1;
1821         }
1822         else if ( ( (const metaTriangle_t*) a )->fogNum > ( (const metaTriangle_t*) b )->fogNum ) {
1823                 return -1;
1824         }
1825
1826         /* then plane */
1827         #if 0
1828         else if ( npDegrees == 0.0f && ( (const metaTriangle_t*) a )->si->nonplanar == qfalse &&
1829                           ( (const metaTriangle_t*) a )->planeNum >= 0 && ( (const metaTriangle_t*) a )->planeNum >= 0 ) {
1830                 if ( ( (const metaTriangle_t*) a )->plane[ 3 ] < ( (const metaTriangle_t*) b )->plane[ 3 ] ) {
1831                         return 1;
1832                 }
1833                 else if ( ( (const metaTriangle_t*) a )->plane[ 3 ] > ( (const metaTriangle_t*) b )->plane[ 3 ] ) {
1834                         return -1;
1835                 }
1836                 else if ( ( (const metaTriangle_t*) a )->plane[ 0 ] < ( (const metaTriangle_t*) b )->plane[ 0 ] ) {
1837                         return 1;
1838                 }
1839                 else if ( ( (const metaTriangle_t*) a )->plane[ 0 ] > ( (const metaTriangle_t*) b )->plane[ 0 ] ) {
1840                         return -1;
1841                 }
1842                 else if ( ( (const metaTriangle_t*) a )->plane[ 1 ] < ( (const metaTriangle_t*) b )->plane[ 1 ] ) {
1843                         return 1;
1844                 }
1845                 else if ( ( (const metaTriangle_t*) a )->plane[ 1 ] > ( (const metaTriangle_t*) b )->plane[ 1 ] ) {
1846                         return -1;
1847                 }
1848                 else if ( ( (const metaTriangle_t*) a )->plane[ 2 ] < ( (const metaTriangle_t*) b )->plane[ 2 ] ) {
1849                         return 1;
1850                 }
1851                 else if ( ( (const metaTriangle_t*) a )->plane[ 2 ] > ( (const metaTriangle_t*) b )->plane[ 2 ] ) {
1852                         return -1;
1853                 }
1854         }
1855         #endif
1856
1857         /* then position in world */
1858
1859         /* find mins */
1860         VectorSet( aMins, 999999, 999999, 999999 );
1861         VectorSet( bMins, 999999, 999999, 999999 );
1862         for ( i = 0; i < 3; i++ )
1863         {
1864                 av = ( (const metaTriangle_t*) a )->indexes[ i ];
1865                 bv = ( (const metaTriangle_t*) b )->indexes[ i ];
1866                 for ( j = 0; j < 3; j++ )
1867                 {
1868                         if ( metaVerts[ av ].xyz[ j ] < aMins[ j ] ) {
1869                                 aMins[ j ] = metaVerts[ av ].xyz[ j ];
1870                         }
1871                         if ( metaVerts[ bv ].xyz[ j ] < bMins[ j ] ) {
1872                                 bMins[ j ] = metaVerts[ bv ].xyz[ j ];
1873                         }
1874                 }
1875         }
1876
1877         /* test it */
1878         for ( i = 0; i < 3; i++ )
1879         {
1880                 if ( aMins[ i ] < bMins[ i ] ) {
1881                         return 1;
1882                 }
1883                 else if ( aMins[ i ] > bMins[ i ] ) {
1884                         return -1;
1885                 }
1886         }
1887
1888         /* functionally equivalent */
1889         return 0;
1890 }
1891
1892
1893
1894 /*
1895    MergeMetaTriangles()
1896    merges meta triangles into drawsurfaces
1897  */
1898
1899 void MergeMetaTriangles( void ){
1900         int i, j, fOld, start, numAdded;
1901         metaTriangle_t      *head, *end;
1902
1903
1904         /* only do this if there are meta triangles */
1905         if ( numMetaTriangles <= 0 ) {
1906                 return;
1907         }
1908
1909         /* note it */
1910         Sys_FPrintf( SYS_VRB, "--- MergeMetaTriangles ---\n" );
1911
1912         /* sort the triangles by shader major, fognum minor */
1913         qsort( metaTriangles, numMetaTriangles, sizeof( metaTriangle_t ), CompareMetaTriangles );
1914
1915         /* init pacifier */
1916         fOld = -1;
1917         start = I_FloatTime();
1918         numAdded = 0;
1919
1920         /* merge */
1921         for ( i = 0, j = 0; i < numMetaTriangles; i = j )
1922         {
1923                 /* get head of list */
1924                 head = &metaTriangles[ i ];
1925
1926                 /* skip this triangle if it has already been merged */
1927                 if ( head->si == NULL ) {
1928                         continue;
1929                 }
1930
1931                 /* find end */
1932                 if ( j <= i ) {
1933                         for ( j = i + 1; j < numMetaTriangles; j++ )
1934                         {
1935                                 /* get end of list */
1936                                 end = &metaTriangles[ j ];
1937                                 if ( head->si != end->si || head->fogNum != end->fogNum ) {
1938                                         break;
1939                                 }
1940                         }
1941                 }
1942
1943                 /* try to merge this list of possible merge candidates */
1944                 MetaTrianglesToSurface( ( j - i ), head, &fOld, &numAdded );
1945         }
1946
1947         /* clear meta triangle list */
1948         ClearMetaTriangles();
1949
1950         /* print time */
1951         if ( i ) {
1952                 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) ( I_FloatTime() - start ) );
1953         }
1954
1955         /* emit some stats */
1956         Sys_FPrintf( SYS_VRB, "%9d surfaces merged\n", numMergedSurfaces );
1957         Sys_FPrintf( SYS_VRB, "%9d vertexes merged\n", numMergedVerts );
1958 }