]> icculus.org git repositories - divverent/netradiant.git/blob - tools/quake3/q3map2/light_bounce.c
-lightmapdir option
[divverent/netradiant.git] / tools / quake3 / q3map2 / light_bounce.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 LIGHT_BOUNCE_C
33
34
35
36 /* dependencies */
37 #include "q3map2.h"
38
39
40
41 /* functions */
42
43 /*
44 RadFreeLights()
45 deletes any existing lights, freeing up memory for the next bounce
46 */
47
48 void RadFreeLights( void )
49 {
50         light_t         *light, *next;
51         
52         
53         /* delete lights */
54         for( light = lights; light; light = next )
55         {
56                 next = light->next;
57                 if( light->w != NULL )
58                         FreeWinding( light->w );
59                 free( light );
60         }
61         numLights = 0;
62         lights = NULL;
63 }
64
65
66
67 /*
68 RadClipWindingEpsilon()
69 clips a rad winding by a plane
70 based off the regular clip winding code
71 */
72
73 static void RadClipWindingEpsilon( radWinding_t *in, vec3_t normal, vec_t dist,
74         vec_t epsilon, radWinding_t *front, radWinding_t *back, clipWork_t *cw )
75 {
76         vec_t                   *dists;
77         int                             *sides;
78         int                             counts[ 3 ];
79         vec_t                   dot;            /* ydnar: changed from static b/c of threading */ /* VC 4.2 optimizer bug if not static? */
80         int                             i, j, k;
81         radVert_t               *v1, *v2, mid;
82         int                             maxPoints;
83         
84         
85         /* crutch */
86         dists = cw->dists;
87         sides = cw->sides;
88         
89         /* clear counts */
90         counts[ 0 ] = counts[ 1 ] = counts[ 2 ] = 0;
91
92         /* determine sides for each point */
93         for( i = 0; i < in->numVerts; i++ )
94         {
95                 dot = DotProduct( in->verts[ i ].xyz, normal );
96                 dot -= dist;
97                 dists[ i ] = dot;
98                 if( dot > epsilon )
99                         sides[ i ] = SIDE_FRONT;
100                 else if( dot < -epsilon )
101                         sides[ i ] = SIDE_BACK;
102                 else
103                         sides[ i ] = SIDE_ON;
104                 counts[ sides[ i ] ]++;
105         }
106         sides[ i ] = sides[ 0 ];
107         dists[ i ] = dists[ 0 ];
108         
109         /* clear front and back */
110         front->numVerts = back->numVerts = 0;
111         
112         /* handle all on one side cases */
113         if( counts[ 0 ] == 0 )
114         {
115                 memcpy( back, in, sizeof( radWinding_t ) );
116                 return;
117         }
118         if( counts[ 1 ] == 0 )
119         {
120                 memcpy( front, in, sizeof( radWinding_t ) );
121                 return;
122         }
123         
124         /* setup windings */
125         maxPoints = in->numVerts + 4;
126         
127         /* do individual verts */
128         for( i = 0; i < in->numVerts; i++ )
129         {
130                 /* do simple vertex copies first */
131                 v1 = &in->verts[ i ];
132                 
133                 if( sides[ i ] == SIDE_ON )
134                 {
135                         memcpy( &front->verts[ front->numVerts++ ], v1, sizeof( radVert_t ) );
136                         memcpy( &back->verts[ back->numVerts++ ], v1, sizeof( radVert_t ) );
137                         continue;
138                 }
139         
140                 if( sides[ i ] == SIDE_FRONT )
141                         memcpy( &front->verts[ front->numVerts++ ], v1, sizeof( radVert_t ) );
142                 
143                 if( sides[ i ] == SIDE_BACK )
144                         memcpy( &back->verts[ back->numVerts++ ], v1, sizeof( radVert_t ) );
145                 
146                 if( sides[ i + 1 ] == SIDE_ON || sides[ i + 1 ] == sides[ i ] )
147                         continue;
148                         
149                 /* generate a split vertex */
150                 v2 = &in->verts[ (i + 1) % in->numVerts ];
151                 
152                 dot = dists[ i ] / (dists[ i ] - dists[ i + 1 ]);
153
154                 /* average vertex values */
155                 for( j = 0; j < 4; j++ )
156                 {
157                         /* color */
158                         if( j < 4 )
159                         {
160                                 for( k = 0; k < MAX_LIGHTMAPS; k++ )
161                                         mid.color[ k ][ j ] = v1->color[ k ][ j ] + dot * (v2->color[ k ][ j ] - v1->color[ k ][ j ]);
162                         }
163                         
164                         /* xyz, normal */
165                         if( j < 3 )
166                         {
167                                 mid.xyz[ j ] = v1->xyz[ j ] + dot * (v2->xyz[ j ] - v1->xyz[ j ]);
168                                 mid.normal[ j ] = v1->normal[ j ] + dot * (v2->normal[ j ] - v1->normal[ j ]);
169                         }
170                         
171                         /* st, lightmap */
172                         if( j < 2 )
173                         {
174                                 mid.st[ j ] = v1->st[ j ] + dot * (v2->st[ j ] - v1->st[ j ]);
175                                 for( k = 0; k < MAX_LIGHTMAPS; k++ )
176                                         mid.lightmap[ k ][ j ] = v1->lightmap[ k ][ j ] + dot * (v2->lightmap[ k ][ j ] - v1->lightmap[ k ][ j ]);
177                         }
178                 }
179                 
180                 /* normalize the averaged normal */
181                 VectorNormalize( mid.normal, mid.normal );
182
183                 /* copy the midpoint to both windings */
184                 memcpy( &front->verts[ front->numVerts++ ], &mid, sizeof( radVert_t ) );
185                 memcpy( &back->verts[ back->numVerts++ ], &mid, sizeof( radVert_t ) );
186         }
187         
188         /* error check */
189         if( front->numVerts > maxPoints || front->numVerts > maxPoints )
190                 Error( "RadClipWindingEpsilon: points exceeded estimate" );
191         if( front->numVerts > MAX_POINTS_ON_WINDING || front->numVerts > MAX_POINTS_ON_WINDING )
192                 Error( "RadClipWindingEpsilon: MAX_POINTS_ON_WINDING" );
193 }
194
195
196
197
198
199 /*
200 RadSampleImage()
201 samples a texture image for a given color
202 returns qfalse if pixels are bad
203 */
204
205 qboolean RadSampleImage( byte *pixels, int width, int height, float st[ 2 ], float color[ 4 ] )
206 {
207         float   sto[ 2 ];
208         int             x, y;
209         
210         
211         /* clear color first */
212         color[ 0 ] = color[ 1 ] = color[ 2 ] = color[ 3 ] = 255;
213         
214         /* dummy check */
215         if( pixels == NULL || width < 1 || height < 1 )
216                 return qfalse;
217         
218         /* bias st */
219         sto[ 0 ] = st[ 0 ];
220         while( sto[ 0 ] < 0.0f )
221                 sto[ 0 ] += 1.0f;
222         sto[ 1 ] = st[ 1 ];
223         while( sto[ 1 ] < 0.0f )
224                 sto[ 1 ] += 1.0f;
225
226         /* get offsets */
227         x = ((float) width * sto[ 0 ]) + 0.5f;
228         x %= width;
229         y = ((float) height * sto[ 1 ])  + 0.5f;
230         y %= height;
231         
232         /* get pixel */
233         pixels += (y * width * 4) + (x * 4);
234         VectorCopy( pixels, color );
235         color[ 3 ] = pixels[ 3 ];
236         return qtrue;
237 }
238
239
240
241 /*
242 RadSample()
243 samples a fragment's lightmap or vertex color and returns an
244 average color and a color gradient for the sample
245 */
246
247 #define MAX_SAMPLES                     150
248 #define SAMPLE_GRANULARITY      6
249
250 static void RadSample( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, shaderInfo_t *si, radWinding_t *rw, vec3_t average, vec3_t gradient, int *style )
251 {
252         int                     i, j, k, l, v, x, y, samples;
253         vec3_t          color, mins, maxs;
254         vec4_t          textureColor;
255         float           alpha, alphaI, bf;
256         vec3_t          blend;
257         float           st[ 2 ], lightmap[ 2 ], *radLuxel;
258         radVert_t       *rv[ 3 ];
259         
260         
261         /* initial setup */
262         ClearBounds( mins, maxs );
263         VectorClear( average );
264         VectorClear( gradient );
265         alpha = 0;
266         
267         /* dummy check */
268         if( rw == NULL || rw->numVerts < 3 )
269                 return;
270         
271         /* start sampling */
272         samples = 0;
273         
274         /* sample vertex colors if no lightmap or this is the initial pass */
275         if( lm == NULL || lm->radLuxels[ lightmapNum ] == NULL || bouncing == qfalse )
276         {
277                 for( samples = 0; samples < rw->numVerts; samples++ )
278                 {
279                         /* multiply by texture color */
280                         if( !RadSampleImage( si->lightImage->pixels, si->lightImage->width, si->lightImage->height, rw->verts[ samples ].st, textureColor ) )
281                         {
282                                 VectorCopy( si->averageColor, textureColor );
283                                 textureColor[ 4 ] = 255.0f;
284                         }
285                         for( i = 0; i < 3; i++ )
286                                 color[ i ] = (textureColor[ i ] / 255) * (rw->verts[ samples ].color[ lightmapNum ][ i ] / 255.0f);
287                         
288                         AddPointToBounds( color, mins, maxs );
289                         VectorAdd( average, color, average );
290                         
291                         /* get alpha */
292                         alpha += (textureColor[ 3 ] / 255.0f) * (rw->verts[ samples ].color[ lightmapNum ][ 3 ] / 255.0f);
293                 }
294                 
295                 /* set style */
296                 *style = ds->vertexStyles[ lightmapNum ];
297         }
298         
299         /* sample lightmap */
300         else
301         {
302                 /* fracture the winding into a fan (including degenerate tris) */
303                 for( v = 1; v < (rw->numVerts - 1) && samples < MAX_SAMPLES; v++ )
304                 {
305                         /* get a triangle */
306                         rv[ 0 ] = &rw->verts[ 0 ];
307                         rv[ 1 ] = &rw->verts[ v ];
308                         rv[ 2 ] = &rw->verts[ v + 1 ];
309                         
310                         /* this code is embarassing (really should just rasterize the triangle) */
311                         for( i = 1; i < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; i++ )
312                         {
313                                 for( j = 1; j < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; j++ )
314                                 {
315                                         for( k = 1; k < SAMPLE_GRANULARITY && samples < MAX_SAMPLES; k++ )
316                                         {
317                                                 /* create a blend vector (barycentric coordinates) */
318                                                 blend[ 0 ] = i;
319                                                 blend[ 1 ] = j;
320                                                 blend[ 2 ] = k;
321                                                 bf = (1.0 / (blend[ 0 ] + blend[ 1 ] + blend[ 2 ]));
322                                                 VectorScale( blend, bf, blend );
323                                                 
324                                                 /* create a blended sample */
325                                                 st[ 0 ] = st[ 1 ] = 0.0f;
326                                                 lightmap[ 0 ] = lightmap[ 1 ] = 0.0f;
327                                                 alphaI = 0.0f;
328                                                 for( l = 0; l < 3; l++ )
329                                                 {
330                                                         st[ 0 ] += (rv[ l ]->st[ 0 ] * blend[ l ]);
331                                                         st[ 1 ] += (rv[ l ]->st[ 1 ] * blend[ l ]);
332                                                         lightmap[ 0 ] += (rv[ l ]->lightmap[ lightmapNum ][ 0 ] * blend[ l ]);
333                                                         lightmap[ 1 ] += (rv[ l ]->lightmap[ lightmapNum ][ 1 ] * blend[ l ]);
334                                                         alphaI += (rv[ l ]->color[ lightmapNum ][ 3 ] * blend[ l ]);
335                                                 }
336                                                 
337                                                 /* get lightmap xy coords */
338                                                 x = lightmap[ 0 ] / (float) superSample;
339                                                 y = lightmap[ 1 ] / (float) superSample;
340                                                 if( x < 0 )
341                                                         x = 0;
342                                                 else if ( x >= lm->w )
343                                                         x = lm->w - 1;
344                                                 if( y < 0 )
345                                                         y = 0;
346                                                 else if ( y >= lm->h )
347                                                         y = lm->h - 1;
348                                                 
349                                                 /* get radiosity luxel */
350                                                 radLuxel = RAD_LUXEL( lightmapNum, x, y );
351                                                 
352                                                 /* ignore unlit/unused luxels */
353                                                 if( radLuxel[ 0 ] < 0.0f )
354                                                         continue;
355                                                 
356                                                 /* inc samples */
357                                                 samples++;
358                                                 
359                                                 /* multiply by texture color */
360                                                 if( !RadSampleImage( si->lightImage->pixels, si->lightImage->width, si->lightImage->height, st, textureColor ) )
361                                                 {
362                                                         VectorCopy( si->averageColor, textureColor );
363                                                         textureColor[ 4 ] = 255;
364                                                 }
365                                                 for( i = 0; i < 3; i++ )
366                                                         color[ i ] = (textureColor[ i ] / 255) * (radLuxel[ i ] / 255);
367                                                 
368                                                 AddPointToBounds( color, mins, maxs );
369                                                 VectorAdd( average, color, average );
370                                                 
371                                                 /* get alpha */
372                                                 alpha += (textureColor[ 3 ] / 255) * (alphaI / 255);
373                                         }
374                                 }
375                         }
376                 }
377                 
378                 /* set style */
379                 *style = ds->lightmapStyles[ lightmapNum ];
380         }
381         
382         /* any samples? */
383         if( samples <= 0 )
384                 return;
385         
386         /* average the color */
387         VectorScale( average, (1.0 / samples), average );
388         
389         /* create the color gradient */
390         //%     VectorSubtract( maxs, mins, delta );
391         
392         /* new: color gradient will always be 0-1.0, expressed as the range of light relative to overall light */
393         //%     gradient[ 0 ] = maxs[ 0 ] > 0.0f ? (maxs[ 0 ] - mins[ 0 ]) / maxs[ 0 ] : 0.0f;
394         //%     gradient[ 1 ] = maxs[ 1 ] > 0.0f ? (maxs[ 1 ] - mins[ 1 ]) / maxs[ 1 ] : 0.0f;
395         //%     gradient[ 2 ] = maxs[ 2 ] > 0.0f ? (maxs[ 2 ] - mins[ 2 ]) / maxs[ 2 ] : 0.0f;
396         
397         /* newer: another contrast function */
398         for( i = 0; i < 3; i++ )
399                 gradient[ i ] = (maxs[ i ] - mins[ i ]) * maxs[ i ];
400 }
401
402
403
404 /*
405 RadSubdivideDiffuseLight()
406 subdivides a radiosity winding until it is smaller than subdivide, then generates an area light
407 */
408
409 #define RADIOSITY_MAX_GRADIENT          0.75f   //%     0.25f
410 #define RADIOSITY_VALUE                         500.0f
411 #define RADIOSITY_MIN                           0.0001f
412 #define RADIOSITY_CLIP_EPSILON          0.125f
413
414 static void RadSubdivideDiffuseLight( int lightmapNum, bspDrawSurface_t *ds, rawLightmap_t *lm, shaderInfo_t *si,
415         float scale, float subdivide, qboolean original, radWinding_t *rw, clipWork_t *cw )
416 {
417         int                             i, style;
418         float                   dist, area, value;
419         vec3_t                  mins, maxs, normal, d1, d2, cross, color, gradient;
420         light_t                 *light, *splash;
421         winding_t               *w;
422         
423         
424         /* dummy check */
425         if( rw == NULL || rw->numVerts < 3 )
426                 return;
427         
428         /* get bounds for winding */
429         ClearBounds( mins, maxs );
430         for( i = 0; i < rw->numVerts; i++ )
431                 AddPointToBounds( rw->verts[ i ].xyz, mins, maxs );
432         
433         /* subdivide if necessary */
434         for( i = 0; i < 3; i++ )
435         {
436                 if( maxs[ i ] - mins[ i ] > subdivide )
437                 {
438                         radWinding_t    front, back;
439                         
440                         
441                         /* make axial plane */
442                         VectorClear( normal );
443                         normal[ i ] = 1;
444                         dist = (maxs[ i ] + mins[ i ]) * 0.5f;
445                         
446                         /* clip the winding */
447                         RadClipWindingEpsilon( rw, normal, dist, RADIOSITY_CLIP_EPSILON, &front, &back, cw );
448                         
449                         /* recurse */
450                         RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qfalse, &front, cw );
451                         RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qfalse, &back, cw );
452                         return;
453                 }
454         }
455         
456         /* check area */
457         area = 0.0f;
458         for( i = 2; i < rw->numVerts; i++ )
459         {
460                 VectorSubtract( rw->verts[ i - 1 ].xyz, rw->verts[ 0 ].xyz, d1 );
461                 VectorSubtract( rw->verts[ i ].xyz, rw->verts[ 0 ].xyz, d2 );
462                 CrossProduct( d1, d2, cross );
463                 area += 0.5f * VectorLength( cross );
464         }
465         if( area < 1.0f || area > 20000000.0f )
466                 return;
467         
468         /* more subdivision may be necessary */
469         if( bouncing )
470         {
471                 /* get color sample for the surface fragment */
472                 RadSample( lightmapNum, ds, lm, si, rw, color, gradient, &style );
473                 
474                 /* if color gradient is too high, subdivide again */
475                 if( subdivide > minDiffuseSubdivide && 
476                         (gradient[ 0 ] > RADIOSITY_MAX_GRADIENT || gradient[ 1 ] > RADIOSITY_MAX_GRADIENT || gradient[ 2 ] > RADIOSITY_MAX_GRADIENT) )
477                 {
478                         RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, (subdivide / 2.0f), qfalse, rw, cw );
479                         return;
480                 }
481         }
482         
483         /* create a regular winding and an average normal */
484         w = AllocWinding( rw->numVerts );
485         w->numpoints = rw->numVerts;
486         VectorClear( normal );
487         for( i = 0; i < rw->numVerts; i++ )
488         {
489                 VectorCopy( rw->verts[ i ].xyz, w->p[ i ] );
490                 VectorAdd( normal, rw->verts[ i ].normal, normal );
491         }
492         VectorScale( normal, (1.0f / rw->numVerts), normal );
493         if( VectorNormalize( normal, normal ) == 0.0f )
494                 return;
495         
496         /* early out? */
497         if( bouncing && VectorLength( color ) < RADIOSITY_MIN )
498                 return;
499         
500         /* debug code */
501         //%     Sys_Printf( "Size: %d %d %d\n", (int) (maxs[ 0 ] - mins[ 0 ]), (int) (maxs[ 1 ] - mins[ 1 ]), (int) (maxs[ 2 ] - mins[ 2 ]) );
502         //%     Sys_Printf( "Grad: %f %f %f\n", gradient[ 0 ], gradient[ 1 ], gradient[ 2 ] );
503         
504         /* increment counts */
505         numDiffuseLights++;
506         switch( ds->surfaceType )
507         {
508                 case MST_PLANAR:
509                         numBrushDiffuseLights++;
510                         break;
511                 
512                 case MST_TRIANGLE_SOUP:
513                         numTriangleDiffuseLights++;
514                         break;
515                 
516                 case MST_PATCH:
517                         numPatchDiffuseLights++;
518                         break;
519         }
520         
521         /* create a light */
522         light = safe_malloc( sizeof( *light ) );
523         memset( light, 0, sizeof( *light ) );
524         
525         /* attach it */
526         ThreadLock();
527         light->next = lights;
528         lights = light;
529         ThreadUnlock();
530         
531         /* initialize the light */
532         light->flags = LIGHT_AREA_DEFAULT;
533         light->type = EMIT_AREA;
534         light->si = si;
535         light->fade = 1.0f;
536         light->w = w;
537         
538         /* set falloff threshold */
539         light->falloffTolerance = falloffTolerance;
540         
541         /* bouncing light? */
542         if( bouncing == qfalse )
543         {
544                 /* handle first-pass lights in normal q3a style */
545                 value = si->value;
546                 light->photons = value * area * areaScale;
547                 light->add = value * formFactorValueScale * areaScale;
548                 VectorCopy( si->color, light->color );
549                 VectorScale( light->color, light->add, light->emitColor );
550                 light->style = noStyles ? LS_NORMAL : si->lightStyle;
551                 if( light->style < LS_NORMAL || light->style >= LS_NONE )
552                         light->style = LS_NORMAL;
553                 
554                 /* set origin */
555                 VectorAdd( mins, maxs, light->origin );
556                 VectorScale( light->origin, 0.5f, light->origin );
557                 
558                 /* nudge it off the plane a bit */
559                 VectorCopy( normal, light->normal );
560                 VectorMA( light->origin, 1.0f, light->normal, light->origin );
561                 light->dist = DotProduct( light->origin, normal );
562                 
563                 /* optionally create a point splashsplash light for first pass */
564                 if( original && si->backsplashFraction > 0 )
565                 {
566                         /* allocate a new point light */
567                         splash = safe_malloc( sizeof( *splash ) );
568                         memset( splash, 0, sizeof( *splash ) );
569                         splash->next = lights;
570                         lights = splash;
571                         
572                         /* set it up */
573                         splash->flags = LIGHT_Q3A_DEFAULT;
574                         splash->type = EMIT_POINT;
575                         splash->photons = light->photons * si->backsplashFraction;
576                         splash->fade = 1.0f;
577                         splash->si = si;
578                         VectorMA( light->origin, si->backsplashDistance, normal, splash->origin );
579                         VectorCopy( si->color, splash->color );
580                         splash->falloffTolerance = falloffTolerance;
581                         splash->style = noStyles ? LS_NORMAL : light->style;
582                         
583                         /* add to counts */
584                         numPointLights++;
585                 }
586         }
587         else
588         {
589                 /* handle bounced light (radiosity) a little differently */
590                 value = RADIOSITY_VALUE * si->bounceScale * 0.375f;
591                 light->photons = value * area * bounceScale;
592                 light->add = value * formFactorValueScale * bounceScale;
593                 VectorCopy( color, light->color );
594                 VectorScale( light->color, light->add, light->emitColor );
595                 light->style = noStyles ? LS_NORMAL : style;
596                 if( light->style < LS_NORMAL || light->style >= LS_NONE )
597                         light->style = LS_NORMAL;
598                 
599                 /* set origin */
600                 WindingCenter( w, light->origin );
601                 
602                 /* nudge it off the plane a bit */
603                 VectorCopy( normal, light->normal );
604                 VectorMA( light->origin, 1.0f, light->normal, light->origin );
605                 light->dist = DotProduct( light->origin, normal );
606         }
607         
608         /* emit light from both sides? */
609         if( si->compileFlags & C_FOG || si->twoSided )
610                 light->flags |= LIGHT_TWOSIDED;
611         
612         //%     Sys_Printf( "\nAL: C: (%6f, %6f, %6f) [%6f] N: (%6f, %6f, %6f) %s\n",
613         //%             light->color[ 0 ], light->color[ 1 ], light->color[ 2 ], light->add,
614         //%             light->normal[ 0 ], light->normal[ 1 ], light->normal[ 2 ],
615         //%             light->si->shader );
616 }
617
618
619
620 /*
621 RadLightForTriangles()
622 creates unbounced diffuse lights for triangle soup (misc_models, etc)
623 */
624
625 void RadLightForTriangles( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw )
626 {
627         int                                     i, j, k, v;
628         bspDrawSurface_t        *ds;
629         surfaceInfo_t           *info;
630         float                           *radVertexLuxel;
631         radWinding_t            rw;
632         
633         
634         /* get surface */
635         ds = &bspDrawSurfaces[ num ];
636         info = &surfaceInfos[ num ];
637         
638         /* each triangle is a potential emitter */
639         rw.numVerts = 3;
640         for( i = 0; i < ds->numIndexes; i += 3 )
641         {
642                 /* copy each vert */
643                 for( j = 0; j < 3; j++ )
644                 {
645                         /* get vertex index and rad vertex luxel */
646                         v = ds->firstVert + bspDrawIndexes[ ds->firstIndex + i + j ];
647                         
648                         /* get most everything */
649                         memcpy( &rw.verts[ j ], &yDrawVerts[ v ], sizeof( bspDrawVert_t ) );
650                         
651                         /* fix colors */
652                         for( k = 0; k < MAX_LIGHTMAPS; k++ )
653                         {
654                                 radVertexLuxel = RAD_VERTEX_LUXEL( k, ds->firstVert + bspDrawIndexes[ ds->firstIndex + i + j ] );
655                                 VectorCopy( radVertexLuxel, rw.verts[ j ].color[ k ] );
656                                 rw.verts[ j ].color[ k ][ 3 ] = yDrawVerts[ v ].color[ k ][ 3 ];
657                         }
658                 }
659                 
660                 /* subdivide into area lights */
661                 RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qtrue, &rw, cw );
662         }
663 }
664
665
666
667 /*
668 RadLightForPatch()
669 creates unbounced diffuse lights for patches
670 */
671
672 #define PLANAR_EPSILON  0.1f
673
674 void RadLightForPatch( int num, int lightmapNum, rawLightmap_t *lm, shaderInfo_t *si, float scale, float subdivide, clipWork_t *cw )
675 {
676         int                                     i, x, y, v, t, pw[ 5 ], r;
677         bspDrawSurface_t        *ds;
678         surfaceInfo_t           *info;
679         bspDrawVert_t           *bogus;
680         bspDrawVert_t           *dv[ 4 ];
681         mesh_t                          src, *subdivided, *mesh;
682         float                           *radVertexLuxel;
683         float                           dist;
684         vec4_t                          plane;
685         qboolean                        planar;
686         radWinding_t            rw;
687         
688         
689         /* get surface */
690         ds = &bspDrawSurfaces[ num ];
691         info = &surfaceInfos[ num ];
692         
693         /* construct a bogus vert list with color index stuffed into color[ 0 ] */
694         bogus = safe_malloc( ds->numVerts * sizeof( bspDrawVert_t ) );
695         memcpy( bogus, &yDrawVerts[ ds->firstVert ], ds->numVerts * sizeof( bspDrawVert_t ) );
696         for( i = 0; i < ds->numVerts; i++ )
697                 bogus[ i ].color[ 0 ][ 0 ] = i;
698         
699         /* build a subdivided mesh identical to shadow facets for this patch */
700         /* this MUST MATCH FacetsForPatch() identically! */
701         src.width = ds->patchWidth;
702         src.height = ds->patchHeight;
703         src.verts = bogus;
704         //%     subdivided = SubdivideMesh( src, 8, 512 );
705         subdivided = SubdivideMesh2( src, info->patchIterations );
706         PutMeshOnCurve( *subdivided );
707         //%     MakeMeshNormals( *subdivided );
708         mesh = RemoveLinearMeshColumnsRows( subdivided );
709         FreeMesh( subdivided );
710         free( bogus );
711         
712         /* FIXME: build interpolation table into color[ 1 ] */
713         
714         /* fix up color indexes */
715         for( i = 0; i < (mesh->width * mesh->height); i++ )
716         {
717                 dv[ 0 ] = &mesh->verts[ i ];
718                 if( dv[ 0 ]->color[ 0 ][ 0 ] >= ds->numVerts )
719                         dv[ 0 ]->color[ 0 ][ 0 ] = ds->numVerts - 1;
720         }
721         
722         /* iterate through the mesh quads */
723         for( y = 0; y < (mesh->height - 1); y++ )
724         {
725                 for( x = 0; x < (mesh->width - 1); x++ )
726                 {
727                         /* set indexes */
728                         pw[ 0 ] = x + (y * mesh->width);
729                         pw[ 1 ] = x + ((y + 1) * mesh->width);
730                         pw[ 2 ] = x + 1 + ((y + 1) * mesh->width);
731                         pw[ 3 ] = x + 1 + (y * mesh->width);
732                         pw[ 4 ] = x + (y * mesh->width);        /* same as pw[ 0 ] */
733                         
734                         /* set radix */
735                         r = (x + y) & 1;
736                         
737                         /* get drawverts */
738                         dv[ 0 ] = &mesh->verts[ pw[ r + 0 ] ];
739                         dv[ 1 ] = &mesh->verts[ pw[ r + 1 ] ];
740                         dv[ 2 ] = &mesh->verts[ pw[ r + 2 ] ];
741                         dv[ 3 ] = &mesh->verts[ pw[ r + 3 ] ];
742                         
743                         /* planar? */
744                         planar = PlaneFromPoints( plane, dv[ 0 ]->xyz, dv[ 1 ]->xyz, dv[ 2 ]->xyz );
745                         if( planar )
746                         {
747                                 dist = DotProduct( dv[ 1 ]->xyz, plane ) - plane[ 3 ];
748                                 if( fabs( dist ) > PLANAR_EPSILON )
749                                         planar = qfalse;
750                         }
751                         
752                         /* generate a quad */
753                         if( planar )
754                         {
755                                 rw.numVerts = 4;
756                                 for( v = 0; v < 4; v++ )
757                                 {
758                                         /* get most everything */
759                                         memcpy( &rw.verts[ v ], dv[ v ], sizeof( bspDrawVert_t ) );
760                                         
761                                         /* fix colors */
762                                         for( i = 0; i < MAX_LIGHTMAPS; i++ )
763                                         {
764                                                 radVertexLuxel = RAD_VERTEX_LUXEL( i, ds->firstVert + dv[ v ]->color[ 0 ][ 0 ] );
765                                                 VectorCopy( radVertexLuxel, rw.verts[ v ].color[ i ] );
766                                                 rw.verts[ v ].color[ i ][ 3 ] = dv[ v ]->color[ i ][ 3 ];
767                                         }
768                                 }
769                                 
770                                 /* subdivide into area lights */
771                                 RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qtrue, &rw, cw );
772                         }
773                         
774                         /* generate 2 tris */
775                         else
776                         {
777                                 rw.numVerts = 3;
778                                 for( t = 0; t < 2; t++ )
779                                 {
780                                         for( v = 0; v < 3 + t; v++ )
781                                         {
782                                                 /* get "other" triangle (stupid hacky logic, but whatevah) */
783                                                 if( v == 1 && t == 1 )
784                                                         v++;
785
786                                                 /* get most everything */
787                                                 memcpy( &rw.verts[ v ], dv[ v ], sizeof( bspDrawVert_t ) );
788                                                 
789                                                 /* fix colors */
790                                                 for( i = 0; i < MAX_LIGHTMAPS; i++ )
791                                                 {
792                                                         radVertexLuxel = RAD_VERTEX_LUXEL( i, ds->firstVert + dv[ v ]->color[ 0 ][ 0 ] );
793                                                         VectorCopy( radVertexLuxel, rw.verts[ v ].color[ i ] );
794                                                         rw.verts[ v ].color[ i ][ 3 ] = dv[ v ]->color[ i ][ 3 ];
795                                                 }
796                                         }
797                                         
798                                         /* subdivide into area lights */
799                                         RadSubdivideDiffuseLight( lightmapNum, ds, lm, si, scale, subdivide, qtrue, &rw, cw );
800                                 }
801                         }
802                 }
803         }
804         
805         /* free the mesh */
806         FreeMesh( mesh );
807 }
808
809
810
811
812 /*
813 RadLight()
814 creates unbounced diffuse lights for a given surface
815 */
816
817 void RadLight( int num )
818 {
819         int                                     lightmapNum;
820         float                           scale, subdivide;
821         int                                     contentFlags, surfaceFlags, compileFlags;
822         bspDrawSurface_t        *ds;
823         surfaceInfo_t           *info;
824         rawLightmap_t           *lm;
825         shaderInfo_t            *si;
826         clipWork_t                      cw;
827         
828         
829         /* get drawsurface, lightmap, and shader info */
830         ds = &bspDrawSurfaces[ num ];
831         info = &surfaceInfos[ num ];
832         lm = info->lm;
833         si = info->si;
834         scale = si->bounceScale;
835         
836         /* find nodraw bit */
837         contentFlags = surfaceFlags = compileFlags = 0;
838         ApplySurfaceParm( "nodraw", &contentFlags, &surfaceFlags, &compileFlags );
839         
840         /* early outs? */
841         if( scale <= 0.0f || (si->compileFlags & C_SKY) || si->autosprite ||
842                 (bspShaders[ ds->shaderNum ].contentFlags & contentFlags) || (bspShaders[ ds->shaderNum ].surfaceFlags & surfaceFlags) ||
843                 (si->compileFlags & compileFlags) )
844                 return;
845         
846         /* determine how much we need to chop up the surface */
847         if( si->lightSubdivide )
848                 subdivide = si->lightSubdivide;
849         else
850                 subdivide = diffuseSubdivide;
851         
852         /* inc counts */
853         numDiffuseSurfaces++;
854         
855         /* iterate through styles (this could be more efficient, yes) */
856         for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
857         {
858                 /* switch on type */
859                 if( ds->lightmapStyles[ lightmapNum ] != LS_NONE && ds->lightmapStyles[ lightmapNum ] != LS_UNUSED )
860                 {
861                         switch( ds->surfaceType )
862                         {
863                                 case MST_PLANAR:
864                                 case MST_TRIANGLE_SOUP:
865                                         RadLightForTriangles( num, lightmapNum, lm, si, scale, subdivide, &cw );
866                                         break;
867                                 
868                                 case MST_PATCH:
869                                         RadLightForPatch( num, lightmapNum, lm, si, scale, subdivide, &cw );
870                                         break;
871                                 
872                                 default:
873                                         break;
874                         }
875                 }
876         }
877 }
878
879
880
881 /*
882 RadCreateDiffuseLights()
883 creates lights for unbounced light on surfaces in the bsp
884 */
885
886 int     iterations = 0;
887
888 void RadCreateDiffuseLights( void )
889 {
890         /* startup */
891         Sys_FPrintf( SYS_VRB, "--- RadCreateDiffuseLights ---\n" );
892         numDiffuseSurfaces = 0;
893         numDiffuseLights = 0;
894         numBrushDiffuseLights = 0;
895         numTriangleDiffuseLights = 0;
896         numPatchDiffuseLights = 0;
897         numAreaLights = 0;
898         
899         /* hit every surface (threaded) */
900         RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, RadLight );
901         
902         /* dump the lights generated to a file */
903         if( dump )
904         {
905                 char    dumpName[ 1024 ], ext[ 64 ];
906                 FILE    *file;
907                 light_t *light;
908                 
909                 strcpy( dumpName, source );
910                 StripExtension( dumpName );
911                 sprintf( ext, "_bounce_%03d.map", iterations );
912                 strcat( dumpName, ext );
913                 file = fopen( dumpName, "wb" );
914                 Sys_Printf( "Writing %s...\n", dumpName );
915                 if( file )
916                 {
917                         for( light = lights; light; light = light->next )
918                         {
919                                 fprintf( file,
920                                         "{\n"
921                                         "\"classname\" \"light\"\n"
922                                         "\"light\" \"%d\"\n"
923                                         "\"origin\" \"%.0f %.0f %.0f\"\n"
924                                         "\"_color\" \"%.3f %.3f %.3f\"\n"
925                                         "}\n",
926                                         
927                                         (int) light->add,
928                                         
929                                         light->origin[ 0 ],
930                                         light->origin[ 1 ],
931                                         light->origin[ 2 ],
932                                         
933                                         light->color[ 0 ],
934                                         light->color[ 1 ],
935                                         light->color[ 2 ] );
936                         }
937                         fclose( file );
938                 }
939         }
940         
941         /* increment */
942         iterations++;
943         
944         /* print counts */
945         Sys_Printf( "%8d diffuse surfaces\n", numDiffuseSurfaces );
946         Sys_FPrintf( SYS_VRB, "%8d total diffuse lights\n", numDiffuseLights );
947         Sys_FPrintf( SYS_VRB, "%8d brush diffuse lights\n", numBrushDiffuseLights );
948         Sys_FPrintf( SYS_VRB, "%8d patch diffuse lights\n", numPatchDiffuseLights );
949         Sys_FPrintf( SYS_VRB, "%8d triangle diffuse lights\n", numTriangleDiffuseLights );
950 }
951
952
953
954
955
956