]> icculus.org git repositories - divverent/netradiant.git/blob - tools/quake3/q3map2/model.c
fix bugs in skin load code
[divverent/netradiant.git] / tools / quake3 / q3map2 / model.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 MODEL_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 /* 
42 PicoPrintFunc()
43 callback for picomodel.lib
44 */
45
46 void PicoPrintFunc( int level, const char *str )
47 {
48         if( str == NULL )
49                 return;
50         switch( level )
51         {
52                 case PICO_NORMAL:
53                         Sys_Printf( "%s\n", str );
54                         break;
55                 
56                 case PICO_VERBOSE:
57                         Sys_FPrintf( SYS_VRB, "%s\n", str );
58                         break;
59                 
60                 case PICO_WARNING:
61                         Sys_Printf( "WARNING: %s\n", str );
62                         break;
63                 
64                 case PICO_ERROR:
65                         Sys_Printf( "ERROR: %s\n", str );
66                         break;
67                 
68                 case PICO_FATAL:
69                         Error( "ERROR: %s\n", str );
70                         break;
71         }
72 }
73
74
75
76 /* 
77 PicoLoadFileFunc()
78 callback for picomodel.lib
79 */
80
81 void PicoLoadFileFunc( char *name, byte **buffer, int *bufSize )
82 {
83         *bufSize = vfsLoadFile( (const char*) name, (void**) buffer, 0 );
84 }
85
86
87
88 /*
89 FindModel() - ydnar
90 finds an existing picoModel and returns a pointer to the picoModel_t struct or NULL if not found
91 */
92
93 picoModel_t *FindModel( const char *name, int frame )
94 {
95         int                     i;
96         
97         
98         /* init */
99         if( numPicoModels <= 0 )
100                 memset( picoModels, 0, sizeof( picoModels ) );
101         
102         /* dummy check */
103         if( name == NULL || name[ 0 ] == '\0' )
104                 return NULL;
105         
106         /* search list */
107         for( i = 0; i < MAX_MODELS; i++ )
108         {
109                 if( picoModels[ i ] != NULL &&
110                         !strcmp( PicoGetModelName( picoModels[ i ] ), name ) &&
111                         PicoGetModelFrameNum( picoModels[ i ] ) == frame )
112                         return picoModels[ i ];
113         }
114         
115         /* no matching picoModel found */
116         return NULL;
117 }
118
119
120
121 /*
122 LoadModel() - ydnar
123 loads a picoModel and returns a pointer to the picoModel_t struct or NULL if not found
124 */
125
126 picoModel_t *LoadModel( const char *name, int frame )
127 {
128         int                             i;
129         picoModel_t             *model, **pm;
130         
131         
132         /* init */
133         if( numPicoModels <= 0 )
134                 memset( picoModels, 0, sizeof( picoModels ) );
135         
136         /* dummy check */
137         if( name == NULL || name[ 0 ] == '\0' )
138                 return NULL;
139         
140         /* try to find existing picoModel */
141         model = FindModel( name, frame );
142         if( model != NULL )
143                 return model;
144         
145         /* none found, so find first non-null picoModel */
146         pm = NULL;
147         for( i = 0; i < MAX_MODELS; i++ )
148         {
149                 if( picoModels[ i ] == NULL )
150                 {
151                         pm = &picoModels[ i ];
152                         break;
153                 }
154         }
155         
156         /* too many picoModels? */
157         if( pm == NULL )
158                 Error( "MAX_MODELS (%d) exceeded, there are too many model files referenced by the map.", MAX_MODELS );
159         
160         /* attempt to parse model */
161         *pm = PicoLoadModel( (char*) name, frame );
162         
163         /* if loading failed, make a bogus model to silence the rest of the warnings */
164         if( *pm == NULL )
165         {
166                 /* allocate a new model */
167                 *pm = PicoNewModel();
168                 if( *pm == NULL )
169                         return NULL;
170                 
171                 /* set data */
172                 PicoSetModelName( *pm, (char*) name );
173                 PicoSetModelFrameNum( *pm, frame );
174         }
175         
176         /* debug code */
177         #if 0
178         {
179                 int                             numSurfaces, numVertexes;
180                 picoSurface_t   *ps;
181                 
182                 
183                 Sys_Printf( "Model %s\n", name );
184                 numSurfaces = PicoGetModelNumSurfaces( *pm );
185                 for( i = 0; i < numSurfaces; i++ )
186                 {
187                         ps = PicoGetModelSurface( *pm, i );
188                         numVertexes = PicoGetSurfaceNumVertexes( ps );
189                         Sys_Printf( "Surface %d has %d vertexes\n", i, numVertexes );
190                 }
191         }
192         #endif
193         
194         /* set count */
195         if( *pm != NULL )
196                 numPicoModels++;
197         
198         /* return the picoModel */
199         return *pm;
200 }
201
202
203
204 /*
205 InsertModel() - ydnar
206 adds a picomodel into the bsp
207 */
208
209 void InsertModel( const char *name, int skin, int frame, m4x4_t transform, remap_t *remap, shaderInfo_t *celShader, int eNum, int castShadows, int recvShadows, int spawnFlags, float lightmapScale, int lightmapSampleSize, float shadeAngle )
210 {
211         int                                     i, j, k, s, numSurfaces;
212         m4x4_t                          identity, nTransform;
213         picoModel_t                     *model;
214         picoShader_t            *shader;
215         picoSurface_t           *surface;
216         shaderInfo_t            *si;
217         mapDrawSurface_t        *ds;
218         bspDrawVert_t           *dv;
219         char                            *picoShaderName;
220         char                            shaderName[ MAX_QPATH ];
221         picoVec_t                       *xyz, *normal, *st;
222         byte                            *color;
223         picoIndex_t                     *indexes;
224         remap_t                         *rm, *glob;
225         skinfile_t                      *sf, *sf2;
226         double                          normalEpsilon_save;
227         double                          distanceEpsilon_save;
228         char                            skinfilename[ MAX_QPATH ];
229         char                            *skinfilecontent;
230         int                                     skinfilesize;
231         char                            *skinfileptr, *skinfilenextptr;
232         FILE                            *skinfilehandle;
233         
234         
235         /* get model */
236         model = LoadModel( name, frame );
237         if( model == NULL )
238                 return;
239
240         /* load skin file */
241         snprintf(skinfilename, sizeof(skinfilename), "%s_%d.skin", name, skin);
242         skinfilename[sizeof(skinfilename)-1] = 0;
243         skinfilehandle = fopen(skinfilename, "r");
244         skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0);
245         if(skinfilesize < 0 && skin != 0)
246         {
247                 /* fallback to skin 0 if invalid */
248                 snprintf(skinfilename, sizeof(skinfilename), "%s_0.skin", name);
249                 skinfilename[sizeof(skinfilename)-1] = 0;
250                 skinfilesize = vfsLoadFile(skinfilename, (void**) &skinfilecontent, 0);
251                 if(skinfilesize >= 0)
252                         Sys_Printf( "Skin %d of %s does not exist, using 0 instead\n", skin, name );
253         }
254         sf = NULL;
255         if(skinfilesize >= 0)
256         {
257                 Sys_Printf( "Using skin %d of %s\n", skin, name );
258                 int pos;
259                 for(skinfileptr = skinfilecontent; *skinfileptr; skinfileptr = skinfilenextptr)
260                 {
261                         // for fscanf
262                         char format[64];
263
264                         skinfilenextptr = strchr(skinfileptr, '\r');
265                         if(skinfilenextptr)
266                         {
267                                 *skinfilenextptr++ = 0;
268                         }
269                         else
270                         {
271                                 skinfilenextptr = strchr(skinfileptr, '\n');
272                                 if(skinfilenextptr)
273                                         *skinfilenextptr++ = 0;
274                                 else
275                                         skinfilenextptr = skinfileptr + strlen(skinfileptr);
276                         }
277
278                         /* create new item */
279                         sf2 = sf;
280                         sf = safe_malloc( sizeof( *sf ) );
281                         sf->next = sf2;
282
283                         sprintf(format, "replace %%%ds %%%ds", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1);
284                         if(sscanf(skinfileptr, format, sf->name, sf->to) == 2)
285                                 continue;
286                         sprintf(format, " %%%d[^,       ] ,%%%ds", (int)sizeof(sf->name)-1, (int)sizeof(sf->to)-1);
287                         if((pos = sscanf(skinfileptr, format, sf->name, sf->to)) == 2)
288                                 continue;
289
290                         /* invalid input line -> discard sf struct */
291                         Sys_Printf( "Discarding skin directive in %s: %s\n", skinfilename, skinfileptr );
292                         free(sf);
293                         sf = sf2;
294                 }
295                 free(skinfilecontent);
296         }
297         
298         /* handle null matrix */
299         if( transform == NULL )
300         {
301                 m4x4_identity( identity );
302                 transform = identity;
303         }
304         
305         /* hack: Stable-1_2 and trunk have differing row/column major matrix order
306            this transpose is necessary with Stable-1_2
307            uncomment the following line with old m4x4_t (non 1.3/spog_branch) code */
308         //%     m4x4_transpose( transform );
309         
310         /* create transform matrix for normals */
311         memcpy( nTransform, transform, sizeof( m4x4_t ) );
312         if( m4x4_invert( nTransform ) )
313                 Sys_FPrintf( SYS_VRB, "WARNING: Can't invert model transform matrix, using transpose instead\n" );
314         m4x4_transpose( nTransform );
315         
316         /* fix bogus lightmap scale */
317         if( lightmapScale <= 0.0f )
318                 lightmapScale = 1.0f;
319
320         /* fix bogus shade angle */
321         if( shadeAngle <= 0.0f )
322                 shadeAngle = 0.0f;
323         
324         /* each surface on the model will become a new map drawsurface */
325         numSurfaces = PicoGetModelNumSurfaces( model );
326         //%     Sys_FPrintf( SYS_VRB, "Model %s has %d surfaces\n", name, numSurfaces );
327         for( s = 0; s < numSurfaces; s++ )
328         {
329                 /* get surface */
330                 surface = PicoGetModelSurface( model, s );
331                 if( surface == NULL )
332                         continue;
333                 
334                 /* only handle triangle surfaces initially (fixme: support patches) */
335                 if( PicoGetSurfaceType( surface ) != PICO_TRIANGLES )
336                         continue;
337                 
338                 /* allocate a surface (ydnar: gs mods) */
339                 ds = AllocDrawSurface( SURFACE_TRIANGLES );
340                 ds->entityNum = eNum;
341                 ds->castShadows = castShadows;
342                 ds->recvShadows = recvShadows;
343                 
344                 /* get shader name */
345         shader = PicoGetSurfaceShader( surface );
346                 if( shader == NULL )
347                         picoShaderName = "";
348                 else
349                         picoShaderName = PicoGetShaderName( shader );
350
351                 /* handle .skin file */
352                 if(sf)
353                 {
354                         picoShaderName = NULL;
355                         for(sf2 = sf; sf2 != NULL; sf2 = sf2->next)
356                         {
357                                 if( !Q_stricmp( surface->name, sf2->name ) )
358                                 {
359                                         Sys_FPrintf( SYS_VRB, "Skin file: mapping %s to %s\n", surface->name, sf2->to );
360                                         picoShaderName = sf2->to;
361                                         break;
362                                 }
363                         }
364                         if(!picoShaderName)
365                         {
366                                 Sys_FPrintf( SYS_VRB, "Skin file: not mapping %s\n", surface->name );
367                                 continue;
368                         }
369                 }
370
371                 /* handle shader remapping */
372                 glob = NULL;
373                 for( rm = remap; rm != NULL; rm = rm->next )
374                 {
375                         if( rm->from[ 0 ] == '*' && rm->from[ 1 ] == '\0' )
376                                 glob = rm;
377                         else if( !Q_stricmp( picoShaderName, rm->from ) )
378                         {
379                                 Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", picoShaderName, rm->to );
380                                 picoShaderName = rm->to;
381                                 glob = NULL;
382                                 break;
383                         }
384                 }
385                 
386                 if( glob != NULL )
387                 {
388                         Sys_FPrintf( SYS_VRB, "Globbing %s to %s\n", picoShaderName, glob->to );
389                         picoShaderName = glob->to;
390                 }
391                 
392                 /* shader renaming for sof2 */
393                 if( renameModelShaders )
394                 {
395                         strcpy( shaderName, picoShaderName );
396                         StripExtension( shaderName );
397                         if( spawnFlags & 1 )
398                                 strcat( shaderName, "_RMG_BSP" );
399                         else
400                                 strcat( shaderName, "_BSP" );
401                         si = ShaderInfoForShader( shaderName );
402                 }
403                 else
404                         si = ShaderInfoForShader( picoShaderName );
405                 
406                 /* set shader */
407                 ds->shaderInfo = si;
408
409                 /* force to meta? */
410                 if( (si != NULL && si->forceMeta) || (spawnFlags & 4) ) /* 3rd bit */
411                         ds->type = SURFACE_FORCED_META;
412
413                 /* fix the surface's normals (jal: conditioned by shader info) */
414                 if( !(spawnFlags & 64) && ( shadeAngle == 0.0f || ds->type != SURFACE_FORCED_META ) )
415                         PicoFixSurfaceNormals( surface );
416
417                 /* set sample size */
418                 if( lightmapSampleSize > 0.0f )
419                         ds->sampleSize = lightmapSampleSize;
420                 
421                 /* set lightmap scale */
422                 if( lightmapScale > 0.0f )
423                         ds->lightmapScale = lightmapScale;
424
425                 /* set shading angle */
426                 if( shadeAngle > 0.0f )
427                         ds->shadeAngleDegrees = shadeAngle;
428                 
429                 /* set particulars */
430                 ds->numVerts = PicoGetSurfaceNumVertexes( surface );
431                 ds->verts = safe_malloc( ds->numVerts * sizeof( ds->verts[ 0 ] ) );
432                 memset( ds->verts, 0, ds->numVerts * sizeof( ds->verts[ 0 ] ) );
433                 
434                 ds->numIndexes = PicoGetSurfaceNumIndexes( surface );
435                 ds->indexes = safe_malloc( ds->numIndexes * sizeof( ds->indexes[ 0 ] ) );
436                 memset( ds->indexes, 0, ds->numIndexes * sizeof( ds->indexes[ 0 ] ) );
437                 
438                 /* copy vertexes */
439                 for( i = 0; i < ds->numVerts; i++ )
440                 {
441                         /* get vertex */
442                         dv = &ds->verts[ i ];
443                         
444                         /* xyz and normal */
445                         xyz = PicoGetSurfaceXYZ( surface, i );
446                         VectorCopy( xyz, dv->xyz );
447                         m4x4_transform_point( transform, dv->xyz );
448                         
449                         normal = PicoGetSurfaceNormal( surface, i );
450                         VectorCopy( normal, dv->normal );
451                         m4x4_transform_normal( nTransform, dv->normal );
452                         VectorNormalize( dv->normal, dv->normal );
453
454                         /* ydnar: tek-fu celshading support for flat shaded shit */
455                         if( flat )
456                         {
457                                 dv->st[ 0 ] = si->stFlat[ 0 ];
458                                 dv->st[ 1 ] = si->stFlat[ 1 ];
459                         }
460                         
461                         /* ydnar: gs mods: added support for explicit shader texcoord generation */
462                         else if( si->tcGen )
463                         {
464                                 /* project the texture */
465                                 dv->st[ 0 ] = DotProduct( si->vecs[ 0 ], dv->xyz );
466                                 dv->st[ 1 ] = DotProduct( si->vecs[ 1 ], dv->xyz );
467                         }
468                         
469                         /* normal texture coordinates */
470                         else
471                         {
472                                 st = PicoGetSurfaceST( surface, 0, i );
473                                 dv->st[ 0 ] = st[ 0 ];
474                                 dv->st[ 1 ] = st[ 1 ];
475                         }
476                         
477                         /* set lightmap/color bits */
478                         color = PicoGetSurfaceColor( surface, 0, i );
479                         for( j = 0; j < MAX_LIGHTMAPS; j++ )
480                         {
481                                 dv->lightmap[ j ][ 0 ] = 0.0f;
482                                 dv->lightmap[ j ][ 1 ] = 0.0f;
483                                 if(spawnFlags & 32) // spawnflag 32: model color -> alpha hack
484                                 {
485                                         dv->color[ j ][ 0 ] = 255.0f;
486                                         dv->color[ j ][ 1 ] = 255.0f;
487                                         dv->color[ j ][ 2 ] = 255.0f;
488                                         dv->color[ j ][ 3 ] = RGBTOGRAY( color );
489                                 }
490                                 else
491                                 {
492                                         dv->color[ j ][ 0 ] = color[ 0 ];
493                                         dv->color[ j ][ 1 ] = color[ 1 ];
494                                         dv->color[ j ][ 2 ] = color[ 2 ];
495                                         dv->color[ j ][ 3 ] = color[ 3 ];
496                                 }
497                         }
498                 }
499                 
500                 /* copy indexes */
501                 indexes = PicoGetSurfaceIndexes( surface, 0 );
502                 for( i = 0; i < ds->numIndexes; i++ )
503                         ds->indexes[ i ] = indexes[ i ];
504                 
505                 /* set cel shader */
506                 ds->celShader = celShader;
507                 
508                 /* ydnar: giant hack land: generate clipping brushes for model triangles */
509                 if( si->clipModel || (spawnFlags & 2) ) /* 2nd bit */
510                 {
511                         vec3_t          points[ 4 ], backs[ 3 ];
512                         vec4_t          plane, reverse, pa, pb, pc;
513                         
514                         
515                         /* temp hack */
516                         if( !si->clipModel && !(si->compileFlags & C_SOLID) )
517                                 continue;
518                         
519                         /* walk triangle list */
520                         for( i = 0; i < ds->numIndexes; i += 3 )
521                         {
522                                 /* overflow hack */
523                                 AUTOEXPAND_BY_REALLOC(mapplanes, (nummapplanes+64) << 1, allocatedmapplanes, 1024);
524                                 
525                                 /* make points and back points */
526                                 for( j = 0; j < 3; j++ )
527                                 {
528                                         /* get vertex */
529                                         dv = &ds->verts[ ds->indexes[ i + j ] ];
530                                         
531                                         /* copy xyz */
532                                         VectorCopy( dv->xyz, points[ j ] );
533                                         VectorCopy( dv->xyz, backs[ j ] );
534                                         
535                                         /* find nearest axial to normal and push back points opposite */
536                                         /* note: this doesn't work as well as simply using the plane of the triangle, below */
537                                         for( k = 0; k < 3; k++ )
538                                         {
539                                                 if( fabs( dv->normal[ k ] ) >= fabs( dv->normal[ (k + 1) % 3 ] ) &&
540                                                         fabs( dv->normal[ k ] ) >= fabs( dv->normal[ (k + 2) % 3 ] ) )
541                                                 {
542                                                         backs[ j ][ k ] += dv->normal[ k ] < 0.0f ? 64.0f : -64.0f;
543                                                         break;
544                                                 }
545                                         }
546                                 }
547
548                                 VectorCopy( points[0], points[3] ); // for cyclic usage
549                                 
550                                 /* make plane for triangle */
551                                 // div0: add some extra spawnflags:
552                                 //   0: snap normals to axial planes for extrusion
553                                 //   8: extrude with the original normals
554                                 //  16: extrude only with up/down normals (ideal for terrain)
555                                 //  24: extrude by distance zero (may need engine changes)
556                                 if( PlaneFromPoints( plane, points[ 0 ], points[ 1 ], points[ 2 ] ) )
557                                 {
558                                         vec3_t bestNormal;
559                                         float backPlaneDistance = 2;
560
561                                         if(spawnFlags & 8) // use a DOWN normal
562                                         {
563                                                 if(spawnFlags & 16)
564                                                 {
565                                                         // 24: normal as is, and zero width (broken)
566                                                         VectorCopy(plane, bestNormal);
567                                                 }
568                                                 else
569                                                 {
570                                                         // 8: normal as is
571                                                         VectorCopy(plane, bestNormal);
572                                                 }
573                                         }
574                                         else
575                                         {
576                                                 if(spawnFlags & 16)
577                                                 {
578                                                         // 16: UP/DOWN normal
579                                                         VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1));
580                                                 }
581                                                 else
582                                                 {
583                                                         // 0: axial normal
584                                                         if(fabs(plane[0]) > fabs(plane[1])) // x>y
585                                                                 if(fabs(plane[1]) > fabs(plane[2])) // x>y, y>z
586                                                                         VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0);
587                                                                 else // x>y, z>=y
588                                                                         if(fabs(plane[0]) > fabs(plane[2])) // x>z, z>=y
589                                                                                 VectorSet(bestNormal, (plane[0] >= 0 ? 1 : -1), 0, 0);
590                                                                         else // z>=x, x>y
591                                                                                 VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1));
592                                                         else // y>=x
593                                                                 if(fabs(plane[1]) > fabs(plane[2])) // y>z, y>=x
594                                                                         VectorSet(bestNormal, 0, (plane[1] >= 0 ? 1 : -1), 0);
595                                                                 else // z>=y, y>=x
596                                                                         VectorSet(bestNormal, 0, 0, (plane[2] >= 0 ? 1 : -1));
597                                                 }
598                                         }
599
600                                         /* build a brush */
601                                         buildBrush = AllocBrush( 48 );
602                                         buildBrush->entityNum = mapEntityNum;
603                                         buildBrush->original = buildBrush;
604                                         buildBrush->contentShader = si;
605                                         buildBrush->compileFlags = si->compileFlags;
606                                         buildBrush->contentFlags = si->contentFlags;
607                                         normalEpsilon_save = normalEpsilon;
608                                         distanceEpsilon_save = distanceEpsilon;
609                                         if(si->compileFlags & C_STRUCTURAL) // allow forced structural brushes here
610                                         {
611                                                 buildBrush->detail = qfalse;
612
613                                                 // only allow EXACT matches when snapping for these (this is mostly for caulk brushes inside a model)
614                                                 if(normalEpsilon > 0)
615                                                         normalEpsilon = 0;
616                                                 if(distanceEpsilon > 0)
617                                                         distanceEpsilon = 0;
618                                         }
619                                         else
620                                                 buildBrush->detail = qtrue;
621
622                                         /* regenerate back points */
623                                         for( j = 0; j < 3; j++ )
624                                         {
625                                                 /* get vertex */
626                                                 dv = &ds->verts[ ds->indexes[ i + j ] ];
627
628                                                 // shift by some units
629                                                 VectorMA(dv->xyz, -64.0f, bestNormal, backs[j]); // 64 prevents roundoff errors a bit
630                                         }
631
632                                         /* make back plane */
633                                         VectorScale( plane, -1.0f, reverse );
634                                         reverse[ 3 ] = -plane[ 3 ];
635                                         if((spawnFlags & 24) != 24)
636                                                 reverse[3] += DotProduct(bestNormal, plane) * backPlaneDistance;
637                                         // that's at least sqrt(1/3) backPlaneDistance, unless in DOWN mode; in DOWN mode, we are screwed anyway if we encounter a plane that's perpendicular to the xy plane)
638
639                                         if( PlaneFromPoints( pa, points[ 2 ], points[ 1 ], backs[ 1 ] ) &&
640                                                         PlaneFromPoints( pb, points[ 1 ], points[ 0 ], backs[ 0 ] ) &&
641                                                         PlaneFromPoints( pc, points[ 0 ], points[ 2 ], backs[ 2 ] ) )
642                                         {
643                                                 /* set up brush sides */
644                                                 buildBrush->numsides = 5;
645                                                 buildBrush->sides[ 0 ].shaderInfo = si;
646                                                 for( j = 1; j < buildBrush->numsides; j++ )
647                                                         buildBrush->sides[ j ].shaderInfo = NULL; // don't emit these faces as draw surfaces, should make smaller BSPs; hope this works
648
649                                                 buildBrush->sides[ 0 ].planenum = FindFloatPlane( plane, plane[ 3 ], 3, points );
650                                                 buildBrush->sides[ 1 ].planenum = FindFloatPlane( pa, pa[ 3 ], 2, &points[ 1 ] ); // pa contains points[1] and points[2]
651                                                 buildBrush->sides[ 2 ].planenum = FindFloatPlane( pb, pb[ 3 ], 2, &points[ 0 ] ); // pb contains points[0] and points[1]
652                                                 buildBrush->sides[ 3 ].planenum = FindFloatPlane( pc, pc[ 3 ], 2, &points[ 2 ] ); // pc contains points[2] and points[0] (copied to points[3]
653                                                 buildBrush->sides[ 4 ].planenum = FindFloatPlane( reverse, reverse[ 3 ], 3, backs );
654                                         }
655                                         else
656                                         {
657                                                 free(buildBrush);
658                                                 continue;
659                                         }
660
661                                         normalEpsilon = normalEpsilon_save;
662                                         distanceEpsilon = distanceEpsilon_save;
663
664                                         /* add to entity */
665                                         if( CreateBrushWindings( buildBrush ) )
666                                         {
667                                                 AddBrushBevels();
668                                                 //%     EmitBrushes( buildBrush, NULL, NULL );
669                                                 buildBrush->next = entities[ mapEntityNum ].brushes;
670                                                 entities[ mapEntityNum ].brushes = buildBrush;
671                                                 entities[ mapEntityNum ].numBrushes++;
672                                         }
673                                         else
674                                                 free( buildBrush );
675                                 }
676                         }
677                 }
678         }
679 }
680
681
682
683 /*
684 AddTriangleModels()
685 adds misc_model surfaces to the bsp
686 */
687
688 void AddTriangleModels( entity_t *e )
689 {
690         int                             num, frame, skin, castShadows, recvShadows, spawnFlags;
691         entity_t                *e2;
692         const char              *targetName;
693         const char              *target, *model, *value;
694         char                    shader[ MAX_QPATH ];
695         shaderInfo_t    *celShader;
696         float                   temp, baseLightmapScale, lightmapScale;
697         float                   shadeAngle;
698         int                             lightmapSampleSize;
699         vec3_t                  origin, scale, angles;
700         m4x4_t                  transform;
701         epair_t                 *ep;
702         remap_t                 *remap, *remap2;
703         char                    *split;
704         
705         
706         /* note it */
707         Sys_FPrintf( SYS_VRB, "--- AddTriangleModels ---\n" );
708         
709         /* get current brush entity targetname */
710         if( e == entities )
711                 targetName = "";
712         else
713         {
714                 targetName = ValueForKey( e, "targetname" );
715         
716                 /* misc_model entities target non-worldspawn brush model entities */
717                 if( targetName[ 0 ] == '\0' )
718                         return;
719         }
720         
721         /* get lightmap scale */
722         /* vortex: added _ls key (short name of lightmapscale) */
723         baseLightmapScale = 0.0f;
724         if( strcmp( "", ValueForKey( e, "lightmapscale" ) ) ||
725                 strcmp( "", ValueForKey( e, "_lightmapscale" ) ) || 
726                 strcmp( "", ValueForKey( e, "_ls" ) ) )
727         {
728                 baseLightmapScale = FloatForKey( e, "lightmapscale" );
729                 if( baseLightmapScale <= 0.0f )
730                         baseLightmapScale = FloatForKey( e, "_lightmapscale" );
731                 if( baseLightmapScale <= 0.0f )
732                         baseLightmapScale = FloatForKey( e, "_ls" );
733                 if( baseLightmapScale < 0.0f )
734                         baseLightmapScale = 0.0f;
735                 if( baseLightmapScale > 0.0f )
736                         Sys_Printf( "World Entity has lightmap scale of %.4f\n", baseLightmapScale );
737         }
738         
739         
740         /* walk the entity list */
741         for( num = 1; num < numEntities; num++ )
742         {
743                 /* get e2 */
744                 e2 = &entities[ num ];
745                 
746                 /* convert misc_models into raw geometry */
747                 if( Q_stricmp( "misc_model", ValueForKey( e2, "classname" ) ) )
748                         continue;
749
750                 /* ydnar: added support for md3 models on non-worldspawn models */
751                 target = ValueForKey( e2, "target" );
752                 if( strcmp( target, targetName ) )
753                         continue;
754                 
755                 /* get model name */
756                 model = ValueForKey( e2, "model" );
757                 if( model[ 0 ] == '\0' )
758                 {
759                         Sys_Printf( "WARNING: misc_model at %i %i %i without a model key\n",
760                                 (int) origin[ 0 ], (int) origin[ 1 ], (int) origin[ 2 ] );
761                         continue;
762                 }
763                 
764                 /* get model frame */
765                 frame = IntForKey( e2, "_frame" );
766                 
767                 /* worldspawn (and func_groups) default to cast/recv shadows in worldspawn group */
768                 if( e == entities )
769                 {
770                         castShadows = WORLDSPAWN_CAST_SHADOWS;
771                         recvShadows = WORLDSPAWN_RECV_SHADOWS;
772                 }
773                 
774                 /* other entities don't cast any shadows, but recv worldspawn shadows */
775                 else
776                 {
777                         castShadows = ENTITY_CAST_SHADOWS;
778                         recvShadows = ENTITY_RECV_SHADOWS;
779                 }
780                 
781                 /* get explicit shadow flags */
782                 GetEntityShadowFlags( e2, e, &castShadows, &recvShadows );
783                 
784                 /* get spawnflags */
785                 spawnFlags = IntForKey( e2, "spawnflags" );
786                 
787                 /* get origin */
788                 GetVectorForKey( e2, "origin", origin );
789                 VectorSubtract( origin, e->origin, origin );    /* offset by parent */
790                 
791                 /* get scale */
792                 scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = 1.0f;
793                 temp = FloatForKey( e2, "modelscale" );
794                 if( temp != 0.0f )
795                         scale[ 0 ] = scale[ 1 ] = scale[ 2 ] = temp;
796                 value = ValueForKey( e2, "modelscale_vec" );
797                 if( value[ 0 ] != '\0' )
798                         sscanf( value, "%f %f %f", &scale[ 0 ], &scale[ 1 ], &scale[ 2 ] );
799                 
800                 /* get "angle" (yaw) or "angles" (pitch yaw roll) */
801                 angles[ 0 ] = angles[ 1 ] = angles[ 2 ] = 0.0f;
802                 angles[ 2 ] = FloatForKey( e2, "angle" );
803                 value = ValueForKey( e2, "angles" );
804                 if( value[ 0 ] != '\0' )
805                         sscanf( value, "%f %f %f", &angles[ 1 ], &angles[ 2 ], &angles[ 0 ] );
806                 
807                 /* set transform matrix (thanks spog) */
808                 m4x4_identity( transform );
809                 m4x4_pivoted_transform_by_vec3( transform, origin, angles, eXYZ, scale, vec3_origin );
810                 
811                 /* get shader remappings */
812                 remap = NULL;
813                 for( ep = e2->epairs; ep != NULL; ep = ep->next )
814                 {
815                         /* look for keys prefixed with "_remap" */
816                         if( ep->key != NULL && ep->value != NULL &&
817                                 ep->key[ 0 ] != '\0' && ep->value[ 0 ] != '\0' &&
818                                 !Q_strncasecmp( ep->key, "_remap", 6 ) )
819                         {
820                                 /* create new remapping */
821                                 remap2 = remap;
822                                 remap = safe_malloc( sizeof( *remap ) );
823                                 remap->next = remap2;
824                                 strcpy( remap->from, ep->value );
825                                 
826                                 /* split the string */
827                                 split = strchr( remap->from, ';' );
828                                 if( split == NULL )
829                                 {
830                                         Sys_Printf( "WARNING: Shader _remap key found in misc_model without a ; character\n" );
831                                         free( remap );
832                                         remap = remap2;
833                                         continue;
834                                 }
835                                 
836                                 /* store the split */
837                                 *split = '\0';
838                                 strcpy( remap->to, (split + 1) );
839                                 
840                                 /* note it */
841                                 //%     Sys_FPrintf( SYS_VRB, "Remapping %s to %s\n", remap->from, remap->to );
842                         }
843                 }
844                 
845                 /* ydnar: cel shader support */
846                 value = ValueForKey( e2, "_celshader" );
847                 if( value[ 0 ] == '\0' )
848                         value = ValueForKey( &entities[ 0 ], "_celshader" );
849                 if( value[ 0 ] != '\0' )
850                 {
851                         sprintf( shader, "textures/%s", value );
852                         celShader = ShaderInfoForShader( shader );
853                 }
854                 else
855                         celShader = *globalCelShader ? ShaderInfoForShader(globalCelShader) : NULL;
856
857                 /* jal : entity based _samplesize */
858                 lightmapSampleSize = 0;
859                 if ( strcmp( "", ValueForKey( e2, "_lightmapsamplesize" ) ) )
860                         lightmapSampleSize = IntForKey( e2, "_lightmapsamplesize" );
861                 else if ( strcmp( "", ValueForKey( e2, "_samplesize" ) ) )
862                         lightmapSampleSize = IntForKey( e2, "_samplesize" );
863
864                 if( lightmapSampleSize < 0 )
865                         lightmapSampleSize = 0;
866
867                 if( lightmapSampleSize > 0.0f )
868                         Sys_Printf( "misc_model has lightmap sample size of %.d\n", lightmapSampleSize );
869
870                 /* get lightmap scale */
871                 /* vortex: added _ls key (short name of lightmapscale) */
872                 lightmapScale = 0.0f;
873                 if( strcmp( "", ValueForKey( e2, "lightmapscale" ) ) ||
874                         strcmp( "", ValueForKey( e2, "_lightmapscale" ) ) || 
875                         strcmp( "", ValueForKey( e2, "_ls" ) ) )
876                 {
877                         lightmapScale = FloatForKey( e2, "lightmapscale" );
878                         if( lightmapScale <= 0.0f )
879                                 lightmapScale = FloatForKey( e2, "_lightmapscale" );
880                         if( lightmapScale <= 0.0f )
881                                 lightmapScale = FloatForKey( e2, "_ls" );
882                         if( lightmapScale < 0.0f )
883                                 lightmapScale = 0.0f;
884                         if( lightmapScale > 0.0f )
885                                 Sys_Printf( "misc_model has lightmap scale of %.4f\n", lightmapScale );
886                 }
887
888                 /* jal : entity based _shadeangle */
889                 shadeAngle = 0.0f;
890                 if ( strcmp( "", ValueForKey( e2, "_shadeangle" ) ) )
891                         shadeAngle = FloatForKey( e2, "_shadeangle" );
892                 /* vortex' aliases */
893                 else if ( strcmp( "", ValueForKey( e2, "_smoothnormals" ) ) )
894                         shadeAngle = FloatForKey( e2, "_smoothnormals" );
895                 else if ( strcmp( "", ValueForKey( e2, "_sn" ) ) )
896                         shadeAngle = FloatForKey( e2, "_sn" );
897                 else if ( strcmp( "", ValueForKey( e2, "_smooth" ) ) )
898                         shadeAngle = FloatForKey( e2, "_smooth" );
899
900                 if( shadeAngle < 0.0f )
901                         shadeAngle = 0.0f;
902
903                 if( shadeAngle > 0.0f )
904                         Sys_Printf( "misc_model has shading angle of %.4f\n", shadeAngle );
905
906                 skin = IntForKey(e2, "skin");
907
908                 /* insert the model */
909                 InsertModel( model, skin, frame, transform, remap, celShader, mapEntityNum, castShadows, recvShadows, spawnFlags, lightmapScale, lightmapSampleSize, shadeAngle );
910                 
911                 /* free shader remappings */
912                 while( remap != NULL )
913                 {
914                         remap2 = remap->next;
915                         free( remap );
916                         remap = remap2;
917                 }
918         }
919 }