1 /* -------------------------------------------------------------------------------
3 Copyright (C) 1999-2007 id Software, Inc. and contributors.
4 For a list of contributors, see the accompanying CONTRIBUTORS file.
6 This file is part of GtkRadiant.
8 GtkRadiant is free software; you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation; either version 2 of the License, or
11 (at your option) any later version.
13 GtkRadiant is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
18 You should have received a copy of the GNU General Public License
19 along with GtkRadiant; if not, write to the Free Software
20 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
22 ----------------------------------------------------------------------------------
24 This code has been altered significantly from its original form, to support
25 several games based on the Quake III Arena engine, in the form of "Q3Map2."
27 ------------------------------------------------------------------------------- */
42 CreateSunLight() - ydnar
43 this creates a sun light
46 static void CreateSunLight( sun_t *sun )
49 float photons, d, angle, elevation, da, de;
59 if( sun->numSamples < 1 )
63 photons = sun->photons / sun->numSamples;
65 /* create the right number of suns */
66 for( i = 0; i < sun->numSamples; i++ )
68 /* calculate sun direction */
70 VectorCopy( sun->direction, direction );
74 sun->direction[ 0 ] = cos( angle ) * cos( elevation );
75 sun->direction[ 1 ] = sin( angle ) * cos( elevation );
76 sun->direction[ 2 ] = sin( elevation );
78 xz_dist = sqrt( x*x + z*z )
79 latitude = atan2( xz_dist, y ) * RADIANS
80 longitude = atan2( x, z ) * RADIANS
83 d = sqrt( sun->direction[ 0 ] * sun->direction[ 0 ] + sun->direction[ 1 ] * sun->direction[ 1 ] );
84 angle = atan2( sun->direction[ 1 ], sun->direction[ 0 ] );
85 elevation = atan2( sun->direction[ 2 ], d );
87 /* jitter the angles (loop to keep random sample within sun->deviance steridians) */
90 da = (Random() * 2.0f - 1.0f) * sun->deviance;
91 de = (Random() * 2.0f - 1.0f) * sun->deviance;
93 while( (da * da + de * de) > (sun->deviance * sun->deviance) );
98 //% Sys_Printf( "%d: Angle: %3.4f Elevation: %3.3f\n", sun->numSamples, (angle / Q_PI * 180.0f), (elevation / Q_PI * 180.0f) );
100 /* create new vector */
101 direction[ 0 ] = cos( angle ) * cos( elevation );
102 direction[ 1 ] = sin( angle ) * cos( elevation );
103 direction[ 2 ] = sin( elevation );
108 light = safe_malloc( sizeof( *light ) );
109 memset( light, 0, sizeof( *light ) );
110 light->next = lights;
113 /* initialize the light */
114 light->flags = LIGHT_SUN_DEFAULT;
115 light->type = EMIT_SUN;
117 light->falloffTolerance = falloffTolerance;
118 light->filterRadius = sun->filterRadius / sun->numSamples;
119 light->style = noStyles ? LS_NORMAL : sun->style;
121 /* set the light's position out to infinity */
122 VectorMA( vec3_origin, (MAX_WORLD_COORD * 8.0f), direction, light->origin ); /* MAX_WORLD_COORD * 2.0f */
124 /* set the facing to be the inverse of the sun direction */
125 VectorScale( direction, -1.0, light->normal );
126 light->dist = DotProduct( light->origin, light->normal );
128 /* set color and photons */
129 VectorCopy( sun->color, light->color );
130 light->photons = photons * skyScale;
134 if( sun->next != NULL )
135 CreateSunLight( sun->next );
141 CreateSkyLights() - ydnar
142 simulates sky light with multiple suns
145 static void CreateSkyLights( vec3_t color, float value, int iterations, float filterRadius, int style )
148 int angleSteps, elevationSteps;
149 float angle, elevation;
150 float angleStep, elevationStep;
156 if( value <= 0.0f || iterations < 2 )
159 /* calculate some stuff */
160 step = 2.0f / (iterations - 1);
163 /* basic sun setup */
164 VectorCopy( color, sun.color );
166 sun.filterRadius = filterRadius;
168 sun.style = noStyles ? LS_NORMAL : style;
172 elevationSteps = iterations - 1;
173 angleSteps = elevationSteps * 4;
175 elevationStep = DEG2RAD( 90.0f / iterations ); /* skip elevation 0 */
176 angleStep = DEG2RAD( 360.0f / angleSteps );
178 /* calc individual sun brightness */
179 numSuns = angleSteps * elevationSteps + 1;
180 sun.photons = value / numSuns;
182 /* iterate elevation */
183 elevation = elevationStep * 0.5f;
185 for( i = 0, elevation = elevationStep * 0.5f; i < elevationSteps; i++ )
188 for( j = 0; j < angleSteps; j++ )
191 sun.direction[ 0 ] = cos( angle ) * cos( elevation );
192 sun.direction[ 1 ] = sin( angle ) * cos( elevation );
193 sun.direction[ 2 ] = sin( elevation );
194 CreateSunLight( &sun );
201 elevation += elevationStep;
202 angle += angleStep / elevationSteps;
205 /* create vertical sun */
206 VectorSet( sun.direction, 0.0f, 0.0f, 1.0f );
207 CreateSunLight( &sun );
217 creates lights from light entities
220 void CreateEntityLights( void )
223 light_t *light, *light2;
229 float intensity, scale, deviance, filterRadius;
230 int spawnflags, flags, numSamples;
234 /* go throught entity list and find lights */
235 for( i = 0; i < numEntities; i++ )
239 name = ValueForKey( e, "classname" );
241 /* ydnar: check for lightJunior */
242 if( Q_strncasecmp( name, "lightJunior", 11 ) == 0 )
244 else if( Q_strncasecmp( name, "light", 5 ) == 0 )
249 /* lights with target names (and therefore styles) are only parsed from BSP */
250 target = ValueForKey( e, "targetname" );
251 if( target[ 0 ] != '\0' && i >= numBSPEntities )
256 light = safe_malloc( sizeof( *light ) );
257 memset( light, 0, sizeof( *light ) );
258 light->next = lights;
261 /* handle spawnflags */
262 spawnflags = IntForKey( e, "spawnflags" );
264 /* ydnar: quake 3+ light behavior */
265 if( wolfLight == qfalse )
267 /* set default flags */
268 flags = LIGHT_Q3A_DEFAULT;
270 /* linear attenuation? */
273 flags |= LIGHT_ATTEN_LINEAR;
274 flags &= ~LIGHT_ATTEN_ANGLE;
277 /* no angle attenuate? */
279 flags &= ~LIGHT_ATTEN_ANGLE;
282 /* ydnar: wolf light behavior */
285 /* set default flags */
286 flags = LIGHT_WOLF_DEFAULT;
288 /* inverse distance squared attenuation? */
291 flags &= ~LIGHT_ATTEN_LINEAR;
292 flags |= LIGHT_ATTEN_ANGLE;
295 /* angle attenuate? */
297 flags |= LIGHT_ATTEN_ANGLE;
300 /* other flags (borrowed from wolf) */
302 /* wolf dark light? */
303 if( (spawnflags & 4) || (spawnflags & 8) )
307 if( spawnflags & 16 )
308 flags &= ~LIGHT_GRID;
314 flags &= ~LIGHT_SURFACES;
317 /* vortex: unnormalized? */
319 flags |= LIGHT_UNNORMALIZED;
321 /* vortex: distance atten? */
323 flags |= LIGHT_ATTEN_DISTANCE;
325 /* store the flags */
326 light->flags = flags;
328 /* ydnar: set fade key (from wolf) */
330 if( light->flags & LIGHT_ATTEN_LINEAR )
332 light->fade = FloatForKey( e, "fade" );
333 if( light->fade == 0.0f )
337 /* ydnar: set angle scaling (from vlight) */
338 light->angleScale = FloatForKey( e, "_anglescale" );
339 if( light->angleScale != 0.0f )
340 light->flags |= LIGHT_ATTEN_ANGLE;
343 GetVectorForKey( e, "origin", light->origin);
344 light->style = IntForKey( e, "_style" );
345 if( light->style == LS_NORMAL )
346 light->style = IntForKey( e, "style" );
347 if( light->style < LS_NORMAL || light->style >= LS_NONE )
348 Error( "Invalid lightstyle (%d) on entity %d", light->style, i );
350 if( light->style != LS_NORMAL ) {
351 Sys_FPrintf (SYS_WRN, "WARNING: Styled light found targeting %s\n **", target );
354 /* set light intensity */
355 intensity = FloatForKey( e, "_light" );
356 if( intensity == 0.0f )
357 intensity = FloatForKey( e, "light" );
358 if( intensity == 0.0f)
361 /* ydnar: set light scale (sof2) */
362 scale = FloatForKey( e, "scale" );
367 /* ydnar: get deviance and samples */
368 deviance = FloatForKey( e, "_deviance" );
369 if( deviance == 0.0f )
370 deviance = FloatForKey( e, "_deviation" );
371 if( deviance == 0.0f )
372 deviance = FloatForKey( e, "_jitter" );
373 numSamples = IntForKey( e, "_samples" );
374 if( deviance < 0.0f || numSamples < 1 )
379 intensity /= numSamples;
381 /* ydnar: get filter radius */
382 filterRadius = FloatForKey( e, "_filterradius" );
383 if( filterRadius == 0.0f )
384 filterRadius = FloatForKey( e, "_filteradius" );
385 if( filterRadius == 0.0f )
386 filterRadius = FloatForKey( e, "_filter" );
387 if( filterRadius < 0.0f )
389 light->filterRadius = filterRadius;
391 /* set light color */
392 _color = ValueForKey( e, "_color" );
393 if( _color && _color[ 0 ] )
395 sscanf( _color, "%f %f %f", &light->color[ 0 ], &light->color[ 1 ], &light->color[ 2 ] );
396 if (!(light->flags & LIGHT_UNNORMALIZED))
398 ColorNormalize( light->color, light->color );
402 light->color[ 0 ] = light->color[ 1 ] = light->color[ 2 ] = 1.0f;
404 intensity = intensity * pointScale;
405 light->photons = intensity;
407 light->type = EMIT_POINT;
409 /* set falloff threshold */
410 light->falloffTolerance = falloffTolerance / numSamples;
412 /* lights with a target will be spotlights */
413 target = ValueForKey( e, "target" );
423 e2 = FindTargetEntity( target );
426 Sys_Printf( "WARNING: light at (%i %i %i) has missing target\n",
427 (int) light->origin[ 0 ], (int) light->origin[ 1 ], (int) light->origin[ 2 ] );
431 /* not a point light */
435 /* make a spotlight */
436 GetVectorForKey( e2, "origin", dest );
437 VectorSubtract( dest, light->origin, light->normal );
438 dist = VectorNormalize( light->normal, light->normal );
439 radius = FloatForKey( e, "radius" );
444 light->radiusByDist = (radius + 16) / dist;
445 light->type = EMIT_SPOT;
447 /* ydnar: wolf mods: spotlights always use nonlinear + angle attenuation */
448 light->flags &= ~LIGHT_ATTEN_LINEAR;
449 light->flags |= LIGHT_ATTEN_ANGLE;
452 /* ydnar: is this a sun? */
453 _sun = ValueForKey( e, "_sun" );
454 if( _sun[ 0 ] == '1' )
456 /* not a spot light */
459 /* unlink this light */
460 lights = light->next;
463 VectorScale( light->normal, -1.0f, sun.direction );
464 VectorCopy( light->color, sun.color );
465 sun.photons = (intensity / pointScale);
466 sun.deviance = deviance / 180.0f * Q_PI;
467 sun.numSamples = numSamples;
468 sun.style = noStyles ? LS_NORMAL : light->style;
471 /* make a sun light */
472 CreateSunLight( &sun );
474 /* free original light */
478 /* skip the rest of this love story */
484 /* jitter the light */
485 for( j = 1; j < numSamples; j++ )
488 light2 = safe_malloc( sizeof( *light ) );
489 memcpy( light2, light, sizeof( *light ) );
490 light2->next = lights;
494 if( light->type == EMIT_SPOT )
500 light2->origin[ 0 ] = light->origin[ 0 ] + (Random() * 2.0f - 1.0f) * deviance;
501 light2->origin[ 1 ] = light->origin[ 1 ] + (Random() * 2.0f - 1.0f) * deviance;
502 light2->origin[ 2 ] = light->origin[ 2 ] + (Random() * 2.0f - 1.0f) * deviance;
510 CreateSurfaceLights() - ydnar
511 this hijacks the radiosity code to generate surface lights for first pass
514 #define APPROX_BOUNCE 1.0f
516 void CreateSurfaceLights( void )
519 bspDrawSurface_t *ds;
529 /* get sun shader supressor */
530 nss = ValueForKey( &entities[ 0 ], "_noshadersun" );
532 /* walk the list of surfaces */
533 for( i = 0; i < numBSPDrawSurfaces; i++ )
535 /* get surface and other bits */
536 ds = &bspDrawSurfaces[ i ];
537 info = &surfaceInfos[ i ];
541 if( si->sun != NULL && nss[ 0 ] != '1' )
543 Sys_FPrintf( SYS_VRB, "Sun: %s\n", si->shader );
544 CreateSunLight( si->sun );
545 si->sun = NULL; /* FIXME: leak! */
549 if( si->skyLightValue > 0.0f )
551 Sys_FPrintf( SYS_VRB, "Sky: %s\n", si->shader );
552 CreateSkyLights( si->color, si->skyLightValue, si->skyLightIterations, si->lightFilterRadius, si->lightStyle );
553 si->skyLightValue = 0.0f; /* FIXME: hack! */
556 /* try to early out */
560 /* autosprite shaders become point lights */
563 /* create an average xyz */
564 VectorAdd( info->mins, info->maxs, origin );
565 VectorScale( origin, 0.5f, origin );
568 light = safe_malloc( sizeof( *light ) );
569 memset( light, 0, sizeof( *light ) );
570 light->next = lights;
574 light->flags = LIGHT_Q3A_DEFAULT;
575 light->type = EMIT_POINT;
576 light->photons = si->value * pointScale;
579 VectorCopy( origin, light->origin );
580 VectorCopy( si->color, light->color );
581 light->falloffTolerance = falloffTolerance;
582 light->style = si->lightStyle;
584 /* add to point light count and continue */
589 /* get subdivision amount */
590 if( si->lightSubdivide > 0 )
591 subdivide = si->lightSubdivide;
593 subdivide = defaultLightSubdivide;
596 switch( ds->surfaceType )
599 case MST_TRIANGLE_SOUP:
600 RadLightForTriangles( i, 0, info->lm, si, APPROX_BOUNCE, subdivide, &cw );
604 RadLightForPatch( i, 0, info->lm, si, APPROX_BOUNCE, subdivide, &cw );
617 find the offset values for inline models
620 void SetEntityOrigins( void )
628 bspDrawSurface_t *ds;
631 /* ydnar: copy drawverts into private storage for nefarious purposes */
632 yDrawVerts = safe_malloc( numBSPDrawVerts * sizeof( bspDrawVert_t ) );
633 memcpy( yDrawVerts, bspDrawVerts, numBSPDrawVerts * sizeof( bspDrawVert_t ) );
635 /* set the entity origins */
636 for( i = 0; i < numEntities; i++ )
638 /* get entity and model */
640 key = ValueForKey( e, "model" );
641 if( key[ 0 ] != '*' )
643 modelnum = atoi( key + 1 );
644 dm = &bspModels[ modelnum ];
646 /* get entity origin */
647 key = ValueForKey( e, "origin" );
648 if( key[ 0 ] == '\0' )
650 GetVectorForKey( e, "origin", origin );
652 /* set origin for all surfaces for this model */
653 for( j = 0; j < dm->numBSPSurfaces; j++ )
656 ds = &bspDrawSurfaces[ dm->firstBSPSurface + j ];
659 for( k = 0; k < ds->numVerts; k++ )
661 f = ds->firstVert + k;
662 VectorAdd( origin, bspDrawVerts[ f ].xyz, yDrawVerts[ f ].xyz );
671 PointToPolygonFormFactor()
672 calculates the area over a point/normal hemisphere a winding covers
673 ydnar: fixme: there has to be a faster way to calculate this
674 without the expensive per-vert sqrts and transcendental functions
675 ydnar 2002-09-30: added -faster switch because only 19% deviance > 10%
676 between this and the approximation
679 #define ONE_OVER_2PI 0.159154942f //% (1.0f / (2.0f * 3.141592657f))
681 float PointToPolygonFormFactor( const vec3_t point, const vec3_t normal, const winding_t *w )
683 vec3_t triVector, triNormal;
685 vec3_t dirs[ MAX_POINTS_ON_WINDING ];
687 float dot, angle, facing;
690 /* this is expensive */
691 for( i = 0; i < w->numpoints; i++ )
693 VectorSubtract( w->p[ i ], point, dirs[ i ] );
694 VectorNormalize( dirs[ i ], dirs[ i ] );
697 /* duplicate first vertex to avoid mod operation */
698 VectorCopy( dirs[ 0 ], dirs[ i ] );
700 /* calculcate relative area */
702 for( i = 0; i < w->numpoints; i++ )
706 dot = DotProduct( dirs[ i ], dirs[ j ] );
708 /* roundoff can cause slight creep, which gives an IND from acos */
711 else if( dot < -1.0f )
717 CrossProduct( dirs[ i ], dirs[ j ], triVector );
718 if( VectorNormalize( triVector, triNormal ) < 0.0001f )
721 facing = DotProduct( normal, triNormal );
722 total += facing * angle;
724 /* ydnar: this was throwing too many errors with radiosity + crappy maps. ignoring it. */
725 if( total > 6.3f || total < -6.3f )
729 /* now in the range of 0 to 1 over the entire incoming hemisphere */
730 //% total /= (2.0f * 3.141592657f);
731 total *= ONE_OVER_2PI;
738 LightContributionTosample()
739 determines the amount of light reaching a sample (luxel or vertex) from a given light
742 int LightContributionToSample( trace_t *trace )
751 light = trace->light;
754 VectorClear( trace->color );
755 VectorClear( trace->colorNoShadow );
757 /* ydnar: early out */
758 if( !(light->flags & LIGHT_SURFACES) || light->envelope <= 0.0f )
761 /* do some culling checks */
762 if( light->type != EMIT_SUN )
764 /* MrE: if the light is behind the surface */
765 if( trace->twoSided == qfalse )
766 if( DotProduct( light->origin, trace->normal ) - DotProduct( trace->origin, trace->normal ) < 0.0f )
769 /* ydnar: test pvs */
770 if( !ClusterVisible( trace->cluster, light->cluster ) )
774 /* exact point to polygon form factor */
775 if( light->type == EMIT_AREA )
781 /* project sample point into light plane */
782 d = DotProduct( trace->origin, light->normal ) - light->dist;
785 /* sample point behind plane? */
786 if( !(light->flags & LIGHT_TWOSIDED) && d < -1.0f )
789 /* sample plane coincident? */
790 if( d > -3.0f && DotProduct( trace->normal, light->normal ) > 0.9f )
794 /* nudge the point so that it is clearly forward of the light */
795 /* so that surfaces meeting a light emiter don't get black edges */
796 if( d > -8.0f && d < 8.0f )
797 VectorMA( trace->origin, (8.0f - d), light->normal, pushedOrigin );
799 VectorCopy( trace->origin, pushedOrigin );
801 /* get direction and distance */
802 VectorCopy( light->origin, trace->end );
803 dist = SetupTrace( trace );
804 if( dist >= light->envelope )
807 /* ptpff approximation */
810 /* angle attenuation */
811 angle = DotProduct( trace->normal, trace->direction );
813 /* twosided lighting */
814 if( trace->twoSided )
815 angle = fabs( angle );
818 angle *= -DotProduct( light->normal, trace->direction );
821 else if( angle < 0.0f &&
822 (trace->twoSided || (light->flags & LIGHT_TWOSIDED)) )
824 add = light->photons / (dist * dist) * angle;
828 /* calculate the contribution */
829 factor = PointToPolygonFormFactor( pushedOrigin, trace->normal, light->w );
832 else if( factor < 0.0f )
834 /* twosided lighting */
835 if( trace->twoSided || (light->flags & LIGHT_TWOSIDED) )
839 /* push light origin to other side of the plane */
840 VectorMA( light->origin, -2.0f, light->normal, trace->end );
841 dist = SetupTrace( trace );
842 if( dist >= light->envelope )
849 /* ydnar: moved to here */
850 add = factor * light->add;
854 /* point/spot lights */
855 else if( light->type == EMIT_POINT || light->type == EMIT_SPOT )
857 /* get direction and distance */
858 VectorCopy( light->origin, trace->end );
859 dist = SetupTrace( trace );
860 if( dist >= light->envelope )
863 /* clamp the distance to prevent super hot spots */
867 /* angle attenuation */
868 angle = (light->flags & LIGHT_ATTEN_ANGLE) ? DotProduct( trace->normal, trace->direction ) : 1.0f;
869 if( light->angleScale != 0.0f )
871 angle /= light->angleScale;
876 /* twosided lighting */
877 if( trace->twoSided )
878 angle = fabs( angle );
881 if( light->flags & LIGHT_ATTEN_LINEAR )
883 add = angle * light->photons * linearScale - (dist * light->fade);
888 add = light->photons / (dist * dist) * angle;
890 /* handle spotlights */
891 if( light->type == EMIT_SPOT )
893 float distByNormal, radiusAtDist, sampleRadius;
894 vec3_t pointAtDist, distToSample;
896 /* do cone calculation */
897 distByNormal = -DotProduct( trace->displacement, light->normal );
898 if( distByNormal < 0.0f )
900 VectorMA( light->origin, distByNormal, light->normal, pointAtDist );
901 radiusAtDist = light->radiusByDist * distByNormal;
902 VectorSubtract( trace->origin, pointAtDist, distToSample );
903 sampleRadius = VectorLength( distToSample );
905 /* outside the cone */
906 if( sampleRadius >= radiusAtDist )
910 if( sampleRadius > (radiusAtDist - 32.0f) )
911 add *= ((radiusAtDist - sampleRadius) / 32.0f);
915 /* ydnar: sunlight */
916 else if( light->type == EMIT_SUN )
918 /* get origin and direction */
919 VectorAdd( trace->origin, light->origin, trace->end );
920 dist = SetupTrace( trace );
922 /* angle attenuation */
923 angle = (light->flags & LIGHT_ATTEN_ANGLE)
924 ? DotProduct( trace->normal, trace->direction )
927 /* twosided lighting */
928 if( trace->twoSided )
929 angle = fabs( angle );
932 add = light->photons * angle;
936 /* VorteX: set noShadow color */
937 VectorScale(light->color, add, trace->colorNoShadow);
940 trace->testAll = qtrue;
941 VectorScale( light->color, add, trace->color );
944 if( trace->testOcclusion && !trace->forceSunlight )
948 if( !(trace->compileFlags & C_SKY) || trace->opaque )
950 VectorClear( trace->color );
955 /* return to sender */
959 /* VorteX: set noShadow color */
960 VectorScale(light->color, add, trace->colorNoShadow);
962 /* ydnar: changed to a variable number */
963 if( add <= 0.0f || (add <= light->falloffTolerance && (light->flags & LIGHT_FAST_ACTUAL)) )
967 trace->testAll = qfalse;
968 VectorScale( light->color, add, trace->color );
972 if( trace->passSolid || trace->opaque )
974 VectorClear( trace->color );
978 /* return to sender */
986 determines the amount of light reaching a sample (luxel or vertex)
989 void LightingAtSample( trace_t *trace, byte styles[ MAX_LIGHTMAPS ], vec3_t colors[ MAX_LIGHTMAPS ] )
995 for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
996 VectorClear( colors[ lightmapNum ] );
998 /* ydnar: normalmap */
1001 colors[ 0 ][ 0 ] = (trace->normal[ 0 ] + 1.0f) * 127.5f;
1002 colors[ 0 ][ 1 ] = (trace->normal[ 1 ] + 1.0f) * 127.5f;
1003 colors[ 0 ][ 2 ] = (trace->normal[ 2 ] + 1.0f) * 127.5f;
1007 /* ydnar: don't bounce ambient all the time */
1009 VectorCopy( ambientColor, colors[ 0 ] );
1011 /* ydnar: trace to all the list of lights pre-stored in tw */
1012 for( i = 0; i < trace->numLights && trace->lights[ i ] != NULL; i++ )
1015 trace->light = trace->lights[ i ];
1018 for( lightmapNum = 0; lightmapNum < MAX_LIGHTMAPS; lightmapNum++ )
1020 if( styles[ lightmapNum ] == trace->light->style ||
1021 styles[ lightmapNum ] == LS_NONE )
1025 /* max of MAX_LIGHTMAPS (4) styles allowed to hit a sample */
1026 if( lightmapNum >= MAX_LIGHTMAPS )
1030 LightContributionToSample( trace );
1031 if( trace->color[ 0 ] == 0.0f && trace->color[ 1 ] == 0.0f && trace->color[ 2 ] == 0.0f )
1034 /* handle negative light */
1035 if( trace->light->flags & LIGHT_NEGATIVE )
1036 VectorScale( trace->color, -1.0f, trace->color );
1039 styles[ lightmapNum ] = trace->light->style;
1042 VectorAdd( colors[ lightmapNum ], trace->color, colors[ lightmapNum ] );
1046 colors[ 0 ][ 0 ] >= 255.0f &&
1047 colors[ 0 ][ 1 ] >= 255.0f &&
1048 colors[ 0 ][ 2 ] >= 255.0f )
1056 LightContributionToPoint()
1057 for a given light, how much light/color reaches a given point in space (with no facing)
1058 note: this is similar to LightContributionToSample() but optimized for omnidirectional sampling
1061 int LightContributionToPoint( trace_t *trace )
1068 light = trace->light;
1071 VectorClear( trace->color );
1073 /* ydnar: early out */
1074 if( !(light->flags & LIGHT_GRID) || light->envelope <= 0.0f )
1077 /* is this a sun? */
1078 if( light->type != EMIT_SUN )
1085 if( !ClusterVisible( trace->cluster, light->cluster ) )
1089 /* ydnar: check origin against light's pvs envelope */
1090 if( trace->origin[ 0 ] > light->maxs[ 0 ] || trace->origin[ 0 ] < light->mins[ 0 ] ||
1091 trace->origin[ 1 ] > light->maxs[ 1 ] || trace->origin[ 1 ] < light->mins[ 1 ] ||
1092 trace->origin[ 2 ] > light->maxs[ 2 ] || trace->origin[ 2 ] < light->mins[ 2 ] )
1098 /* set light origin */
1099 if( light->type == EMIT_SUN )
1100 VectorAdd( trace->origin, light->origin, trace->end );
1102 VectorCopy( light->origin, trace->end );
1105 dist = SetupTrace( trace );
1108 if( dist > light->envelope )
1110 gridEnvelopeCulled++;
1114 /* ptpff approximation */
1115 if( light->type == EMIT_AREA && faster )
1117 /* clamp the distance to prevent super hot spots */
1122 add = light->photons / (dist * dist);
1125 /* exact point to polygon form factor */
1126 else if( light->type == EMIT_AREA )
1129 vec3_t pushedOrigin;
1132 /* see if the point is behind the light */
1133 d = DotProduct( trace->origin, light->normal ) - light->dist;
1134 if( !(light->flags & LIGHT_TWOSIDED) && d < -1.0f )
1137 /* nudge the point so that it is clearly forward of the light */
1138 /* so that surfaces meeting a light emiter don't get black edges */
1139 if( d > -8.0f && d < 8.0f )
1140 VectorMA( trace->origin, (8.0f - d), light->normal, pushedOrigin );
1142 VectorCopy( trace->origin, pushedOrigin );
1144 /* calculate the contribution (ydnar 2002-10-21: [bug 642] bad normal calc) */
1145 factor = PointToPolygonFormFactor( pushedOrigin, trace->direction, light->w );
1146 if( factor == 0.0f )
1148 else if( factor < 0.0f )
1150 if( light->flags & LIGHT_TWOSIDED )
1156 /* ydnar: moved to here */
1157 add = factor * light->add;
1160 /* point/spot lights */
1161 else if( light->type == EMIT_POINT || light->type == EMIT_SPOT )
1163 /* clamp the distance to prevent super hot spots */
1168 if( light->flags & LIGHT_ATTEN_LINEAR )
1170 add = light->photons * linearScale - (dist * light->fade);
1175 add = light->photons / (dist * dist);
1177 /* handle spotlights */
1178 if( light->type == EMIT_SPOT )
1180 float distByNormal, radiusAtDist, sampleRadius;
1181 vec3_t pointAtDist, distToSample;
1184 /* do cone calculation */
1185 distByNormal = -DotProduct( trace->displacement, light->normal );
1186 if( distByNormal < 0.0f )
1188 VectorMA( light->origin, distByNormal, light->normal, pointAtDist );
1189 radiusAtDist = light->radiusByDist * distByNormal;
1190 VectorSubtract( trace->origin, pointAtDist, distToSample );
1191 sampleRadius = VectorLength( distToSample );
1193 /* outside the cone */
1194 if( sampleRadius >= radiusAtDist )
1198 if( sampleRadius > (radiusAtDist - 32.0f) )
1199 add *= ((radiusAtDist - sampleRadius) / 32.0f);
1203 /* ydnar: sunlight */
1204 else if( light->type == EMIT_SUN )
1207 add = light->photons;
1212 trace->testAll = qtrue;
1213 VectorScale( light->color, add, trace->color );
1215 /* trace to point */
1216 if( trace->testOcclusion && !trace->forceSunlight )
1220 if( !(trace->compileFlags & C_SKY) || trace->opaque )
1222 VectorClear( trace->color );
1227 /* return to sender */
1231 /* unknown light type */
1235 /* ydnar: changed to a variable number */
1236 if( add <= 0.0f || (add <= light->falloffTolerance && (light->flags & LIGHT_FAST_ACTUAL)) )
1240 trace->testAll = qfalse;
1241 VectorScale( light->color, add, trace->color );
1245 if( trace->passSolid )
1247 VectorClear( trace->color );
1251 /* we have a valid sample */
1259 grid samples are for quickly determining the lighting
1260 of dynamically placed entities in the world
1263 #define MAX_CONTRIBUTIONS 32768
1273 void TraceGrid( int num )
1275 int i, j, x, y, z, mod, step, numCon, numStyles;
1277 vec3_t baseOrigin, cheapColor, color, thisdir;
1279 bspGridPoint_t *bgp;
1280 contribution_t contributions[ MAX_CONTRIBUTIONS ];
1284 /* get grid points */
1285 gp = &rawGridPoints[ num ];
1286 bgp = &bspGridPoints[ num ];
1288 /* get grid origin */
1290 z = mod / (gridBounds[ 0 ] * gridBounds[ 1 ]);
1291 mod -= z * (gridBounds[ 0 ] * gridBounds[ 1 ]);
1292 y = mod / gridBounds[ 0 ];
1293 mod -= y * gridBounds[ 0 ];
1296 trace.origin[ 0 ] = gridMins[ 0 ] + x * gridSize[ 0 ];
1297 trace.origin[ 1 ] = gridMins[ 1 ] + y * gridSize[ 1 ];
1298 trace.origin[ 2 ] = gridMins[ 2 ] + z * gridSize[ 2 ];
1300 /* set inhibit sphere */
1301 if( gridSize[ 0 ] > gridSize[ 1 ] && gridSize[ 0 ] > gridSize[ 2 ] )
1302 trace.inhibitRadius = gridSize[ 0 ] * 0.5f;
1303 else if( gridSize[ 1 ] > gridSize[ 0 ] && gridSize[ 1 ] > gridSize[ 2 ] )
1304 trace.inhibitRadius = gridSize[ 1 ] * 0.5f;
1306 trace.inhibitRadius = gridSize[ 2 ] * 0.5f;
1308 /* find point cluster */
1309 trace.cluster = ClusterForPointExt( trace.origin, GRID_EPSILON );
1310 if( trace.cluster < 0 )
1312 /* try to nudge the origin around to find a valid point */
1313 VectorCopy( trace.origin, baseOrigin );
1314 for( step = 0.05; step <= 0.5; step += 0.05 )
1316 for( i = 0; i < 8; i++ )
1318 VectorCopy( baseOrigin, trace.origin );
1320 trace.origin[ 0 ] += step * gridSize[0];
1322 trace.origin[ 0 ] -= step * gridSize[0];
1325 trace.origin[ 1 ] += step * gridSize[1];
1327 trace.origin[ 1 ] -= step * gridSize[1];
1330 trace.origin[ 2 ] += step * gridSize[2];
1332 trace.origin[ 2 ] -= step * gridSize[2];
1334 /* ydnar: changed to find cluster num */
1335 trace.cluster = ClusterForPointExt( trace.origin, VERTEX_EPSILON );
1336 if( trace.cluster >= 0 )
1344 /* can't find a valid point at all */
1350 trace.testOcclusion = !noTrace;
1351 trace.forceSunlight = qfalse;
1352 trace.recvShadows = WORLDSPAWN_RECV_SHADOWS;
1353 trace.numSurfaces = 0;
1354 trace.surfaces = NULL;
1355 trace.numLights = 0;
1356 trace.lights = NULL;
1360 VectorClear( cheapColor );
1362 /* trace to all the lights, find the major light direction, and divide the
1363 total light between that along the direction and the remaining in the ambient */
1364 for( trace.light = lights; trace.light != NULL; trace.light = trace.light->next )
1370 if( !LightContributionToPoint( &trace ) )
1373 /* handle negative light */
1374 if( trace.light->flags & LIGHT_NEGATIVE )
1375 VectorScale( trace.color, -1.0f, trace.color );
1377 /* add a contribution */
1378 VectorCopy( trace.color, contributions[ numCon ].color );
1379 VectorCopy( trace.direction, contributions[ numCon ].dir );
1380 contributions[ numCon ].style = trace.light->style;
1383 /* push average direction around */
1384 addSize = VectorLength( trace.color );
1385 VectorMA( gp->dir, addSize, trace.direction, gp->dir );
1387 /* stop after a while */
1388 if( numCon >= (MAX_CONTRIBUTIONS - 1) )
1391 /* ydnar: cheap mode */
1392 VectorAdd( cheapColor, trace.color, cheapColor );
1393 if( cheapgrid && cheapColor[ 0 ] >= 255.0f && cheapColor[ 1 ] >= 255.0f && cheapColor[ 2 ] >= 255.0f )
1397 /////// Floodlighting for point //////////////////
1398 //do our floodlight ambient occlusion loop, and add a single contribution based on the brightest dir
1404 col[0]=col[1]=col[2]=floodlightIntensity;
1408 trace.testOcclusion = qtrue;
1409 trace.forceSunlight = qfalse;
1410 trace.inhibitRadius = DEFAULT_INHIBIT_RADIUS;
1411 trace.testAll = qtrue;
1415 if (q==0) //upper hemisphere
1421 else //lower hemisphere
1428 f = FloodLightForSample(&trace, floodlightDistance, floodlight_lowquality);
1430 contributions[ numCon ].color[0]=col[0]*f;
1431 contributions[ numCon ].color[1]=col[1]*f;
1432 contributions[ numCon ].color[2]=col[2]*f;
1434 contributions[ numCon ].dir[0]=dir[0];
1435 contributions[ numCon ].dir[1]=dir[1];
1436 contributions[ numCon ].dir[2]=dir[2];
1438 contributions[ numCon ].style = 0;
1440 /* push average direction around */
1441 addSize = VectorLength( col );
1442 VectorMA( gp->dir, addSize, dir, gp->dir );
1445 /////////////////////
1447 /* normalize to get primary light direction */
1448 VectorNormalize( gp->dir, thisdir );
1450 /* now that we have identified the primary light direction,
1451 go back and separate all the light into directed and ambient */
1454 for( i = 0; i < numCon; i++ )
1456 /* get relative directed strength */
1457 d = DotProduct( contributions[ i ].dir, thisdir );
1458 /* we map 1 to gridDirectionality, and 0 to gridAmbientDirectionality */
1459 d = gridAmbientDirectionality + d * (gridDirectionality - gridAmbientDirectionality);
1463 /* find appropriate style */
1464 for( j = 0; j < numStyles; j++ )
1466 if( gp->styles[ j ] == contributions[ i ].style )
1470 /* style not found? */
1471 if( j >= numStyles )
1473 /* add a new style */
1474 if( numStyles < MAX_LIGHTMAPS )
1476 gp->styles[ numStyles ] = contributions[ i ].style;
1477 bgp->styles[ numStyles ] = contributions[ i ].style;
1479 //% Sys_Printf( "(%d, %d) ", num, contributions[ i ].style );
1487 /* add the directed color */
1488 VectorMA( gp->directed[ j ], d, contributions[ i ].color, gp->directed[ j ] );
1490 /* ambient light will be at 1/4 the value of directed light */
1491 /* (ydnar: nuke this in favor of more dramatic lighting?) */
1492 /* (PM: how about actually making it work? d=1 when it got here for single lights/sun :P */
1494 /* (Hobbes: always setting it to .25 is hardly any better) */
1495 d = 0.25f * (1.0f - d);
1496 VectorMA( gp->ambient[ j ], d, contributions[ i ].color, gp->ambient[ j ] );
1500 * the total light average = ambient value + 0.25 * sum of all directional values
1501 * we can also get the total light average as 0.25 * the sum of all contributions
1503 * 0.25 * sum(contribution_i) == ambient + 0.25 * sum(d_i contribution_i)
1506 * ambient == 0.25 * sum((1 - d_i) contribution_i)
1508 * So, 0.25f * (1.0f - d) IS RIGHT. If you want to tune it, tune d BEFORE.
1513 /* store off sample */
1514 for( i = 0; i < MAX_LIGHTMAPS; i++ )
1517 /* do some fudging to keep the ambient from being too low (2003-07-05: 0.25 -> 0.125) */
1519 VectorMA( gp->ambient[ i ], 0.125f, gp->directed[ i ], gp->ambient[ i ] );
1522 /* set minimum light and copy off to bytes */
1523 VectorCopy( gp->ambient[ i ], color );
1524 for( j = 0; j < 3; j++ )
1525 if( color[ j ] < minGridLight[ j ] )
1526 color[ j ] = minGridLight[ j ];
1528 /* vortex: apply gridscale and gridambientscale here */
1529 ColorToBytes( color, bgp->ambient[ i ], gridScale*gridAmbientScale );
1530 ColorToBytes( gp->directed[ i ], bgp->directed[ i ], gridScale );
1535 //% Sys_FPrintf( SYS_VRB, "%10d %10d %10d ", &gp->ambient[ 0 ][ 0 ], &gp->ambient[ 0 ][ 1 ], &gp->ambient[ 0 ][ 2 ] );
1536 Sys_FPrintf( SYS_VRB, "%9d Amb: (%03.1f %03.1f %03.1f) Dir: (%03.1f %03.1f %03.1f)\n",
1538 gp->ambient[ 0 ][ 0 ], gp->ambient[ 0 ][ 1 ], gp->ambient[ 0 ][ 2 ],
1539 gp->directed[ 0 ][ 0 ], gp->directed[ 0 ][ 1 ], gp->directed[ 0 ][ 2 ] );
1542 /* store direction */
1543 NormalToLatLong( thisdir, bgp->latLong );
1550 calculates the size of the lightgrid and allocates memory
1553 void SetupGrid( void )
1556 vec3_t maxs, oldGridSize;
1561 /* don't do this if not grid lighting */
1562 if( noGridLighting )
1565 /* ydnar: set grid size */
1566 value = ValueForKey( &entities[ 0 ], "gridsize" );
1567 if( value[ 0 ] != '\0' )
1568 sscanf( value, "%f %f %f", &gridSize[ 0 ], &gridSize[ 1 ], &gridSize[ 2 ] );
1571 VectorCopy( gridSize, oldGridSize );
1572 for( i = 0; i < 3; i++ )
1573 gridSize[ i ] = gridSize[ i ] >= 8.0f ? floor( gridSize[ i ] ) : 8.0f;
1575 /* ydnar: increase gridSize until grid count is smaller than max allowed */
1576 numRawGridPoints = MAX_MAP_LIGHTGRID + 1;
1578 while( numRawGridPoints > MAX_MAP_LIGHTGRID )
1580 /* get world bounds */
1581 for( i = 0; i < 3; i++ )
1583 gridMins[ i ] = gridSize[ i ] * ceil( bspModels[ 0 ].mins[ i ] / gridSize[ i ] );
1584 maxs[ i ] = gridSize[ i ] * floor( bspModels[ 0 ].maxs[ i ] / gridSize[ i ] );
1585 gridBounds[ i ] = (maxs[ i ] - gridMins[ i ]) / gridSize[ i ] + 1;
1589 numRawGridPoints = gridBounds[ 0 ] * gridBounds[ 1 ] * gridBounds[ 2 ];
1591 /* increase grid size a bit */
1592 if( numRawGridPoints > MAX_MAP_LIGHTGRID )
1593 gridSize[ j++ % 3 ] += 16.0f;
1597 Sys_Printf( "Grid size = { %1.0f, %1.0f, %1.0f }\n", gridSize[ 0 ], gridSize[ 1 ], gridSize[ 2 ] );
1600 if( !VectorCompare( gridSize, oldGridSize ) )
1602 sprintf( temp, "%.0f %.0f %.0f", gridSize[ 0 ], gridSize[ 1 ], gridSize[ 2 ] );
1603 SetKeyValue( &entities[ 0 ], "gridsize", (const char*) temp );
1604 Sys_FPrintf( SYS_VRB, "Storing adjusted grid size\n" );
1607 /* 2nd variable. fixme: is this silly? */
1608 numBSPGridPoints = numRawGridPoints;
1610 /* allocate lightgrid */
1611 rawGridPoints = safe_malloc( numRawGridPoints * sizeof( *rawGridPoints ) );
1612 memset( rawGridPoints, 0, numRawGridPoints * sizeof( *rawGridPoints ) );
1614 if( bspGridPoints != NULL )
1615 free( bspGridPoints );
1616 bspGridPoints = safe_malloc( numBSPGridPoints * sizeof( *bspGridPoints ) );
1617 memset( bspGridPoints, 0, numBSPGridPoints * sizeof( *bspGridPoints ) );
1619 /* clear lightgrid */
1620 for( i = 0; i < numRawGridPoints; i++ )
1622 VectorCopy( ambientColor, rawGridPoints[ i ].ambient[ j ] );
1623 rawGridPoints[ i ].styles[ 0 ] = LS_NORMAL;
1624 bspGridPoints[ i ].styles[ 0 ] = LS_NORMAL;
1625 for( j = 1; j < MAX_LIGHTMAPS; j++ )
1627 rawGridPoints[ i ].styles[ j ] = LS_NONE;
1628 bspGridPoints[ i ].styles[ j ] = LS_NONE;
1633 Sys_Printf( "%9d grid points\n", numRawGridPoints );
1640 does what it says...
1643 void LightWorld( void )
1648 qboolean minVertex, minGrid;
1652 /* ydnar: smooth normals */
1655 Sys_Printf( "--- SmoothNormals ---\n" );
1659 /* determine the number of grid points */
1660 Sys_Printf( "--- SetupGrid ---\n" );
1663 /* find the optional minimum lighting values */
1664 GetVectorForKey( &entities[ 0 ], "_color", color );
1665 if( VectorLength( color ) == 0.0f )
1666 VectorSet( color, 1.0, 1.0, 1.0 );
1669 f = FloatForKey( &entities[ 0 ], "_ambient" );
1671 f = FloatForKey( &entities[ 0 ], "ambient" );
1672 VectorScale( color, f, ambientColor );
1674 /* minvertexlight */
1676 value = ValueForKey( &entities[ 0 ], "_minvertexlight" );
1677 if( value[ 0 ] != '\0' )
1681 VectorScale( color, f, minVertexLight );
1686 value = ValueForKey( &entities[ 0 ], "_mingridlight" );
1687 if( value[ 0 ] != '\0' )
1691 VectorScale( color, f, minGridLight );
1695 value = ValueForKey( &entities[ 0 ], "_minlight" );
1696 if( value[ 0 ] != '\0' )
1699 VectorScale( color, f, minLight );
1700 if( minVertex == qfalse )
1701 VectorScale( color, f, minVertexLight );
1702 if( minGrid == qfalse )
1703 VectorScale( color, f, minGridLight );
1706 /* create world lights */
1707 Sys_FPrintf( SYS_VRB, "--- CreateLights ---\n" );
1708 CreateEntityLights();
1709 CreateSurfaceLights();
1710 Sys_Printf( "%9d point lights\n", numPointLights );
1711 Sys_Printf( "%9d spotlights\n", numSpotLights );
1712 Sys_Printf( "%9d diffuse (area) lights\n", numDiffuseLights );
1713 Sys_Printf( "%9d sun/sky lights\n", numSunLights );
1715 /* calculate lightgrid */
1716 if( !noGridLighting )
1718 /* ydnar: set up light envelopes */
1719 SetupEnvelopes( qtrue, fastgrid );
1721 Sys_Printf( "--- TraceGrid ---\n" );
1722 RunThreadsOnIndividual( numRawGridPoints, qtrue, TraceGrid );
1723 Sys_Printf( "%d x %d x %d = %d grid\n",
1724 gridBounds[ 0 ], gridBounds[ 1 ], gridBounds[ 2 ], numBSPGridPoints );
1726 /* ydnar: emit statistics on light culling */
1727 Sys_FPrintf( SYS_VRB, "%9d grid points envelope culled\n", gridEnvelopeCulled );
1728 Sys_FPrintf( SYS_VRB, "%9d grid points bounds culled\n", gridBoundsCulled );
1731 /* slight optimization to remove a sqrt */
1732 subdivideThreshold *= subdivideThreshold;
1734 /* map the world luxels */
1735 Sys_Printf( "--- MapRawLightmap ---\n" );
1736 RunThreadsOnIndividual( numRawLightmaps, qtrue, MapRawLightmap );
1737 Sys_Printf( "%9d luxels\n", numLuxels );
1738 Sys_Printf( "%9d luxels mapped\n", numLuxelsMapped );
1739 Sys_Printf( "%9d luxels occluded\n", numLuxelsOccluded );
1744 Sys_Printf( "--- DirtyRawLightmap ---\n" );
1749 RunThreadsOnIndividual( numRawLightmaps, qtrue, DirtyRawLightmap );
1752 /* floodlight pass */
1753 FloodlightRawLightmaps();
1755 /* ydnar: set up light envelopes */
1756 SetupEnvelopes( qfalse, fast );
1758 /* light up my world */
1759 lightsPlaneCulled = 0;
1760 lightsEnvelopeCulled = 0;
1761 lightsBoundsCulled = 0;
1762 lightsClusterCulled = 0;
1764 Sys_Printf( "--- IlluminateRawLightmap ---\n" );
1765 RunThreadsOnIndividual( numRawLightmaps, qtrue, IlluminateRawLightmap );
1766 Sys_Printf( "%9d luxels illuminated\n", numLuxelsIlluminated );
1768 StitchSurfaceLightmaps();
1770 Sys_Printf( "--- IlluminateVertexes ---\n" );
1771 RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, IlluminateVertexes );
1772 Sys_Printf( "%9d vertexes illuminated\n", numVertsIlluminated );
1774 /* ydnar: emit statistics on light culling */
1775 Sys_FPrintf( SYS_VRB, "%9d lights plane culled\n", lightsPlaneCulled );
1776 Sys_FPrintf( SYS_VRB, "%9d lights envelope culled\n", lightsEnvelopeCulled );
1777 Sys_FPrintf( SYS_VRB, "%9d lights bounds culled\n", lightsBoundsCulled );
1778 Sys_FPrintf( SYS_VRB, "%9d lights cluster culled\n", lightsClusterCulled );
1785 /* store off the bsp between bounces */
1786 StoreSurfaceLightmaps();
1788 Sys_Printf( "Writing %s\n", source );
1789 WriteBSPFile( source );
1792 Sys_Printf( "\n--- Radiosity (bounce %d of %d) ---\n", b, bt );
1796 VectorClear( ambientColor );
1797 floodlighty = qfalse;
1799 /* generate diffuse lights */
1801 RadCreateDiffuseLights();
1803 /* setup light envelopes */
1804 SetupEnvelopes( qfalse, fastbounce );
1805 if( numLights == 0 )
1807 Sys_Printf( "No diffuse light to calculate, ending radiosity.\n" );
1811 /* add to lightgrid */
1814 gridEnvelopeCulled = 0;
1815 gridBoundsCulled = 0;
1817 Sys_Printf( "--- BounceGrid ---\n" );
1818 RunThreadsOnIndividual( numRawGridPoints, qtrue, TraceGrid );
1819 Sys_FPrintf( SYS_VRB, "%9d grid points envelope culled\n", gridEnvelopeCulled );
1820 Sys_FPrintf( SYS_VRB, "%9d grid points bounds culled\n", gridBoundsCulled );
1823 /* light up my world */
1824 lightsPlaneCulled = 0;
1825 lightsEnvelopeCulled = 0;
1826 lightsBoundsCulled = 0;
1827 lightsClusterCulled = 0;
1829 Sys_Printf( "--- IlluminateRawLightmap ---\n" );
1830 RunThreadsOnIndividual( numRawLightmaps, qtrue, IlluminateRawLightmap );
1831 Sys_Printf( "%9d luxels illuminated\n", numLuxelsIlluminated );
1832 Sys_Printf( "%9d vertexes illuminated\n", numVertsIlluminated );
1834 StitchSurfaceLightmaps();
1836 Sys_Printf( "--- IlluminateVertexes ---\n" );
1837 RunThreadsOnIndividual( numBSPDrawSurfaces, qtrue, IlluminateVertexes );
1838 Sys_Printf( "%9d vertexes illuminated\n", numVertsIlluminated );
1840 /* ydnar: emit statistics on light culling */
1841 Sys_FPrintf( SYS_VRB, "%9d lights plane culled\n", lightsPlaneCulled );
1842 Sys_FPrintf( SYS_VRB, "%9d lights envelope culled\n", lightsEnvelopeCulled );
1843 Sys_FPrintf( SYS_VRB, "%9d lights bounds culled\n", lightsBoundsCulled );
1844 Sys_FPrintf( SYS_VRB, "%9d lights cluster culled\n", lightsClusterCulled );
1856 main routine for light processing
1859 int LightMain( int argc, char **argv )
1863 char mapSource[ 1024 ];
1865 int lightmapMergeSize = 0;
1869 Sys_Printf( "--- Light ---\n" );
1870 Sys_Printf( "--- ProcessGameSpecific ---\n" );
1872 /* set standard game flags */
1873 wolfLight = game->wolfLight;
1874 if (wolfLight == qtrue)
1875 Sys_Printf( " lightning model: wolf\n" );
1877 Sys_Printf( " lightning model: quake3\n" );
1879 lmCustomSize = game->lightmapSize;
1880 Sys_Printf( " lightmap size: %d x %d pixels\n", lmCustomSize, lmCustomSize );
1882 lightmapGamma = game->lightmapGamma;
1883 Sys_Printf( " lightning gamma: %f\n", lightmapGamma );
1885 lightmapCompensate = game->lightmapCompensate;
1886 Sys_Printf( " lightning compensation: %f\n", lightmapCompensate );
1888 lightmapExposure = game->lightmapExposure;
1889 Sys_Printf( " lightning exposure: %f\n", lightmapExposure );
1891 gridScale = game->gridScale;
1892 Sys_Printf( " lightgrid scale: %f\n", gridScale );
1894 gridAmbientScale = game->gridAmbientScale;
1895 Sys_Printf( " lightgrid ambient scale: %f\n", gridAmbientScale );
1897 noStyles = game->noStyles;
1898 if (noStyles == qtrue)
1899 Sys_Printf( " shader lightstyles hack: disabled\n" );
1901 Sys_Printf( " shader lightstyles hack: enabled\n" );
1903 keepLights = game->keepLights;
1904 if (keepLights == qtrue)
1905 Sys_Printf( " keep lights: enabled\n" );
1907 Sys_Printf( " keep lights: disabled\n" );
1909 patchShadows = game->patchShadows;
1910 if (patchShadows == qtrue)
1911 Sys_Printf( " patch shadows: enabled\n" );
1913 Sys_Printf( " patch shadows: disabled\n" );
1915 deluxemap = game->deluxeMap;
1916 deluxemode = game->deluxeMode;
1917 if (deluxemap == qtrue)
1920 Sys_Printf( " deluxemapping: enabled with tangentspace deluxemaps\n" );
1922 Sys_Printf( " deluxemapping: enabled with modelspace deluxemaps\n" );
1925 Sys_Printf( " deluxemapping: disabled\n" );
1927 Sys_Printf( "--- ProcessCommandLine ---\n" );
1929 /* process commandline arguments */
1930 for( i = 1; i < (argc - 1); i++ )
1932 /* lightsource scaling */
1933 if( !strcmp( argv[ i ], "-point" ) || !strcmp( argv[ i ], "-pointscale" ) )
1935 f = atof( argv[ i + 1 ] );
1937 Sys_Printf( "Point (entity) light scaled by %f to %f\n", f, pointScale );
1941 else if( !strcmp( argv[ i ], "-area" ) || !strcmp( argv[ i ], "-areascale" ) )
1943 f = atof( argv[ i + 1 ] );
1945 Sys_Printf( "Area (shader) light scaled by %f to %f\n", f, areaScale );
1949 else if( !strcmp( argv[ i ], "-sky" ) || !strcmp( argv[ i ], "-skyscale" ) )
1951 f = atof( argv[ i + 1 ] );
1953 Sys_Printf( "Sky/sun light scaled by %f to %f\n", f, skyScale );
1957 else if( !strcmp( argv[ i ], "-bouncescale" ) )
1959 f = atof( argv[ i + 1 ] );
1961 Sys_Printf( "Bounce (radiosity) light scaled by %f to %f\n", f, bounceScale );
1965 else if( !strcmp( argv[ i ], "-scale" ) )
1967 f = atof( argv[ i + 1 ] );
1972 Sys_Printf( "All light scaled by %f\n", f );
1976 else if( !strcmp( argv[ i ], "-gridscale" ) )
1978 f = atof( argv[ i + 1 ] );
1979 Sys_Printf( "Grid lightning scaled by %f\n", f );
1984 else if( !strcmp( argv[ i ], "-gridambientscale" ) )
1986 f = atof( argv[ i + 1 ] );
1987 Sys_Printf( "Grid ambient lightning scaled by %f\n", f );
1988 gridAmbientScale *= f;
1992 else if( !strcmp( argv[ i ], "-griddirectionality" ) )
1994 f = atof( argv[ i + 1 ] );
1996 if(f > gridAmbientDirectionality) f = gridAmbientDirectionality;
1997 Sys_Printf( "Grid directionality is %f\n", f );
1998 gridDirectionality *= f;
2002 else if( !strcmp( argv[ i ], "-gridambientdirectionality" ) )
2004 f = atof( argv[ i + 1 ] );
2005 if(f > gridDirectionality) f = gridDirectionality;
2007 Sys_Printf( "Grid ambient directionality is %f\n", f );
2008 gridAmbientDirectionality *= f;
2012 else if( !strcmp( argv[ i ], "-gamma" ) )
2014 f = atof( argv[ i + 1 ] );
2016 Sys_Printf( "Lighting gamma set to %f\n", lightmapGamma );
2020 else if( !strcmp( argv[ i ], "-exposure" ) )
2022 f = atof( argv[ i + 1 ] );
2023 lightmapExposure = f;
2024 Sys_Printf( "Lighting exposure set to %f\n", lightmapExposure );
2028 else if( !strcmp( argv[ i ], "-compensate" ) )
2030 f = atof( argv[ i + 1 ] );
2033 lightmapCompensate = f;
2034 Sys_Printf( "Lighting compensation set to 1/%f\n", lightmapCompensate );
2038 /* ydnar switches */
2039 else if( !strcmp( argv[ i ], "-bounce" ) )
2041 bounce = atoi( argv[ i + 1 ] );
2044 else if( bounce > 0 )
2045 Sys_Printf( "Radiosity enabled with %d bounce(s)\n", bounce );
2049 else if( !strcmp( argv[ i ], "-supersample" ) || !strcmp( argv[ i ], "-super" ) )
2051 superSample = atoi( argv[ i + 1 ] );
2052 if( superSample < 1 )
2054 else if( superSample > 1 )
2055 Sys_Printf( "Ordered-grid supersampling enabled with %d sample(s) per lightmap texel\n", (superSample * superSample) );
2059 else if( !strcmp( argv[ i ], "-samples" ) )
2061 lightSamples = atoi( argv[ i + 1 ] );
2062 if( lightSamples < 1 )
2064 else if( lightSamples > 1 )
2065 Sys_Printf( "Adaptive supersampling enabled with %d sample(s) per lightmap texel\n", lightSamples );
2069 else if( !strcmp( argv[ i ], "-filter" ) )
2072 Sys_Printf( "Lightmap filtering enabled\n" );
2075 else if( !strcmp( argv[ i ], "-dark" ) )
2078 Sys_Printf( "Dark lightmap seams enabled\n" );
2081 else if( !strcmp( argv[ i ], "-shadeangle" ) )
2083 shadeAngleDegrees = atof( argv[ i + 1 ] );
2084 if( shadeAngleDegrees < 0.0f )
2085 shadeAngleDegrees = 0.0f;
2086 else if( shadeAngleDegrees > 0.0f )
2089 Sys_Printf( "Phong shading enabled with a breaking angle of %f degrees\n", shadeAngleDegrees );
2094 else if( !strcmp( argv[ i ], "-thresh" ) )
2096 subdivideThreshold = atof( argv[ i + 1 ] );
2097 if( subdivideThreshold < 0 )
2098 subdivideThreshold = DEFAULT_SUBDIVIDE_THRESHOLD;
2100 Sys_Printf( "Subdivision threshold set at %.3f\n", subdivideThreshold );
2104 else if( !strcmp( argv[ i ], "-approx" ) )
2106 approximateTolerance = atoi( argv[ i + 1 ] );
2107 if( approximateTolerance < 0 )
2108 approximateTolerance = 0;
2109 else if( approximateTolerance > 0 )
2110 Sys_Printf( "Approximating lightmaps within a byte tolerance of %d\n", approximateTolerance );
2113 else if( !strcmp( argv[ i ], "-deluxe" ) || !strcmp( argv[ i ], "-deluxemap" ) )
2116 Sys_Printf( "Generating deluxemaps for average light direction\n" );
2118 else if( !strcmp( argv[ i ], "-deluxemode" ))
2120 deluxemode = atoi( argv[ i + 1 ] );
2121 if (deluxemode == 0 || deluxemode > 1 || deluxemode < 0)
2123 Sys_Printf( "Generating modelspace deluxemaps\n" );
2127 Sys_Printf( "Generating tangentspace deluxemaps\n" );
2130 else if( !strcmp( argv[ i ], "-nodeluxe" ) || !strcmp( argv[ i ], "-nodeluxemap" ) )
2133 Sys_Printf( "Disabling generating of deluxemaps for average light direction\n" );
2135 else if( !strcmp( argv[ i ], "-external" ) )
2137 externalLightmaps = qtrue;
2138 Sys_Printf( "Storing all lightmaps externally\n" );
2141 else if( !strcmp( argv[ i ], "-lightmapsize" ) )
2143 lmCustomSize = atoi( argv[ i + 1 ] );
2145 /* must be a power of 2 and greater than 2 */
2146 if( ((lmCustomSize - 1) & lmCustomSize) || lmCustomSize < 2 )
2148 Sys_Printf( "WARNING: Lightmap size must be a power of 2, greater or equal to 2 pixels.\n" );
2149 lmCustomSize = game->lightmapSize;
2152 Sys_Printf( "Default lightmap size set to %d x %d pixels\n", lmCustomSize, lmCustomSize );
2154 /* enable external lightmaps */
2155 if( lmCustomSize != game->lightmapSize )
2157 externalLightmaps = qtrue;
2158 Sys_Printf( "Storing all lightmaps externally\n" );
2162 else if( !strcmp( argv[ i ], "-rawlightmapsizelimit" ) )
2164 lmLimitSize = atoi( argv[ i + 1 ] );
2167 Sys_Printf( "Raw lightmap size limit set to %d x %d pixels\n", lmLimitSize, lmLimitSize );
2170 else if( !strcmp( argv[ i ], "-lightmapdir" ) )
2172 lmCustomDir = argv[i + 1];
2174 Sys_Printf( "Lightmap directory set to %s\n", lmCustomDir );
2175 externalLightmaps = qtrue;
2176 Sys_Printf( "Storing all lightmaps externally\n" );
2179 /* ydnar: add this to suppress warnings */
2180 else if( !strcmp( argv[ i ], "-custinfoparms") )
2182 Sys_Printf( "Custom info parms enabled\n" );
2183 useCustomInfoParms = qtrue;
2186 else if( !strcmp( argv[ i ], "-wolf" ) )
2188 /* -game should already be set */
2190 Sys_Printf( "Enabling Wolf lighting model (linear default)\n" );
2193 else if( !strcmp( argv[ i ], "-q3" ) )
2195 /* -game should already be set */
2197 Sys_Printf( "Enabling Quake 3 lighting model (nonlinear default)\n" );
2200 else if( !strcmp( argv[ i ], "-sunonly" ) )
2203 Sys_Printf( "Only computing sunlight\n" );
2206 else if( !strcmp( argv[ i ], "-bounceonly" ) )
2209 Sys_Printf( "Storing bounced light (radiosity) only\n" );
2212 else if( !strcmp( argv[ i ], "-nocollapse" ) )
2215 Sys_Printf( "Identical lightmap collapsing disabled\n" );
2218 else if( !strcmp( argv[ i ], "-nolightmapsearch" ) )
2220 lightmapSearchBlockSize = 1;
2221 Sys_Printf( "No lightmap searching - all lightmaps will be sequential\n" );
2224 else if( !strcmp( argv[ i ], "-lightmapsearchpower" ) )
2226 lightmapMergeSize = (game->lightmapSize << atoi(argv[i+1]));
2228 Sys_Printf( "Restricted lightmap searching enabled - optimize for lightmap merge power %d (size %d)\n", atoi(argv[i]), lightmapMergeSize );
2231 else if( !strcmp( argv[ i ], "-lightmapsearchblocksize" ) )
2233 lightmapSearchBlockSize = atoi(argv[i+1]);
2235 Sys_Printf( "Restricted lightmap searching enabled - block size set to %d\n", lightmapSearchBlockSize );
2238 else if( !strcmp( argv[ i ], "-shade" ) )
2241 Sys_Printf( "Phong shading enabled\n" );
2244 else if( !strcmp( argv[ i ], "-bouncegrid") )
2248 Sys_Printf( "Grid lighting with radiosity enabled\n" );
2251 else if( !strcmp( argv[ i ], "-smooth" ) )
2253 lightSamples = EXTRA_SCALE;
2254 Sys_Printf( "The -smooth argument is deprecated, use \"-samples 2\" instead\n" );
2257 else if( !strcmp( argv[ i ], "-fast" ) )
2262 Sys_Printf( "Fast mode enabled\n" );
2265 else if( !strcmp( argv[ i ], "-faster" ) )
2271 Sys_Printf( "Faster mode enabled\n" );
2274 else if( !strcmp( argv[ i ], "-fastgrid" ) )
2277 Sys_Printf( "Fast grid lighting enabled\n" );
2280 else if( !strcmp( argv[ i ], "-fastbounce" ) )
2283 Sys_Printf( "Fast bounce mode enabled\n" );
2286 else if( !strcmp( argv[ i ], "-cheap" ) )
2290 Sys_Printf( "Cheap mode enabled\n" );
2293 else if( !strcmp( argv[ i ], "-cheapgrid" ) )
2296 Sys_Printf( "Cheap grid mode enabled\n" );
2299 else if( !strcmp( argv[ i ], "-normalmap" ) )
2302 Sys_Printf( "Storing normal map instead of lightmap\n" );
2305 else if( !strcmp( argv[ i ], "-trisoup" ) )
2308 Sys_Printf( "Converting brush faces to triangle soup\n" );
2311 else if( !strcmp( argv[ i ], "-debug" ) )
2314 Sys_Printf( "Lightmap debugging enabled\n" );
2317 else if( !strcmp( argv[ i ], "-debugsurfaces" ) || !strcmp( argv[ i ], "-debugsurface" ) )
2319 debugSurfaces = qtrue;
2320 Sys_Printf( "Lightmap surface debugging enabled\n" );
2323 else if( !strcmp( argv[ i ], "-debugunused" ) )
2325 debugUnused = qtrue;
2326 Sys_Printf( "Unused luxel debugging enabled\n" );
2329 else if( !strcmp( argv[ i ], "-debugaxis" ) )
2332 Sys_Printf( "Lightmap axis debugging enabled\n" );
2335 else if( !strcmp( argv[ i ], "-debugcluster" ) )
2337 debugCluster = qtrue;
2338 Sys_Printf( "Luxel cluster debugging enabled\n" );
2341 else if( !strcmp( argv[ i ], "-debugorigin" ) )
2343 debugOrigin = qtrue;
2344 Sys_Printf( "Luxel origin debugging enabled\n" );
2347 else if( !strcmp( argv[ i ], "-debugdeluxe" ) )
2350 debugDeluxemap = qtrue;
2351 Sys_Printf( "Deluxemap debugging enabled\n" );
2354 else if( !strcmp( argv[ i ], "-export" ) )
2356 exportLightmaps = qtrue;
2357 Sys_Printf( "Exporting lightmaps\n" );
2360 else if( !strcmp(argv[ i ], "-notrace" ))
2363 Sys_Printf( "Shadow occlusion disabled\n" );
2365 else if( !strcmp(argv[ i ], "-patchshadows" ) )
2367 patchShadows = qtrue;
2368 Sys_Printf( "Patch shadow casting enabled\n" );
2370 else if( !strcmp( argv[ i ], "-extra" ) )
2372 superSample = EXTRA_SCALE; /* ydnar */
2373 Sys_Printf( "The -extra argument is deprecated, use \"-super 2\" instead\n" );
2375 else if( !strcmp( argv[ i ], "-extrawide" ) )
2377 superSample = EXTRAWIDE_SCALE; /* ydnar */
2378 filter = qtrue; /* ydnar */
2379 Sys_Printf( "The -extrawide argument is deprecated, use \"-filter [-super 2]\" instead\n");
2381 else if( !strcmp( argv[ i ], "-samplesize" ) )
2383 sampleSize = atoi( argv[ i + 1 ] );
2384 if( sampleSize < 1 )
2387 Sys_Printf( "Default lightmap sample size set to %dx%d units\n", sampleSize, sampleSize );
2389 else if( !strcmp( argv[ i ], "-minsamplesize" ) )
2391 minSampleSize = atoi( argv[ i + 1 ] );
2392 if( minSampleSize < 1 )
2395 Sys_Printf( "Minimum lightmap sample size set to %dx%d units\n", minSampleSize, minSampleSize );
2397 else if( !strcmp( argv[ i ], "-samplescale" ) )
2399 sampleScale = atoi( argv[ i + 1 ] );
2401 Sys_Printf( "Lightmaps sample scale set to %d\n", sampleScale);
2403 else if( !strcmp( argv[ i ], "-novertex" ) )
2405 noVertexLighting = qtrue;
2406 Sys_Printf( "Disabling vertex lighting\n" );
2408 else if( !strcmp( argv[ i ], "-nogrid" ) )
2410 noGridLighting = qtrue;
2411 Sys_Printf( "Disabling grid lighting\n" );
2413 else if( !strcmp( argv[ i ], "-border" ) )
2415 lightmapBorder = qtrue;
2416 Sys_Printf( "Adding debug border to lightmaps\n" );
2418 else if( !strcmp( argv[ i ], "-nosurf" ) )
2421 Sys_Printf( "Not tracing against surfaces\n" );
2423 else if( !strcmp( argv[ i ], "-dump" ) )
2426 Sys_Printf( "Dumping radiosity lights into numbered prefabs\n" );
2428 else if( !strcmp( argv[ i ], "-lomem" ) )
2431 Sys_Printf( "Enabling low-memory (potentially slower) lighting mode\n" );
2433 else if( !strcmp( argv[ i ], "-nostyle" ) || !strcmp( argv[ i ], "-nostyles" ) )
2436 Sys_Printf( "Disabling lightstyles\n" );
2438 else if( !strcmp( argv[ i ], "-style" ) || !strcmp( argv[ i ], "-styles" ) )
2441 Sys_Printf( "Enabling lightstyles\n" );
2443 else if( !strcmp( argv[ i ], "-keeplights" ))
2446 Sys_Printf( "Leaving light entities on map after compile\n" );
2448 else if( !strcmp( argv[ i ], "-cpma" ) )
2451 Sys_Printf( "Enabling Challenge Pro Mode Asstacular Vertex Lighting Mode (tm)\n" );
2453 else if( !strcmp( argv[ i ], "-floodlight" ) )
2455 floodlighty = qtrue;
2456 Sys_Printf( "FloodLighting enabled\n" );
2458 else if( !strcmp( argv[ i ], "-debugnormals" ) )
2460 debugnormals = qtrue;
2461 Sys_Printf( "DebugNormals enabled\n" );
2463 else if( !strcmp( argv[ i ], "-lowquality" ) )
2465 floodlight_lowquality = qtrue;
2466 Sys_Printf( "Low Quality FloodLighting enabled\n" );
2469 /* r7: dirtmapping */
2470 else if( !strcmp( argv[ i ], "-dirty" ) )
2473 Sys_Printf( "Dirtmapping enabled\n" );
2475 else if( !strcmp( argv[ i ], "-dirtdebug" ) || !strcmp( argv[ i ], "-debugdirt" ) )
2478 Sys_Printf( "Dirtmap debugging enabled\n" );
2480 else if( !strcmp( argv[ i ], "-dirtmode" ) )
2482 dirtMode = atoi( argv[ i + 1 ] );
2483 if( dirtMode != 0 && dirtMode != 1 )
2486 Sys_Printf( "Enabling randomized dirtmapping\n" );
2488 Sys_Printf( "Enabling ordered dir mapping\n" );
2491 else if( !strcmp( argv[ i ], "-dirtdepth" ) )
2493 dirtDepth = atof( argv[ i + 1 ] );
2494 if( dirtDepth <= 0.0f )
2496 Sys_Printf( "Dirtmapping depth set to %.1f\n", dirtDepth );
2499 else if( !strcmp( argv[ i ], "-dirtscale" ) )
2501 dirtScale = atof( argv[ i + 1 ] );
2502 if( dirtScale <= 0.0f )
2504 Sys_Printf( "Dirtmapping scale set to %.1f\n", dirtScale );
2507 else if( !strcmp( argv[ i ], "-dirtgain" ) )
2509 dirtGain = atof( argv[ i + 1 ] );
2510 if( dirtGain <= 0.0f )
2512 Sys_Printf( "Dirtmapping gain set to %.1f\n", dirtGain );
2515 else if( !strcmp( argv[ i ], "-trianglecheck" ) )
2517 lightmapTriangleCheck = qtrue;
2519 else if( !strcmp( argv[ i ], "-extravisnudge" ) )
2521 lightmapExtraVisClusterNudge = qtrue;
2523 /* unhandled args */
2526 Sys_Printf( "WARNING: Unknown argument \"%s\"\n", argv[ i ] );
2531 /* fix up lightmap search power */
2532 if(lightmapMergeSize)
2534 lightmapSearchBlockSize = (lightmapMergeSize / lmCustomSize) * (lightmapMergeSize / lmCustomSize);
2535 if(lightmapSearchBlockSize < 1)
2536 lightmapSearchBlockSize = 1;
2538 Sys_Printf( "Restricted lightmap searching enabled - block size adjusted to %d\n", lightmapSearchBlockSize );
2541 /* clean up map name */
2542 strcpy( source, ExpandArg( argv[ i ] ) );
2543 StripExtension( source );
2544 DefaultExtension( source, ".bsp" );
2545 strcpy( mapSource, ExpandArg( argv[ i ] ) );
2546 StripExtension( mapSource );
2547 DefaultExtension( mapSource, ".map" );
2549 /* ydnar: set default sample size */
2550 SetDefaultSampleSize( sampleSize );
2552 /* ydnar: handle shaders */
2553 BeginMapShaderFile( source );
2557 Sys_Printf( "Loading %s\n", source );
2559 /* ydnar: load surface file */
2560 LoadSurfaceExtraFile( source );
2563 LoadBSPFile( source );
2565 /* parse bsp entities */
2568 /* inject command line parameters */
2569 InjectCommandLine(argv, 0, argc - 1);
2572 value = ValueForKey( &entities[ 0 ], "_keepLights" );
2573 if( value[ 0 ] != '1' )
2574 LoadMapFile( mapSource, qtrue );
2576 /* set the entity/model origins and init yDrawVerts */
2579 /* ydnar: set up optimization */
2583 SetupSurfaceLightmaps();
2585 /* initialize the surface facet tracing */
2588 /* light the world */
2591 /* ydnar: store off lightmaps */
2592 StoreSurfaceLightmaps();
2594 /* write out the bsp */
2596 Sys_Printf( "Writing %s\n", source );
2597 WriteBSPFile( source );
2599 /* ydnar: export lightmaps */
2600 if( exportLightmaps && !externalLightmaps )
2603 /* return to sender */