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