1 /* -------------------------------------------------------------------------------
3 Copyright (C) 1999-2007 id Software, Inc. and contributors.
4 For a list of contributors, see the accompanying CONTRIBUTORS file.
6 This file is part of GtkRadiant.
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.
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.
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
22 ----------------------------------------------------------------------------------
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."
27 ------------------------------------------------------------------------------- */
32 #define SURFACE_META_C
41 #define LIGHTMAP_EXCEEDED -1
44 #define ST_EXCEEDED -4
45 #define UNSUITABLE_TRIANGLE -10
46 #define VERTS_EXCEEDED -1000
47 #define INDEXES_EXCEEDED -2000
49 #define GROW_META_VERTS 1024
50 #define GROW_META_TRIANGLES 1024
52 static int numMetaSurfaces, numPatchMetaSurfaces;
54 static int maxMetaVerts = 0;
55 static int numMetaVerts = 0;
56 static int firstSearchMetaVert = 0;
57 static bspDrawVert_t *metaVerts = NULL;
59 static int maxMetaTriangles = 0;
60 static int numMetaTriangles = 0;
61 static metaTriangle_t *metaTriangles = NULL;
67 called before staring a new entity to clear out the triangle list
70 void ClearMetaTriangles( void )
80 finds a matching metavertex in the global list, returning its index
83 static int FindMetaVertex( bspDrawVert_t *src )
86 bspDrawVert_t *v, *temp;
89 /* try to find an existing drawvert */
90 for( i = firstSearchMetaVert, v = &metaVerts[ i ]; i < numMetaVerts; i++, v++ )
92 if( memcmp( src, v, sizeof( bspDrawVert_t ) ) == 0 )
97 if( numMetaVerts >= maxMetaVerts )
99 /* reallocate more room */
100 maxMetaVerts += GROW_META_VERTS;
101 temp = safe_malloc( maxMetaVerts * sizeof( bspDrawVert_t ) );
102 if( metaVerts != NULL )
104 memcpy( temp, metaVerts, numMetaVerts * sizeof( bspDrawVert_t ) );
110 /* add the triangle */
111 memcpy( &metaVerts[ numMetaVerts ], src, sizeof( bspDrawVert_t ) );
114 /* return the count */
115 return (numMetaVerts - 1);
122 adds a new meta triangle, allocating more memory if necessary
125 static int AddMetaTriangle( void )
127 metaTriangle_t *temp;
131 if( numMetaTriangles >= maxMetaTriangles )
133 /* reallocate more room */
134 maxMetaTriangles += GROW_META_TRIANGLES;
135 temp = safe_malloc( maxMetaTriangles * sizeof( metaTriangle_t ) );
136 if( metaTriangles != NULL )
138 memcpy( temp, metaTriangles, numMetaTriangles * sizeof( metaTriangle_t ) );
139 free( metaTriangles );
141 metaTriangles = temp;
144 /* increment and return */
146 return numMetaTriangles - 1;
153 finds a matching metatriangle in the global list,
154 otherwise adds it and returns the index to the metatriangle
157 int FindMetaTriangle( metaTriangle_t *src, bspDrawVert_t *a, bspDrawVert_t *b, bspDrawVert_t *c, int planeNum )
164 /* detect degenerate triangles fixme: do something proper here */
165 VectorSubtract( a->xyz, b->xyz, dir );
166 if( VectorLength( dir ) < 0.125f )
168 VectorSubtract( b->xyz, c->xyz, dir );
169 if( VectorLength( dir ) < 0.125f )
171 VectorSubtract( c->xyz, a->xyz, dir );
172 if( VectorLength( dir ) < 0.125f )
178 /* because of precision issues with small triangles, try to use the specified plane */
179 src->planeNum = planeNum;
180 VectorCopy( mapplanes[ planeNum ].normal, src->plane );
181 src->plane[ 3 ] = mapplanes[ planeNum ].dist;
185 /* calculate a plane from the triangle's points (and bail if a plane can't be constructed) */
187 if( PlaneFromPoints( src->plane, a->xyz, b->xyz, c->xyz ) == qfalse )
191 /* ydnar 2002-10-03: repair any bogus normals (busted ase import kludge) */
192 if( VectorLength( a->normal ) <= 0.0f )
193 VectorCopy( src->plane, a->normal );
194 if( VectorLength( b->normal ) <= 0.0f )
195 VectorCopy( src->plane, b->normal );
196 if( VectorLength( c->normal ) <= 0.0f )
197 VectorCopy( src->plane, c->normal );
199 /* ydnar 2002-10-04: set lightmap axis if not already set */
200 if( !(src->si->compileFlags & C_VERTEXLIT) &&
201 src->lightmapAxis[ 0 ] == 0.0f && src->lightmapAxis[ 1 ] == 0.0f && src->lightmapAxis[ 2 ] == 0.0f )
203 /* the shader can specify an explicit lightmap axis */
204 if( src->si->lightmapAxis[ 0 ] || src->si->lightmapAxis[ 1 ] || src->si->lightmapAxis[ 2 ] )
205 VectorCopy( src->si->lightmapAxis, src->lightmapAxis );
207 /* new axis-finding code */
209 CalcLightmapAxis( src->plane, src->lightmapAxis );
212 /* fill out the src triangle */
213 src->indexes[ 0 ] = FindMetaVertex( a );
214 src->indexes[ 1 ] = FindMetaVertex( b );
215 src->indexes[ 2 ] = FindMetaVertex( c );
217 /* try to find an existing triangle */
218 #ifdef USE_EXHAUSTIVE_SEARCH
224 for( i = 0, tri = metaTriangles; i < numMetaTriangles; i++, tri++ )
226 if( memcmp( src, tri, sizeof( metaTriangle_t ) ) == 0 )
232 /* get a new triangle */
233 triIndex = AddMetaTriangle();
235 /* add the triangle */
236 memcpy( &metaTriangles[ triIndex ], src, sizeof( metaTriangle_t ) );
238 /* return the triangle index */
245 SurfaceToMetaTriangles()
246 converts a classified surface to metatriangles
249 static void SurfaceToMetaTriangles( mapDrawSurface_t *ds )
253 bspDrawVert_t a, b, c;
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 )
263 /* speed at the expense of memory */
264 firstSearchMetaVert = numMetaVerts;
266 /* only handle valid surfaces */
267 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 )
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 ] )
277 //% Sys_Printf( "%d! ", ds->numVerts );
281 /* build a metatriangle */
282 src.si = ds->shaderInfo;
283 src.side = (ds->sideRef != NULL ? ds->sideRef->side : NULL);
284 src.entityNum = ds->entityNum;
285 src.surfaceNum = ds->surfaceNum;
286 src.planeNum = ds->planeNum;
287 src.castShadows = ds->castShadows;
288 src.recvShadows = ds->recvShadows;
289 src.fogNum = ds->fogNum;
290 src.sampleSize = ds->sampleSize;
291 src.shadeAngleDegrees = ds->shadeAngleDegrees;
292 VectorCopy( ds->lightmapAxis, src.lightmapAxis );
295 memcpy( &a, &ds->verts[ ds->indexes[ i ] ], sizeof( a ) );
296 memcpy( &b, &ds->verts[ ds->indexes[ i + 1 ] ], sizeof( b ) );
297 memcpy( &c, &ds->verts[ ds->indexes[ i + 2 ] ], sizeof( c ) );
298 FindMetaTriangle( &src, &a, &b, &c, ds->planeNum );
305 /* clear the surface (free verts and indexes, sets it to SURFACE_BAD) */
312 TriangulatePatchSurface()
313 creates triangles from a patch
316 void TriangulatePatchSurface( entity_t *e , mapDrawSurface_t *ds )
318 int iterations, x, y, pw[ 5 ], r;
319 mapDrawSurface_t *dsNew;
320 mesh_t src, *subdivided, *mesh;
323 int patchSubdivision;
325 /* vortex: _patchMeta, _patchQuality, _patchSubdivide support */
326 forcePatchMeta = IntForKey(e, "_patchMeta" );
328 forcePatchMeta = IntForKey(e, "patchMeta" );
329 patchQuality = IntForKey(e, "_patchQuality" );
331 patchQuality = IntForKey(e, "patchQuality" );
334 patchSubdivision = IntForKey(e, "_patchSubdivide" );
335 if (!patchSubdivision)
336 patchSubdivision = IntForKey(e, "patchSubdivide" );
338 /* try to early out */
339 if(ds->numVerts == 0 || ds->type != SURFACE_PATCH || ( patchMeta == qfalse && !forcePatchMeta) )
341 /* make a mesh from the drawsurf */
342 src.width = ds->patchWidth;
343 src.height = ds->patchHeight;
344 src.verts = ds->verts;
345 //% subdivided = SubdivideMesh( src, 8, 999 );
346 if (patchSubdivision)
347 iterations = IterationsForCurve( ds->longestCurve, patchSubdivision );
349 iterations = IterationsForCurve( ds->longestCurve, patchSubdivisions / patchQuality );
351 subdivided = SubdivideMesh2( src, iterations ); //% ds->maxIterations
353 /* fit it to the curve and remove colinear verts on rows/columns */
354 PutMeshOnCurve( *subdivided );
355 mesh = RemoveLinearMeshColumnsRows( subdivided );
356 FreeMesh( subdivided );
357 //% MakeMeshNormals( mesh );
359 /* make a copy of the drawsurface */
360 dsNew = AllocDrawSurface( SURFACE_META );
361 memcpy( dsNew, ds, sizeof( *ds ) );
363 /* if the patch is nonsolid, then discard it */
364 if( !(ds->shaderInfo->compileFlags & C_SOLID) )
367 /* set new pointer */
370 /* basic transmogrification */
371 ds->type = SURFACE_META;
373 ds->indexes = safe_malloc( mesh->width * mesh->height * 6 * sizeof( int ) );
375 /* copy the verts in */
376 ds->numVerts = (mesh->width * mesh->height);
377 ds->verts = mesh->verts;
379 /* iterate through the mesh quads */
380 for( y = 0; y < (mesh->height - 1); y++ )
382 for( x = 0; x < (mesh->width - 1); x++ )
385 pw[ 0 ] = x + (y * mesh->width);
386 pw[ 1 ] = x + ((y + 1) * mesh->width);
387 pw[ 2 ] = x + 1 + ((y + 1) * mesh->width);
388 pw[ 3 ] = x + 1 + (y * mesh->width);
389 pw[ 4 ] = x + (y * mesh->width); /* same as pw[ 0 ] */
394 /* make first triangle */
395 ds->indexes[ ds->numIndexes++ ] = pw[ r + 0 ];
396 ds->indexes[ ds->numIndexes++ ] = pw[ r + 1 ];
397 ds->indexes[ ds->numIndexes++ ] = pw[ r + 2 ];
399 /* make second triangle */
400 ds->indexes[ ds->numIndexes++ ] = pw[ r + 0 ];
401 ds->indexes[ ds->numIndexes++ ] = pw[ r + 2 ];
402 ds->indexes[ ds->numIndexes++ ] = pw[ r + 3 ];
406 /* free the mesh, but not the verts */
410 numPatchMetaSurfaces++;
413 ClassifySurfaces( 1, ds );
416 #define TINY_AREA 1.0f
417 #define MAXAREA_MAXTRIES 8
418 int MaxAreaIndexes(bspDrawVert_t *vert, int cnt, int *indexes)
420 int r, s, t, bestR = 0, bestS = 1, bestT = 2;
422 double A, bestA = -1, V, bestV = -1;
423 vec3_t ab, ac, bc, cross;
430 /* calculate total area */
432 for(i = 1; i+1 < cnt; ++i)
434 VectorSubtract(vert[i].xyz, vert[0].xyz, ab);
435 VectorSubtract(vert[i+1].xyz, vert[0].xyz, ac);
436 CrossProduct(ab, ac, cross);
437 A += VectorLength(cross);
440 for(i = 0; i < cnt; ++i)
442 VectorSubtract(vert[(i+1)%cnt].xyz, vert[i].xyz, ab);
443 V += VectorLength(ab);
446 /* calculate shift width from the area sensibly, assuming the polygon
447 * fits about 25% of the screen in both dimensions
448 * we assume 1280x1024
449 * 1 pixel is then about sqrt(A) / (0.25 * screenwidth)
450 * 8 pixels are then about sqrt(A) / (0.25 * 1280) * 8
451 * 8 pixels are then about sqrt(A) * 0.025
453 shiftWidth = sqrt(A) * 0.0125;
454 /* 3->1 6->2 12->3 ... */
455 if(A - ceil(log(cnt/1.5) / log(2)) * V * shiftWidth * 2 < 0)
457 /* printf("Small triangle detected (area %f, circumference %f), adjusting shiftWidth from %f to ", A, V, shiftWidth); */
458 shiftWidth = A / (ceil(log(cnt/1.5) / log(2)) * V * 2);
459 /* printf("%f\n", shiftWidth); */
462 /* find the triangle with highest area */
463 for(r = 0; r+2 < cnt; ++r)
464 for(s = r+1; s+1 < cnt; ++s)
465 for(t = s+1; t < cnt; ++t)
467 VectorSubtract(vert[s].xyz, vert[r].xyz, ab);
468 VectorSubtract(vert[t].xyz, vert[r].xyz, ac);
469 VectorSubtract(vert[t].xyz, vert[s].xyz, bc);
470 CrossProduct(ab, ac, cross);
471 A = VectorLength(cross);
473 V = A - (VectorLength(ab) - VectorLength(ac) - VectorLength(bc)) * shiftWidth;
474 /* value = A - circumference * shiftWidth, i.e. we back out by shiftWidth units from each side, to prevent too acute triangles */
475 /* this kind of simulates "number of shiftWidth*shiftWidth fragments in the triangle not touched by an edge" */
477 if(bestA < 0 || V > bestV)
489 printf("value was REALLY bad\n");
492 for(try = 0; try < MAXAREA_MAXTRIES; ++try)
496 bestR = rand() % cnt;
497 bestS = rand() % cnt;
498 bestT = rand() % cnt;
499 if(bestR == bestS || bestR == bestT || bestS == bestT)
502 // abc acb bac bca cab cba
509 // abc acb abc bca acb bca
516 // abc abc abc bac abc bac
523 // abc abc abc abc abc abc
525 VectorSubtract(vert[bestS].xyz, vert[bestR].xyz, ab);
526 VectorSubtract(vert[bestT].xyz, vert[bestR].xyz, ac);
527 CrossProduct(ab, ac, cross);
528 bestA = VectorLength(cross);
531 if(bestA < TINY_AREA)
532 /* the biggest triangle is degenerate - then every other is too, and the other algorithms wouldn't generate anything useful either */
536 indexes[i++] = bestR;
537 indexes[i++] = bestS;
538 indexes[i++] = bestT;
541 /* identify the other fragments */
543 /* full polygon without triangle (bestR,bestS,bestT) = three new polygons:
549 j = MaxAreaIndexes(vert + bestR, bestS - bestR + 1, indexes + i);
555 /* uses 3*(bestS-bestR+1)-6 */
556 j = MaxAreaIndexes(vert + bestS, bestT - bestS + 1, indexes + i);
562 /* uses 3*(bestT-bestS+1)-6 */
564 /* can'bestT recurse this one directly... therefore, buffering */
565 if(cnt + bestR - bestT + 1 >= 3)
567 buf = safe_malloc(sizeof(*vert) * (cnt + bestR - bestT + 1));
568 memcpy(buf, vert + bestT, sizeof(*vert) * (cnt - bestT));
569 memcpy(buf + (cnt - bestT), vert, sizeof(*vert) * (bestR + 1));
570 j = MaxAreaIndexes(buf, cnt + bestR - bestT + 1, indexes + i);
578 indexes[i] = (indexes[i] + bestT) % cnt;
579 /* uses 3*(cnt+bestR-bestT+1)-6 */
583 /* together 3 + 3*(cnt+3) - 18 = 3*cnt-6 q.e.d. */
591 MaxAreaFaceSurface() - divVerent
592 creates a triangle list using max area indexes
595 void MaxAreaFaceSurface(mapDrawSurface_t *ds)
598 /* try to early out */
599 if( !ds->numVerts || (ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL) )
602 /* is this a simple triangle? */
603 if( ds->numVerts == 3 )
606 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
607 VectorSet( ds->indexes, 0, 1, 2 );
608 numMaxAreaSurfaces++;
613 ds->numIndexes = 3 * ds->numVerts - 6;
614 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
615 n = MaxAreaIndexes(ds->verts, ds->numVerts, ds->indexes);
618 /* whatever we do, it's degenerate */
621 StripFaceSurface(ds);
627 numMaxAreaSurfaces++;
630 ClassifySurfaces( 1, ds );
635 FanFaceSurface() - ydnar
636 creates a tri-fan from a brush face winding
637 loosely based on SurfaceAsTriFan()
640 void FanFaceSurface( mapDrawSurface_t *ds )
642 int i, j, k, a, b, c, color[ MAX_LIGHTMAPS ][ 4 ];
643 bspDrawVert_t *verts, *centroid, *dv;
647 /* try to early out */
648 if( !ds->numVerts || (ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL) )
651 /* add a new vertex at the beginning of the surface */
652 verts = safe_malloc( (ds->numVerts + 1) * sizeof( bspDrawVert_t ) );
653 memset( verts, 0, sizeof( bspDrawVert_t ) );
654 memcpy( &verts[ 1 ], ds->verts, ds->numVerts * sizeof( bspDrawVert_t ) );
658 /* add up the drawverts to create a centroid */
659 centroid = &verts[ 0 ];
660 memset( color, 0, 4 * MAX_LIGHTMAPS * sizeof( int ) );
661 for( i = 1, dv = &verts[ 1 ]; i < (ds->numVerts + 1); i++, dv++ )
663 VectorAdd( centroid->xyz, dv->xyz, centroid->xyz );
664 VectorAdd( centroid->normal, dv->normal, centroid->normal );
665 for( j = 0; j < 4; j++ )
667 for( k = 0; k < MAX_LIGHTMAPS; k++ )
668 color[ k ][ j ] += dv->color[ k ][ j ];
671 centroid->st[ j ] += dv->st[ j ];
672 for( k = 0; k < MAX_LIGHTMAPS; k++ )
673 centroid->lightmap[ k ][ j ] += dv->lightmap[ k ][ j ];
678 /* average the centroid */
679 iv = 1.0f / ds->numVerts;
680 VectorScale( centroid->xyz, iv, centroid->xyz );
681 if( VectorNormalize( centroid->normal, centroid->normal ) <= 0 )
682 VectorCopy( verts[ 1 ].normal, centroid->normal );
683 for( j = 0; j < 4; j++ )
685 for( k = 0; k < MAX_LIGHTMAPS; k++ )
687 color[ k ][ j ] /= ds->numVerts;
688 centroid->color[ k ][ j ] = (color[ k ][ j ] < 255.0f ? color[ k ][ j ] : 255);
692 centroid->st[ j ] *= iv;
693 for( k = 0; k < MAX_LIGHTMAPS; k++ )
694 centroid->lightmap[ k ][ j ] *= iv;
698 /* add to vert count */
701 /* fill indexes in triangle fan order */
703 ds->indexes = safe_malloc( ds->numVerts * 3 * sizeof( int ) );
704 for( i = 1; i < ds->numVerts; i++ )
708 c = (i + 1) % ds->numVerts;
710 ds->indexes[ ds->numIndexes++ ] = a;
711 ds->indexes[ ds->numIndexes++ ] = b;
712 ds->indexes[ ds->numIndexes++ ] = c;
719 ClassifySurfaces( 1, ds );
725 StripFaceSurface() - ydnar
726 attempts to create a valid tri-strip w/o degenerate triangles from a brush face winding
727 based on SurfaceAsTriStrip()
730 #define MAX_INDEXES 1024
732 void StripFaceSurface( mapDrawSurface_t *ds )
734 int i, r, least, rotate, numIndexes, ni, a, b, c, indexes[ MAX_INDEXES ];
738 /* try to early out */
739 if( !ds->numVerts || (ds->type != SURFACE_FACE && ds->type != SURFACE_DECAL) )
742 /* is this a simple triangle? */
743 if( ds->numVerts == 3 )
746 VectorSet( indexes, 0, 1, 2 );
750 /* ydnar: find smallest coordinate */
752 if( ds->shaderInfo != NULL && ds->shaderInfo->autosprite == qfalse )
754 for( i = 0; i < ds->numVerts; i++ )
757 v1 = ds->verts[ i ].xyz;
758 v2 = ds->verts[ least ].xyz;
761 if( v1[ 0 ] < v2[ 0 ] ||
762 (v1[ 0 ] == v2[ 0 ] && v1[ 1 ] < v2[ 1 ]) ||
763 (v1[ 0 ] == v2[ 0 ] && v1[ 1 ] == v2[ 1 ] && v1[ 2 ] < v2[ 2 ]) )
768 /* determine the triangle strip order */
769 numIndexes = (ds->numVerts - 2) * 3;
770 if( numIndexes > MAX_INDEXES )
771 Error( "MAX_INDEXES exceeded for surface (%d > %d) (%d verts)", numIndexes, MAX_INDEXES, ds->numVerts );
773 /* try all possible orderings of the points looking for a non-degenerate strip order */
775 for( r = 0; r < ds->numVerts; r++ )
778 rotate = (r + least) % ds->numVerts;
780 /* walk the winding in both directions */
781 for( ni = 0, i = 0; i < ds->numVerts - 2 - i; i++ )
784 a = (ds->numVerts - 1 - i + rotate) % ds->numVerts;
785 b = (i + rotate ) % ds->numVerts;
786 c = (ds->numVerts - 2 - i + rotate) % ds->numVerts;
788 /* test this triangle */
789 if( ds->numVerts > 4 && IsTriangleDegenerate( ds->verts, a, b, c ) )
795 /* handle end case */
796 if( i + 1 != ds->numVerts - 1 - i )
799 a = (ds->numVerts - 2 - i + rotate ) % ds->numVerts;
800 b = (i + rotate ) % ds->numVerts;
801 c = (i + 1 + rotate ) % ds->numVerts;
804 if( ds->numVerts > 4 && IsTriangleDegenerate( ds->verts, a, b, c ) )
813 if( ni == numIndexes )
817 /* if any triangle in the strip is degenerate, render from a centered fan point instead */
818 if( ni < numIndexes )
820 FanFaceSurface( ds );
825 /* copy strip triangle indexes */
826 ds->numIndexes = numIndexes;
827 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
828 memcpy( ds->indexes, indexes, ds->numIndexes * sizeof( int ) );
834 ClassifySurfaces( 1, ds );
840 vortex: prints meta statistics in general output
845 Sys_Printf( "--- EmitMetaStats ---\n" );
846 Sys_Printf( "%9d total meta surfaces\n", numMetaSurfaces );
847 Sys_Printf( "%9d stripped surfaces\n", numStripSurfaces );
848 Sys_Printf( "%9d fanned surfaces\n", numFanSurfaces );
849 Sys_Printf( "%9d maxarea'd surfaces\n", numMaxAreaSurfaces );
850 Sys_Printf( "%9d patch meta surfaces\n", numPatchMetaSurfaces );
851 Sys_Printf( "%9d meta verts\n", numMetaVerts );
852 Sys_Printf( "%9d meta triangles\n", numMetaTriangles );
856 MakeEntityMetaTriangles()
857 builds meta triangles from brush faces (tristrips and fans)
860 void MakeEntityMetaTriangles( entity_t *e )
862 int i, f, fOld, start;
863 mapDrawSurface_t *ds;
867 Sys_FPrintf( SYS_VRB, "--- MakeEntityMetaTriangles ---\n" );
871 start = I_FloatTime();
873 /* walk the list of surfaces in the entity */
874 for( i = e->firstDrawSurf; i < numMapDrawSurfs; i++ )
877 f = 10 * (i - e->firstDrawSurf) / (numMapDrawSurfs - e->firstDrawSurf);
881 Sys_FPrintf( SYS_VRB, "%d...", f );
885 ds = &mapDrawSurfs[ i ];
886 if( ds->numVerts <= 0 )
889 /* ignore autosprite surfaces */
890 if( ds->shaderInfo->autosprite )
893 /* meta this surface? */
894 if( meta == qfalse && ds->shaderInfo->forceMeta == qfalse )
902 if(maxAreaFaceSurface)
903 MaxAreaFaceSurface( ds );
905 StripFaceSurface( ds );
906 SurfaceToMetaTriangles( ds );
910 TriangulatePatchSurface(e, ds );
913 case SURFACE_TRIANGLES:
916 case SURFACE_FORCED_META:
918 SurfaceToMetaTriangles( ds );
927 if( (numMapDrawSurfs - e->firstDrawSurf) )
928 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
930 /* emit some stats */
931 Sys_FPrintf( SYS_VRB, "%9d total meta surfaces\n", numMetaSurfaces );
932 Sys_FPrintf( SYS_VRB, "%9d stripped surfaces\n", numStripSurfaces );
933 Sys_FPrintf( SYS_VRB, "%9d fanned surfaces\n", numFanSurfaces );
934 Sys_FPrintf( SYS_VRB, "%9d maxarea'd surfaces\n", numMaxAreaSurfaces );
935 Sys_FPrintf( SYS_VRB, "%9d patch meta surfaces\n", numPatchMetaSurfaces );
936 Sys_FPrintf( SYS_VRB, "%9d meta verts\n", numMetaVerts );
937 Sys_FPrintf( SYS_VRB, "%9d meta triangles\n", numMetaTriangles );
940 TidyEntitySurfaces( e );
947 sets up an edge structure from a plane and 2 points that the edge ab falls lies in
950 typedef struct edge_s
953 vec_t length, kingpinLength;
959 void CreateEdge( vec4_t plane, vec3_t a, vec3_t b, edge_t *edge )
961 /* copy edge origin */
962 VectorCopy( a, edge->origin );
964 /* create vector aligned with winding direction of edge */
965 VectorSubtract( b, a, edge->edge );
967 if( fabs( edge->edge[ 0 ] ) > fabs( edge->edge[ 1 ] ) && fabs( edge->edge[ 0 ] ) > fabs( edge->edge[ 2 ] ) )
969 else if( fabs( edge->edge[ 1 ] ) > fabs( edge->edge[ 0 ] ) && fabs( edge->edge[ 1 ] ) > fabs( edge->edge[ 2 ] ) )
973 edge->kingpinLength = edge->edge[ edge->kingpin ];
975 VectorNormalize( edge->edge, edge->edge );
976 edge->edge[ 3 ] = DotProduct( a, edge->edge );
977 edge->length = DotProduct( b, edge->edge ) - edge->edge[ 3 ];
979 /* create perpendicular plane that edge lies in */
980 CrossProduct( plane, edge->edge, edge->plane );
981 edge->plane[ 3 ] = DotProduct( a, edge->plane );
988 fixes t-junctions on meta triangles
991 #define TJ_PLANE_EPSILON (1.0f / 8.0f)
992 #define TJ_EDGE_EPSILON (1.0f / 8.0f)
993 #define TJ_POINT_EPSILON (1.0f / 8.0f)
995 void FixMetaTJunctions( void )
997 int i, j, k, f, fOld, start, vertIndex, triIndex, numTJuncs;
998 metaTriangle_t *tri, *newTri;
1000 bspDrawVert_t *a, *b, *c, junc;
1007 /* this code is crap; revisit later */
1011 Sys_FPrintf( SYS_VRB, "--- FixMetaTJunctions ---\n" );
1015 start = I_FloatTime();
1017 /* walk triangle list */
1019 for( i = 0; i < numMetaTriangles; i++ )
1022 tri = &metaTriangles[ i ];
1024 /* print pacifier */
1025 f = 10 * i / numMetaTriangles;
1029 Sys_FPrintf( SYS_VRB, "%d...", f );
1032 /* attempt to early out */
1034 if( (si->compileFlags & C_NODRAW) || si->autosprite || si->notjunc )
1037 /* calculate planes */
1038 VectorCopy( tri->plane, plane );
1039 plane[ 3 ] = tri->plane[ 3 ];
1040 CreateEdge( plane, metaVerts[ tri->indexes[ 0 ] ].xyz, metaVerts[ tri->indexes[ 1 ] ].xyz, &edges[ 0 ] );
1041 CreateEdge( plane, metaVerts[ tri->indexes[ 1 ] ].xyz, metaVerts[ tri->indexes[ 2 ] ].xyz, &edges[ 1 ] );
1042 CreateEdge( plane, metaVerts[ tri->indexes[ 2 ] ].xyz, metaVerts[ tri->indexes[ 0 ] ].xyz, &edges[ 2 ] );
1044 /* walk meta vert list */
1045 for( j = 0; j < numMetaVerts; j++ )
1048 VectorCopy( metaVerts[ j ].xyz, pt );
1050 /* determine if point lies in the triangle's plane */
1051 dist = DotProduct( pt, plane ) - plane[ 3 ];
1052 if( fabs( dist ) > TJ_PLANE_EPSILON )
1055 /* skip this point if it already exists in the triangle */
1056 for( k = 0; k < 3; k++ )
1058 if( fabs( pt[ 0 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 0 ] ) <= TJ_POINT_EPSILON &&
1059 fabs( pt[ 1 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 1 ] ) <= TJ_POINT_EPSILON &&
1060 fabs( pt[ 2 ] - metaVerts[ tri->indexes[ k ] ].xyz[ 2 ] ) <= TJ_POINT_EPSILON )
1067 for( k = 0; k < 3; k++ )
1069 /* ignore bogus edges */
1070 if( fabs( edges[ k ].kingpinLength ) < TJ_EDGE_EPSILON )
1073 /* determine if point lies on the edge */
1074 dist = DotProduct( pt, edges[ k ].plane ) - edges[ k ].plane[ 3 ];
1075 if( fabs( dist ) > TJ_EDGE_EPSILON )
1078 /* determine how far along the edge the point lies */
1079 amount = (pt[ edges[ k ].kingpin ] - edges[ k ].origin[ edges[ k ].kingpin ]) / edges[ k ].kingpinLength;
1080 if( amount <= 0.0f || amount >= 1.0f )
1084 dist = DotProduct( pt, edges[ k ].edge ) - edges[ k ].edge[ 3 ];
1085 if( dist <= -0.0f || dist >= edges[ k ].length )
1087 amount = dist / edges[ k ].length;
1090 /* the edge opposite the zero-weighted vertex was hit, so use that as an amount */
1091 a = &metaVerts[ tri->indexes[ k % 3 ] ];
1092 b = &metaVerts[ tri->indexes[ (k + 1) % 3 ] ];
1093 c = &metaVerts[ tri->indexes[ (k + 2) % 3 ] ];
1096 LerpDrawVertAmount( a, b, amount, &junc );
1097 VectorCopy( pt, junc.xyz );
1099 /* compare against existing verts */
1100 if( VectorCompare( junc.xyz, a->xyz ) || VectorCompare( junc.xyz, b->xyz ) || VectorCompare( junc.xyz, c->xyz ) )
1103 /* see if we can just re-use the existing vert */
1104 if( !memcmp( &metaVerts[ j ], &junc, sizeof( junc ) ) )
1108 /* find new vertex (note: a and b are invalid pointers after this) */
1109 firstSearchMetaVert = numMetaVerts;
1110 vertIndex = FindMetaVertex( &junc );
1115 /* make new triangle */
1116 triIndex = AddMetaTriangle();
1121 tri = &metaTriangles[ i ];
1122 newTri = &metaTriangles[ triIndex ];
1124 /* copy the triangle */
1125 memcpy( newTri, tri, sizeof( *tri ) );
1128 tri->indexes[ (k + 1) % 3 ] = vertIndex;
1129 newTri->indexes[ k ] = vertIndex;
1131 /* recalculate edges */
1132 CreateEdge( plane, metaVerts[ tri->indexes[ 0 ] ].xyz, metaVerts[ tri->indexes[ 1 ] ].xyz, &edges[ 0 ] );
1133 CreateEdge( plane, metaVerts[ tri->indexes[ 1 ] ].xyz, metaVerts[ tri->indexes[ 2 ] ].xyz, &edges[ 1 ] );
1134 CreateEdge( plane, metaVerts[ tri->indexes[ 2 ] ].xyz, metaVerts[ tri->indexes[ 0 ] ].xyz, &edges[ 2 ] );
1137 metaVerts[ vertIndex ].color[ 0 ][ 0 ] = 255;
1138 metaVerts[ vertIndex ].color[ 0 ][ 1 ] = 204;
1139 metaVerts[ vertIndex ].color[ 0 ][ 2 ] = 0;
1141 /* add to counter and end processing of this vert */
1149 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
1151 /* emit some stats */
1152 Sys_FPrintf( SYS_VRB, "%9d T-junctions added\n", numTJuncs );
1158 SmoothMetaTriangles()
1159 averages coincident vertex normals in the meta triangles
1162 #define MAX_SAMPLES 256
1163 #define THETA_EPSILON 0.000001
1164 #define EQUAL_NORMAL_EPSILON 0.01
1166 void SmoothMetaTriangles( void )
1168 int i, j, k, f, fOld, start, cs, numVerts, numVotes, numSmoothed;
1169 float shadeAngle, defaultShadeAngle, maxShadeAngle, dot, testAngle;
1170 metaTriangle_t *tri;
1173 vec3_t average, diff;
1174 int indexes[ MAX_SAMPLES ];
1175 vec3_t votes[ MAX_SAMPLES ];
1178 Sys_FPrintf( SYS_VRB, "--- SmoothMetaTriangles ---\n" );
1180 /* allocate shade angle table */
1181 shadeAngles = safe_malloc( numMetaVerts * sizeof( float ) );
1182 memset( shadeAngles, 0, numMetaVerts * sizeof( float ) );
1184 /* allocate smoothed table */
1185 cs = (numMetaVerts / 8) + 1;
1186 smoothed = safe_malloc( cs );
1187 memset( smoothed, 0, cs );
1189 /* set default shade angle */
1190 defaultShadeAngle = DEG2RAD( npDegrees );
1191 maxShadeAngle = 0.0f;
1193 /* run through every surface and flag verts belonging to non-lightmapped surfaces
1194 and set per-vertex smoothing angle */
1195 for( i = 0, tri = &metaTriangles[ i ]; i < numMetaTriangles; i++, tri++ )
1197 shadeAngle = defaultShadeAngle;
1199 /* get shade angle from shader */
1200 if( tri->si->shadeAngleDegrees > 0.0f )
1201 shadeAngle = DEG2RAD( tri->si->shadeAngleDegrees );
1202 /* get shade angle from entity */
1203 else if( tri->shadeAngleDegrees > 0.0f )
1204 shadeAngle = DEG2RAD( tri->shadeAngleDegrees );
1206 if( shadeAngle <= 0.0f )
1207 shadeAngle = defaultShadeAngle;
1209 if( shadeAngle > maxShadeAngle )
1210 maxShadeAngle = shadeAngle;
1212 /* flag its verts */
1213 for( j = 0; j < 3; j++ )
1215 shadeAngles[ tri->indexes[ j ] ] = shadeAngle;
1216 if( shadeAngle <= 0 )
1217 smoothed[ tri->indexes[ j ] >> 3 ] |= (1 << (tri->indexes[ j ] & 7));
1221 /* bail if no surfaces have a shade angle */
1222 if( maxShadeAngle <= 0 )
1224 Sys_FPrintf( SYS_VRB, "No smoothing angles specified, aborting\n" );
1225 free( shadeAngles );
1232 start = I_FloatTime();
1234 /* go through the list of vertexes */
1236 for( i = 0; i < numMetaVerts; i++ )
1238 /* print pacifier */
1239 f = 10 * i / numMetaVerts;
1243 Sys_FPrintf( SYS_VRB, "%d...", f );
1246 /* already smoothed? */
1247 if( smoothed[ i >> 3 ] & (1 << (i & 7)) )
1251 VectorClear( average );
1255 /* build a table of coincident vertexes */
1256 for( j = i; j < numMetaVerts && numVerts < MAX_SAMPLES; j++ )
1258 /* already smoothed? */
1259 if( smoothed[ j >> 3 ] & (1 << (j & 7)) )
1263 if( VectorCompare( metaVerts[ i ].xyz, metaVerts[ j ].xyz ) == qfalse )
1266 /* use smallest shade angle */
1267 shadeAngle = (shadeAngles[ i ] < shadeAngles[ j ] ? shadeAngles[ i ] : shadeAngles[ j ]);
1269 /* check shade angle */
1270 dot = DotProduct( metaVerts[ i ].normal, metaVerts[ j ].normal );
1273 else if( dot < -1.0 )
1275 testAngle = acos( dot ) + THETA_EPSILON;
1276 if( testAngle >= shadeAngle )
1279 /* add to the list */
1280 indexes[ numVerts++ ] = j;
1283 smoothed[ j >> 3 ] |= (1 << (j & 7));
1285 /* see if this normal has already been voted */
1286 for( k = 0; k < numVotes; k++ )
1288 VectorSubtract( metaVerts[ j ].normal, votes[ k ], diff );
1289 if( fabs( diff[ 0 ] ) < EQUAL_NORMAL_EPSILON &&
1290 fabs( diff[ 1 ] ) < EQUAL_NORMAL_EPSILON &&
1291 fabs( diff[ 2 ] ) < EQUAL_NORMAL_EPSILON )
1295 /* add a new vote? */
1296 if( k == numVotes && numVotes < MAX_SAMPLES )
1298 VectorAdd( average, metaVerts[ j ].normal, average );
1299 VectorCopy( metaVerts[ j ].normal, votes[ numVotes ] );
1304 /* don't average for less than 2 verts */
1308 /* average normal */
1309 if( VectorNormalize( average, average ) > 0 )
1312 for( j = 0; j < numVerts; j++ )
1313 VectorCopy( average, metaVerts[ indexes[ j ] ].normal );
1318 /* free the tables */
1319 free( shadeAngles );
1323 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
1325 /* emit some stats */
1326 Sys_FPrintf( SYS_VRB, "%9d smoothed vertexes\n", numSmoothed );
1332 AddMetaVertToSurface()
1333 adds a drawvert to a surface unless an existing vert matching already exists
1334 returns the index of that vert (or < 0 on failure)
1337 int AddMetaVertToSurface( mapDrawSurface_t *ds, bspDrawVert_t *dv1, int *coincident )
1343 /* go through the verts and find a suitable candidate */
1344 for( i = 0; i < ds->numVerts; i++ )
1347 dv2 = &ds->verts[ i ];
1349 /* compare xyz and normal */
1350 if( VectorCompare( dv1->xyz, dv2->xyz ) == qfalse )
1352 if( VectorCompare( dv1->normal, dv2->normal ) == qfalse )
1355 /* good enough at this point */
1358 /* compare texture coordinates and color */
1359 if( dv1->st[ 0 ] != dv2->st[ 0 ] || dv1->st[ 1 ] != dv2->st[ 1 ] )
1361 if( dv1->color[ 0 ][ 3 ] != dv2->color[ 0 ][ 3 ] )
1364 /* found a winner */
1369 /* overflow check */
1370 if( ds->numVerts >= ((ds->shaderInfo->compileFlags & C_VERTEXLIT) ? maxSurfaceVerts : maxLMSurfaceVerts) )
1371 return VERTS_EXCEEDED;
1373 /* made it this far, add the vert and return */
1374 dv2 = &ds->verts[ ds->numVerts++ ];
1376 return (ds->numVerts - 1);
1383 AddMetaTriangleToSurface()
1384 attempts to add a metatriangle to a surface
1385 returns the score of the triangle added
1388 #define AXIS_SCORE 100000
1389 #define AXIS_MIN 100000
1390 #define VERT_SCORE 10000
1391 #define SURFACE_SCORE 1000
1393 #define ST_SCORE2 (2 * (ST_SCORE))
1395 #define ADEQUATE_SCORE ((AXIS_MIN) + 1 * (VERT_SCORE))
1396 #define GOOD_SCORE ((AXIS_MIN) + 2 * (VERT_SCORE) + 4 * (ST_SCORE))
1397 #define PERFECT_SCORE ((AXIS_MIN) + 3 * (VERT_SCORE) + (SURFACE_SCORE) + 4 * (ST_SCORE))
1398 //#define MAX_BBOX_DISTANCE 16
1400 static int AddMetaTriangleToSurface( mapDrawSurface_t *ds, metaTriangle_t *tri, qboolean testAdd )
1402 int i, score, coincident, ai, bi, ci, oldTexRange[ 2 ];
1405 qboolean inTexRange;
1406 mapDrawSurface_t old;
1409 /* overflow check */
1410 if( ds->numIndexes >= maxSurfaceIndexes )
1413 /* test the triangle */
1414 if( ds->entityNum != tri->entityNum ) /* ydnar: added 2002-07-06 */
1416 if( ds->castShadows != tri->castShadows || ds->recvShadows != tri->recvShadows )
1418 if( ds->shaderInfo != tri->si || ds->fogNum != tri->fogNum || ds->sampleSize != tri->sampleSize )
1421 if( !(ds->shaderInfo->compileFlags & C_VERTEXLIT) &&
1422 //% VectorCompare( ds->lightmapAxis, tri->lightmapAxis ) == qfalse )
1423 DotProduct( ds->lightmapAxis, tri->plane ) < 0.25f )
1427 /* planar surfaces will only merge with triangles in the same plane */
1428 if( npDegrees == 0.0f && ds->shaderInfo->nonplanar == qfalse && ds->planeNum >= 0 )
1430 if( VectorCompare( mapplanes[ ds->planeNum ].normal, tri->plane ) == qfalse || mapplanes[ ds->planeNum ].dist != tri->plane[ 3 ] )
1432 if( tri->planeNum >= 0 && tri->planeNum != ds->planeNum )
1436 #if MAX_BBOX_DISTANCE > 0
1437 VectorCopy( ds->mins, mins );
1438 VectorCopy( ds->maxs, maxs );
1439 mins[0] -= MAX_BBOX_DISTANCE;
1440 mins[1] -= MAX_BBOX_DISTANCE;
1441 mins[2] -= MAX_BBOX_DISTANCE;
1442 maxs[0] += MAX_BBOX_DISTANCE;
1443 maxs[1] += MAX_BBOX_DISTANCE;
1444 maxs[2] += MAX_BBOX_DISTANCE;
1445 #define CHECK_1D(mins, v, maxs) ((mins) <= (v) && (v) <= (maxs))
1446 #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]))
1447 VectorCopy(metaVerts[ tri->indexes[ 0 ] ].xyz, p);
1448 if(!CHECK_3D(mins, p, maxs))
1450 VectorCopy(metaVerts[ tri->indexes[ 1 ] ].xyz, p);
1451 if(!CHECK_3D(mins, p, maxs))
1453 VectorCopy(metaVerts[ tri->indexes[ 2 ] ].xyz, p);
1454 if(!CHECK_3D(mins, p, maxs))
1462 /* set initial score */
1463 score = tri->surfaceNum == ds->surfaceNum ? SURFACE_SCORE : 0;
1465 /* score the the dot product of lightmap axis to plane */
1466 if( (ds->shaderInfo->compileFlags & C_VERTEXLIT) || VectorCompare( ds->lightmapAxis, tri->lightmapAxis ) )
1467 score += AXIS_SCORE;
1469 score += AXIS_SCORE * DotProduct( ds->lightmapAxis, tri->plane );
1471 /* preserve old drawsurface if this fails */
1472 memcpy( &old, ds, sizeof( *ds ) );
1474 /* attempt to add the verts */
1476 ai = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 0 ] ], &coincident );
1477 bi = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 1 ] ], &coincident );
1478 ci = AddMetaVertToSurface( ds, &metaVerts[ tri->indexes[ 2 ] ], &coincident );
1480 /* check vertex underflow */
1481 if( ai < 0 || bi < 0 || ci < 0 )
1483 memcpy( ds, &old, sizeof( *ds ) );
1487 /* score coincident vertex count (2003-02-14: changed so this only matters on planar surfaces) */
1488 score += (coincident * VERT_SCORE);
1490 /* add new vertex bounds to mins/maxs */
1491 VectorCopy( ds->mins, mins );
1492 VectorCopy( ds->maxs, maxs );
1493 AddPointToBounds( metaVerts[ tri->indexes[ 0 ] ].xyz, mins, maxs );
1494 AddPointToBounds( metaVerts[ tri->indexes[ 1 ] ].xyz, mins, maxs );
1495 AddPointToBounds( metaVerts[ tri->indexes[ 2 ] ].xyz, mins, maxs );
1497 /* check lightmap bounds overflow (after at least 1 triangle has been added) */
1498 if( !(ds->shaderInfo->compileFlags & C_VERTEXLIT) &&
1499 ds->numIndexes > 0 && VectorLength( ds->lightmapAxis ) > 0.0f &&
1500 (VectorCompare( ds->mins, mins ) == qfalse || VectorCompare( ds->maxs, maxs ) == qfalse) )
1502 /* set maximum size before lightmap scaling (normally 2032 units) */
1503 /* 2004-02-24: scale lightmap test size by 2 to catch larger brush faces */
1504 /* 2004-04-11: reverting to actual lightmap size */
1505 lmMax = (ds->sampleSize * (ds->shaderInfo->lmCustomWidth - 1));
1506 for( i = 0; i < 3; i++ )
1508 if( (maxs[ i ] - mins[ i ]) > lmMax )
1510 memcpy( ds, &old, sizeof( *ds ) );
1516 /* check texture range overflow */
1517 oldTexRange[ 0 ] = ds->texRange[ 0 ];
1518 oldTexRange[ 1 ] = ds->texRange[ 1 ];
1519 inTexRange = CalcSurfaceTextureRange( ds );
1521 if( inTexRange == qfalse && ds->numIndexes > 0 )
1523 memcpy( ds, &old, sizeof( *ds ) );
1524 return UNSUITABLE_TRIANGLE;
1527 /* score texture range */
1528 if( ds->texRange[ 0 ] <= oldTexRange[ 0 ] )
1530 else if( ds->texRange[ 0 ] > oldTexRange[ 0 ] && oldTexRange[ 1 ] > oldTexRange[ 0 ] )
1533 if( ds->texRange[ 1 ] <= oldTexRange[ 1 ] )
1535 else if( ds->texRange[ 1 ] > oldTexRange[ 1 ] && oldTexRange[ 0 ] > oldTexRange[ 1 ] )
1539 /* go through the indexes and try to find an existing triangle that matches abc */
1540 for( i = 0; i < ds->numIndexes; i += 3 )
1542 /* 2002-03-11 (birthday!): rotate the triangle 3x to find an existing triangle */
1543 if( (ai == ds->indexes[ i ] && bi == ds->indexes[ i + 1 ] && ci == ds->indexes[ i + 2 ]) ||
1544 (bi == ds->indexes[ i ] && ci == ds->indexes[ i + 1 ] && ai == ds->indexes[ i + 2 ]) ||
1545 (ci == ds->indexes[ i ] && ai == ds->indexes[ i + 1 ] && bi == ds->indexes[ i + 2 ]) )
1547 /* triangle already present */
1548 memcpy( ds, &old, sizeof( *ds ) );
1553 /* rotate the triangle 3x to find an inverse triangle (error case) */
1554 if( (ai == ds->indexes[ i ] && bi == ds->indexes[ i + 2 ] && ci == ds->indexes[ i + 1 ]) ||
1555 (bi == ds->indexes[ i ] && ci == ds->indexes[ i + 2 ] && ai == ds->indexes[ i + 1 ]) ||
1556 (ci == ds->indexes[ i ] && ai == ds->indexes[ i + 2 ] && bi == ds->indexes[ i + 1 ]) )
1559 Sys_Printf( "WARNING: Flipped triangle: (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f) (%6.0f %6.0f %6.0f)\n",
1560 ds->verts[ ai ].xyz[ 0 ], ds->verts[ ai ].xyz[ 1 ], ds->verts[ ai ].xyz[ 2 ],
1561 ds->verts[ bi ].xyz[ 0 ], ds->verts[ bi ].xyz[ 1 ], ds->verts[ bi ].xyz[ 2 ],
1562 ds->verts[ ci ].xyz[ 0 ], ds->verts[ ci ].xyz[ 1 ], ds->verts[ ci ].xyz[ 2 ] );
1564 /* reverse triangle already present */
1565 memcpy( ds, &old, sizeof( *ds ) );
1571 /* add the triangle indexes */
1572 if( ds->numIndexes < maxSurfaceIndexes )
1573 ds->indexes[ ds->numIndexes++ ] = ai;
1574 if( ds->numIndexes < maxSurfaceIndexes )
1575 ds->indexes[ ds->numIndexes++ ] = bi;
1576 if( ds->numIndexes < maxSurfaceIndexes )
1577 ds->indexes[ ds->numIndexes++ ] = ci;
1579 /* check index overflow */
1580 if( ds->numIndexes >= maxSurfaceIndexes )
1582 memcpy( ds, &old, sizeof( *ds ) );
1586 /* sanity check the indexes */
1587 if( ds->numIndexes >= 3 &&
1588 (ds->indexes[ ds->numIndexes - 3 ] == ds->indexes[ ds->numIndexes - 2 ] ||
1589 ds->indexes[ ds->numIndexes - 3 ] == ds->indexes[ ds->numIndexes - 1 ] ||
1590 ds->indexes[ ds->numIndexes - 2 ] == ds->indexes[ ds->numIndexes - 1 ]) )
1591 Sys_Printf( "DEG:%d! ", ds->numVerts );
1595 memcpy( ds, &old, sizeof( *ds ) );
1598 /* copy bounds back to surface */
1599 VectorCopy( mins, ds->mins );
1600 VectorCopy( maxs, ds->maxs );
1602 /* mark triangle as used */
1606 /* add a side reference */
1607 ds->sideRef = AllocSideRef( tri->side, ds->sideRef );
1609 /* return to sender */
1616 MetaTrianglesToSurface()
1617 creates map drawsurface(s) from the list of possibles
1620 static void MetaTrianglesToSurface( int numPossibles, metaTriangle_t *possibles, int *fOld, int *numAdded )
1622 int i, j, f, best, score, bestScore;
1623 metaTriangle_t *seed, *test;
1624 mapDrawSurface_t *ds;
1625 bspDrawVert_t *verts;
1630 /* allocate arrays */
1631 verts = safe_malloc( sizeof( *verts ) * maxSurfaceVerts );
1632 indexes = safe_malloc( sizeof( *indexes ) * maxSurfaceIndexes );
1634 /* walk the list of triangles */
1635 for( i = 0, seed = possibles; i < numPossibles; i++, seed++ )
1637 /* skip this triangle if it has already been merged */
1638 if( seed->si == NULL )
1641 /* -----------------------------------------------------------------
1642 initial drawsurf construction
1643 ----------------------------------------------------------------- */
1645 /* start a new drawsurface */
1646 ds = AllocDrawSurface( SURFACE_META );
1647 ds->entityNum = seed->entityNum;
1648 ds->surfaceNum = seed->surfaceNum;
1649 ds->castShadows = seed->castShadows;
1650 ds->recvShadows = seed->recvShadows;
1652 ds->shaderInfo = seed->si;
1653 ds->planeNum = seed->planeNum;
1654 ds->fogNum = seed->fogNum;
1655 ds->sampleSize = seed->sampleSize;
1656 ds->shadeAngleDegrees = seed->shadeAngleDegrees;
1658 ds->indexes = indexes;
1659 VectorCopy( seed->lightmapAxis, ds->lightmapAxis );
1660 ds->sideRef = AllocSideRef( seed->side, NULL );
1662 ClearBounds( ds->mins, ds->maxs );
1664 /* clear verts/indexes */
1665 memset( verts, 0, sizeof( verts ) );
1666 memset( indexes, 0, sizeof( indexes ) );
1668 /* add the first triangle */
1669 if( AddMetaTriangleToSurface( ds, seed, qfalse ) )
1672 /* -----------------------------------------------------------------
1674 ----------------------------------------------------------------- */
1676 /* progressively walk the list until no more triangles can be added */
1680 /* print pacifier */
1681 f = 10 * *numAdded / numMetaTriangles;
1685 Sys_FPrintf( SYS_VRB, "%d...", f );
1688 /* reset best score */
1693 /* walk the list of possible candidates for merging */
1694 for( j = i + 1, test = &possibles[ j ]; j < numPossibles; j++, test++ )
1696 /* skip this triangle if it has already been merged */
1697 if( test->si == NULL )
1700 /* score this triangle */
1701 score = AddMetaTriangleToSurface( ds, test, qtrue );
1702 if( score > bestScore )
1707 /* if we have a score over a certain threshold, just use it */
1708 if( bestScore >= GOOD_SCORE )
1710 if( AddMetaTriangleToSurface( ds, &possibles[ best ], qfalse ) )
1721 /* add best candidate */
1722 if( best >= 0 && bestScore > ADEQUATE_SCORE )
1724 if( AddMetaTriangleToSurface( ds, &possibles[ best ], qfalse ) )
1732 /* copy the verts and indexes to the new surface */
1733 ds->verts = safe_malloc( ds->numVerts * sizeof( bspDrawVert_t ) );
1734 memcpy( ds->verts, verts, ds->numVerts * sizeof( bspDrawVert_t ) );
1735 ds->indexes = safe_malloc( ds->numIndexes * sizeof( int ) );
1736 memcpy( ds->indexes, indexes, ds->numIndexes * sizeof( int ) );
1738 /* classify the surface */
1739 ClassifySurfaces( 1, ds );
1742 numMergedSurfaces++;
1753 CompareMetaTriangles()
1754 compare function for qsort()
1757 static int CompareMetaTriangles( const void *a, const void *b )
1760 vec3_t aMins, bMins;
1764 if( ((const metaTriangle_t*) a)->si < ((const metaTriangle_t*) b)->si )
1766 else if( ((const metaTriangle_t*) a)->si > ((const metaTriangle_t*) b)->si )
1770 else if( ((const metaTriangle_t*) a)->fogNum < ((const metaTriangle_t*) b)->fogNum )
1772 else if( ((const metaTriangle_t*) a)->fogNum > ((const metaTriangle_t*) b)->fogNum )
1777 else if( npDegrees == 0.0f && ((const metaTriangle_t*) a)->si->nonplanar == qfalse &&
1778 ((const metaTriangle_t*) a)->planeNum >= 0 && ((const metaTriangle_t*) a)->planeNum >= 0 )
1780 if( ((const metaTriangle_t*) a)->plane[ 3 ] < ((const metaTriangle_t*) b)->plane[ 3 ] )
1782 else if( ((const metaTriangle_t*) a)->plane[ 3 ] > ((const metaTriangle_t*) b)->plane[ 3 ] )
1784 else if( ((const metaTriangle_t*) a)->plane[ 0 ] < ((const metaTriangle_t*) b)->plane[ 0 ] )
1786 else if( ((const metaTriangle_t*) a)->plane[ 0 ] > ((const metaTriangle_t*) b)->plane[ 0 ] )
1788 else if( ((const metaTriangle_t*) a)->plane[ 1 ] < ((const metaTriangle_t*) b)->plane[ 1 ] )
1790 else if( ((const metaTriangle_t*) a)->plane[ 1 ] > ((const metaTriangle_t*) b)->plane[ 1 ] )
1792 else if( ((const metaTriangle_t*) a)->plane[ 2 ] < ((const metaTriangle_t*) b)->plane[ 2 ] )
1794 else if( ((const metaTriangle_t*) a)->plane[ 2 ] > ((const metaTriangle_t*) b)->plane[ 2 ] )
1799 /* then position in world */
1802 VectorSet( aMins, 999999, 999999, 999999 );
1803 VectorSet( bMins, 999999, 999999, 999999 );
1804 for( i = 0; i < 3; i++ )
1806 av = ((const metaTriangle_t*) a)->indexes[ i ];
1807 bv = ((const metaTriangle_t*) b)->indexes[ i ];
1808 for( j = 0; j < 3; j++ )
1810 if( metaVerts[ av ].xyz[ j ] < aMins[ j ] )
1811 aMins[ j ] = metaVerts[ av ].xyz[ j ];
1812 if( metaVerts[ bv ].xyz[ j ] < bMins[ j ] )
1813 bMins[ j ] = metaVerts[ bv ].xyz[ j ];
1818 for( i = 0; i < 3; i++ )
1820 if( aMins[ i ] < bMins[ i ] )
1822 else if( aMins[ i ] > bMins[ i ] )
1826 /* functionally equivalent */
1833 MergeMetaTriangles()
1834 merges meta triangles into drawsurfaces
1837 void MergeMetaTriangles( void )
1839 int i, j, fOld, start, numAdded;
1840 metaTriangle_t *head, *end;
1843 /* only do this if there are meta triangles */
1844 if( numMetaTriangles <= 0 )
1848 Sys_FPrintf( SYS_VRB, "--- MergeMetaTriangles ---\n" );
1850 /* sort the triangles by shader major, fognum minor */
1851 qsort( metaTriangles, numMetaTriangles, sizeof( metaTriangle_t ), CompareMetaTriangles );
1855 start = I_FloatTime();
1859 for( i = 0, j = 0; i < numMetaTriangles; i = j )
1861 /* get head of list */
1862 head = &metaTriangles[ i ];
1864 /* skip this triangle if it has already been merged */
1865 if( head->si == NULL )
1871 for( j = i + 1; j < numMetaTriangles; j++ )
1873 /* get end of list */
1874 end = &metaTriangles[ j ];
1875 if( head->si != end->si || head->fogNum != end->fogNum )
1880 /* try to merge this list of possible merge candidates */
1881 MetaTrianglesToSurface( (j - i), head, &fOld, &numAdded );
1884 /* clear meta triangle list */
1885 ClearMetaTriangles();
1889 Sys_FPrintf( SYS_VRB, " (%d)\n", (int) (I_FloatTime() - start) );
1891 /* emit some stats */
1892 Sys_FPrintf( SYS_VRB, "%9d surfaces merged\n", numMergedSurfaces );
1893 Sys_FPrintf( SYS_VRB, "%9d vertexes merged\n", numMergedVerts );