forked from hitmen047/Source-PlusPlus
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathvrad.cpp
2894 lines (2451 loc) · 70.7 KB
/
vrad.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// vrad.c
#include "vrad.h"
#include "physdll.h"
#include "lightmap.h"
#include "tier1/strtools.h"
#include "vmpi.h"
#include "macro_texture.h"
#include "vmpi_tools_shared.h"
#include "leaf_ambient_lighting.h"
#include "tools_minidump.h"
#include "loadcmdline.h"
#include "byteswap.h"
#define ALLOWDEBUGOPTIONS (0 || _DEBUG)
static FileHandle_t pFpTrans = NULL;
/*
NOTES
-----
every surface must be divided into at least two patches each axis
*/
CUtlVector<CPatch> g_Patches;
CUtlVector<int> g_FacePatches; // contains all patches, children first
CUtlVector<int> faceParents; // contains only root patches, use next parent to iterate
CUtlVector<int> clusterChildren;
CUtlVector<Vector> emitlight;
CUtlVector<bumplights_t> addlight;
int num_sky_cameras;
sky_camera_t sky_cameras[MAX_MAP_AREAS];
int area_sky_cameras[MAX_MAP_AREAS];
entity_t *face_entity[MAX_MAP_FACES];
Vector face_offset[MAX_MAP_FACES]; // for rotating bmodels
int fakeplanes;
unsigned numbounce = 100; // 25; /* Originally this was 8 */
float maxchop = 4; // coarsest allowed number of luxel widths for a patch
float minchop = 4; // "-chop" tightest number of luxel widths for a patch, used on edges
float dispchop = 8.0f; // number of luxel widths for a patch
float g_MaxDispPatchRadius = 1500.0f; // Maximum radius allowed for displacement patches
qboolean g_bDumpPatches;
bool bDumpNormals = false;
bool g_bDumpRtEnv = false;
bool bRed2Black = true;
bool g_bFastAmbient = false;
bool g_bNoSkyRecurse = false;
bool g_bDumpPropLightmaps = false;
int junk;
Vector ambient( 0, 0, 0 );
float lightscale = 1.0;
float dlight_threshold = 0.1; // was DIRECT_LIGHT constant
char source[MAX_PATH] = "";
char level_name[MAX_PATH] = ""; // map filename, without extension or path info
char global_lights[MAX_PATH] = "";
char designer_lights[MAX_PATH] = "";
char level_lights[MAX_PATH] = "";
char vismatfile[_MAX_PATH] = "";
char incrementfile[_MAX_PATH] = "";
IIncremental *g_pIncremental = 0;
bool g_bInterrupt = false; // Wsed with background lighting in WC. Tells VRAD
// to stop lighting.
float g_SunAngularExtent=0.0;
float g_flSkySampleScale = 1.0;
bool g_bLargeDispSampleRadius = false;
bool g_bOnlyStaticProps = false;
bool g_bShowStaticPropNormals = false;
float gamma_value = 0.5;
float indirect_sun = 1.0;
float reflectivityScale = 1.0;
qboolean do_extra = true;
bool debug_extra = false;
qboolean do_fast = false;
qboolean do_centersamples = false;
int extrapasses = 4;
float smoothing_threshold = 0.7071067; // cos(45.0*(M_PI/180))
// Cosine of smoothing angle(in radians)
float coring = 1.0; // Light threshold to force to blackness(minimizes lightmaps)
qboolean texscale = true;
int dlight_map = 0; // Setting to 1 forces direct lighting into different lightmap than radiosity
float luxeldensity = 1.0;
unsigned num_degenerate_faces;
qboolean g_bLowPriority = false;
qboolean g_bLogHashData = false;
bool g_bNoDetailLighting = false;
double g_flStartTime;
bool g_bStaticPropLighting = false;
bool g_bStaticPropPolys = false;
bool g_bAllowDX90VTX = false;
bool g_bIgnoreModelVersions = false;
bool g_bTextureShadows = false;
bool g_bAllowDynamicPropsAsStatic = false;
bool g_bDisablePropSelfShadowing = false;
CUtlVector<byte> g_FacesVisibleToLights;
RayTracingEnvironment g_RtEnv;
dface_t *g_pFaces=0;
// this is a list of material names used on static props which shouldn't cast shadows. a
// sequential search is used since we allow substring matches. its not time critical, and this
// functionality is a stopgap until vrad starts reading .vmt files.
CUtlVector<char const *> g_NonShadowCastingMaterialStrings;
/*
===================================================================
MISC
===================================================================
*/
int leafparents[MAX_MAP_LEAFS];
int nodeparents[MAX_MAP_NODES];
void MakeParents (int nodenum, int parent)
{
int i, j;
dnode_t *node;
nodeparents[nodenum] = parent;
node = &dnodes[nodenum];
for (i=0 ; i<2 ; i++)
{
j = node->children[i];
if (j < 0)
leafparents[-j - 1] = nodenum;
else
MakeParents (j, nodenum);
}
}
/*
===================================================================
TEXTURE LIGHT VALUES
===================================================================
*/
typedef struct
{
char name[256];
Vector value;
char *filename;
} texlight_t;
#define MAX_TEXLIGHTS 128
texlight_t texlights[MAX_TEXLIGHTS];
int num_texlights;
/*
============
ReadLightFile
============
*/
void ReadLightFile (char *filename)
{
char buf[1024];
int file_texlights = 0;
FileHandle_t f = g_pFileSystem->Open( filename, "r" );
if (!f)
{
Warning("Warning: Couldn't open texlight file %s.\n", filename);
return;
}
Msg("[Reading texlights from '%s']\n", filename);
while ( CmdLib_FGets( buf, sizeof( buf ), f ) )
{
// check ldr/hdr
char * scan = buf;
if ( !strnicmp( "hdr:", scan, 4) )
{
scan += 4;
if ( ! g_bHDR )
{
continue;
}
}
if ( !strnicmp( "ldr:", scan, 4) )
{
scan += 4;
if ( g_bHDR )
{
continue;
}
}
scan += strspn( scan, " \t" );
char NoShadName[1024];
if ( sscanf(scan,"noshadow %s",NoShadName)==1)
{
char * dot = strchr( NoShadName, '.' );
if ( dot ) // if they specify .vmt, kill it
* dot = 0;
//printf("add %s as a non shadow casting material\n",NoShadName);
g_NonShadowCastingMaterialStrings.AddToTail( strdup( NoShadName ));
}
else if ( sscanf( scan, "forcetextureshadow %s", NoShadName ) == 1 )
{
//printf("add %s as a non shadow casting material\n",NoShadName);
ForceTextureShadowsOnModel( NoShadName );
}
else
{
char szTexlight[256];
Vector value;
if ( num_texlights == MAX_TEXLIGHTS )
Error ("Too many texlights, max = %d", MAX_TEXLIGHTS);
int argCnt = sscanf (scan, "%s ",szTexlight );
if( argCnt != 1 )
{
if ( strlen( scan ) > 4 )
Msg( "ignoring bad texlight '%s' in %s", scan, filename );
continue;
}
LightForString( scan + strlen( szTexlight ) + 1, value );
int j = 0;
for( j; j < num_texlights; j ++ )
{
if ( strcmp( texlights[j].name, szTexlight ) == 0 )
{
if ( strcmp( texlights[j].filename, filename ) == 0 )
{
Msg( "ERROR\a: Duplication of '%s' in file '%s'!\n",
texlights[j].name, texlights[j].filename );
}
else if ( texlights[j].value[0] != value[0]
|| texlights[j].value[1] != value[1]
|| texlights[j].value[2] != value[2] )
{
Warning( "Warning: Overriding '%s' from '%s' with '%s'!\n",
texlights[j].name, texlights[j].filename, filename );
}
else
{
Warning( "Warning: Redundant '%s' def in '%s' AND '%s'!\n",
texlights[j].name, texlights[j].filename, filename );
}
break;
}
}
strcpy( texlights[j].name, szTexlight );
VectorCopy( value, texlights[j].value );
texlights[j].filename = filename;
file_texlights ++;
num_texlights = max( num_texlights, j + 1 );
}
}
Msg( "[%i texlights parsed from '%s']\n\n", file_texlights, filename);
g_pFileSystem->Close( f );
}
/*
============
LightForTexture
============
*/
void LightForTexture( const char *name, Vector& result )
{
result[ 0 ] = result[ 1 ] = result[ 2 ] = 0;
char baseFilename[ MAX_PATH ];
if ( Q_strncmp( "maps/", name, 5 ) == 0 )
{
// this might be a patch texture for cubemaps. try to parse out the original filename.
if ( Q_strncmp( level_name, name + 5, Q_strlen( level_name ) ) == 0 )
{
const char *base = name + 5 + Q_strlen( level_name );
if ( *base == '/' )
{
++base; // step past the path separator
// now we've gotten rid of the 'maps/level_name/' part, so we're left with
// 'originalName_%d_%d_%d'.
strcpy( baseFilename, base );
bool foundSeparators = true;
for ( int i=0; i<3; ++i )
{
char *underscore = Q_strrchr( baseFilename, '_' );
if ( underscore && *underscore )
{
*underscore = '\0';
}
else
{
foundSeparators = false;
}
}
if ( foundSeparators )
{
name = baseFilename;
}
}
}
}
for (int i=0 ; i<num_texlights ; i++)
{
if (!Q_strcasecmp (name, texlights[i].name))
{
VectorCopy( texlights[i].value, result );
return;
}
}
}
/*
=======================================================================
MAKE FACES
=======================================================================
*/
/*
=============
WindingFromFace
=============
*/
winding_t *WindingFromFace (dface_t *f, Vector& origin )
{
int i;
int se;
dvertex_t *dv;
int v;
winding_t *w;
w = AllocWinding (f->numedges);
w->numpoints = f->numedges;
for (i=0 ; i<f->numedges ; i++)
{
se = dsurfedges[f->firstedge + i];
if (se < 0)
v = dedges[-se].v[1];
else
v = dedges[se].v[0];
dv = &dvertexes[v];
VectorAdd (dv->point, origin, w->p[i]);
}
RemoveColinearPoints (w);
return w;
}
/*
=============
BaseLightForFace
=============
*/
void BaseLightForFace( dface_t *f, Vector& light, float *parea, Vector& reflectivity )
{
texinfo_t *tx;
dtexdata_t *texdata;
//
// check for light emited by texture
//
tx = &texinfo[f->texinfo];
texdata = &dtexdata[tx->texdata];
LightForTexture (TexDataStringTable_GetString( texdata->nameStringTableID ), light);
*parea = texdata->height * texdata->width;
VectorScale( texdata->reflectivity, reflectivityScale, reflectivity );
// always keep this less than 1 or the solution will not converge
for ( int i = 0; i < 3; i++ )
{
if ( reflectivity[i] > 0.99 )
reflectivity[i] = 0.99;
}
}
qboolean IsSky (dface_t *f)
{
texinfo_t *tx;
tx = &texinfo[f->texinfo];
if (tx->flags & SURF_SKY)
return true;
return false;
}
#ifdef STATIC_FOG
/*=============
IsFog
=============*/
qboolean IsFog( dface_t *f )
{
texinfo_t *tx;
tx = &texinfo[f->texinfo];
// % denotes a fog texture
if( tx->texture[0] == '%' )
return true;
return false;
}
#endif
void ProcessSkyCameras()
{
int i;
num_sky_cameras = 0;
for (i = 0; i < numareas; ++i)
{
area_sky_cameras[i] = -1;
}
for (i = 0; i < num_entities; ++i)
{
entity_t *e = &entities[i];
const char *name = ValueForKey (e, "classname");
if (stricmp (name, "sky_camera"))
continue;
Vector origin;
GetVectorForKey( e, "origin", origin );
int node = PointLeafnum( origin );
int area = -1;
if (node >= 0 && node < numleafs) area = dleafs[node].area;
float scale = FloatForKey( e, "scale" );
if (scale > 0.0f)
{
sky_cameras[num_sky_cameras].origin = origin;
sky_cameras[num_sky_cameras].sky_to_world = scale;
sky_cameras[num_sky_cameras].world_to_sky = 1.0f / scale;
sky_cameras[num_sky_cameras].area = area;
if (area >= 0 && area < numareas)
{
area_sky_cameras[area] = num_sky_cameras;
}
++num_sky_cameras;
}
}
}
/*
=============
MakePatchForFace
=============
*/
float totalarea;
void MakePatchForFace (int fn, winding_t *w)
{
dface_t *f = g_pFaces + fn;
float area;
CPatch *patch;
int i, j;
texinfo_t *tx;
// get texture info
tx = &texinfo[f->texinfo];
// No patches at all for fog!
#ifdef STATIC_FOG
if ( IsFog( f ) )
return;
#endif
// the sky needs patches or the form factors don't work out correctly
// if (IsSky( f ) )
// return;
area = WindingArea (w);
if (area <= 0)
{
num_degenerate_faces++;
// Msg("degenerate face\n");
return;
}
totalarea += area;
// get a patch
int ndxPatch = g_Patches.AddToTail();
patch = &g_Patches[ndxPatch];
memset( patch, 0, sizeof( CPatch ) );
patch->ndxNext = g_Patches.InvalidIndex();
patch->ndxNextParent = g_Patches.InvalidIndex();
patch->ndxNextClusterChild = g_Patches.InvalidIndex();
patch->child1 = g_Patches.InvalidIndex();
patch->child2 = g_Patches.InvalidIndex();
patch->parent = g_Patches.InvalidIndex();
patch->needsBumpmap = tx->flags & SURF_BUMPLIGHT ? true : false;
// link and save patch data
patch->ndxNext = g_FacePatches.Element( fn );
g_FacePatches[fn] = ndxPatch;
// patch->next = face_g_Patches[fn];
// face_g_Patches[fn] = patch;
// compute a separate scale for chop - since the patch "scale" is the texture scale
// we want textures with higher resolution lighting to be chopped up more
float chopscale[2];
chopscale[0] = chopscale[1] = 16.0f;
if ( texscale )
{
// Compute the texture "scale" in s,t
for( i=0; i<2; i++ )
{
patch->scale[i] = 0.0f;
chopscale[i] = 0.0f;
for( j=0; j<3; j++ )
{
patch->scale[i] +=
tx->textureVecsTexelsPerWorldUnits[i][j] *
tx->textureVecsTexelsPerWorldUnits[i][j];
chopscale[i] +=
tx->lightmapVecsLuxelsPerWorldUnits[i][j] *
tx->lightmapVecsLuxelsPerWorldUnits[i][j];
}
patch->scale[i] = sqrt( patch->scale[i] );
chopscale[i] = sqrt( chopscale[i] );
}
}
else
{
patch->scale[0] = patch->scale[1] = 1.0f;
}
patch->area = area;
patch->sky = IsSky( f );
// chop scaled up lightmaps coarser
patch->luxscale = ((chopscale[0]+chopscale[1])/2);
patch->chop = maxchop;
#ifdef STATIC_FOG
patch->fog = FALSE;
#endif
patch->winding = w;
patch->plane = &dplanes[f->planenum];
// make a new plane to adjust for origined bmodels
if (face_offset[fn][0] || face_offset[fn][1] || face_offset[fn][2] )
{
dplane_t *pl;
// origin offset faces must create new planes
if (numplanes + fakeplanes >= MAX_MAP_PLANES)
{
Error ("numplanes + fakeplanes >= MAX_MAP_PLANES");
}
pl = &dplanes[numplanes + fakeplanes];
fakeplanes++;
*pl = *(patch->plane);
pl->dist += DotProduct (face_offset[fn], pl->normal);
patch->plane = pl;
}
patch->faceNumber = fn;
WindingCenter (w, patch->origin);
// Save "center" for generating the face normals later.
VectorSubtract( patch->origin, face_offset[fn], face_centroids[fn] );
VectorCopy( patch->plane->normal, patch->normal );
WindingBounds (w, patch->face_mins, patch->face_maxs);
VectorCopy( patch->face_mins, patch->mins );
VectorCopy( patch->face_maxs, patch->maxs );
BaseLightForFace( f, patch->baselight, &patch->basearea, patch->reflectivity );
// Chop all texlights very fine.
if ( !VectorCompare( patch->baselight, vec3_origin ) )
{
// patch->chop = do_extra ? maxchop / 2 : maxchop;
tx->flags |= SURF_LIGHT;
}
// get rid of do extra functionality on displacement surfaces
if( ValidDispFace( f ) )
{
patch->chop = maxchop;
}
// FIXME: If we wanted to add a dependency from vrad to the material system,
// we could do this. It would add a bunch of file accesses, though:
/*
// Check for a material var which would override the patch chop
bool bFound;
const char *pMaterialName = TexDataStringTable_GetString( dtexdata[ tx->texdata ].nameStringTableID );
MaterialSystemMaterial_t hMaterial = FindMaterial( pMaterialName, &bFound, false );
if ( bFound )
{
const char *pChopValue = GetMaterialVar( hMaterial, "%chop" );
if ( pChopValue )
{
float flChopValue;
if ( sscanf( pChopValue, "%f", &flChopValue ) > 0 )
{
patch->chop = flChopValue;
}
}
}
*/
}
entity_t *EntityForModel (int modnum)
{
int i;
char *s;
char name[16];
sprintf (name, "*%i", modnum);
// search the entities for one using modnum
for (i=0 ; i<num_entities ; i++)
{
s = ValueForKey (&entities[i], "model");
if (!strcmp (s, name))
return &entities[i];
}
return &entities[0];
}
/*
=============
MakePatches
=============
*/
void MakePatches (void)
{
int i, j;
dface_t *f;
int fn;
winding_t *w;
dmodel_t *mod;
Vector origin;
entity_t *ent;
ParseEntities ();
Msg("%i faces\n", numfaces);
for (i=0 ; i<nummodels ; i++)
{
mod = dmodels+i;
ent = EntityForModel (i);
VectorCopy (vec3_origin, origin);
// bmodels with origin brushes need to be offset into their
// in-use position
GetVectorForKey (ent, "origin", origin);
for (j=0 ; j<mod->numfaces ; j++)
{
fn = mod->firstface + j;
face_entity[fn] = ent;
VectorCopy (origin, face_offset[fn]);
f = &g_pFaces[fn];
if( f->dispinfo == -1 )
{
w = WindingFromFace (f, origin );
MakePatchForFace( fn, w );
}
}
}
if (num_degenerate_faces > 0)
{
Msg("%d degenerate faces\n", num_degenerate_faces );
}
Msg( "%.2f square feet [%.2f square inches]\n", totalarea / 144, totalarea );
// make the displacement surface patches
StaticDispMgr()->MakePatches();
}
/*
=======================================================================
SUBDIVIDE
=======================================================================
*/
//-----------------------------------------------------------------------------
// Purpose: does this surface take/emit light
//-----------------------------------------------------------------------------
bool PreventSubdivision( CPatch *patch )
{
dface_t *f = g_pFaces + patch->faceNumber;
texinfo_t *tx = &texinfo[f->texinfo];
if (tx->flags & SURF_NOCHOP)
return true;
if (tx->flags & SURF_NOLIGHT && !(tx->flags & SURF_LIGHT))
return true;
return false;
}
//-----------------------------------------------------------------------------
// Purpose: subdivide the "parent" patch
//-----------------------------------------------------------------------------
int CreateChildPatch( int nParentIndex, winding_t *pWinding, float flArea, const Vector &vecCenter )
{
int nChildIndex = g_Patches.AddToTail();
CPatch *child = &g_Patches[nChildIndex];
CPatch *parent = &g_Patches[nParentIndex];
// copy all elements of parent patch to children
*child = *parent;
// Set up links
child->ndxNext = g_Patches.InvalidIndex();
child->ndxNextParent = g_Patches.InvalidIndex();
child->ndxNextClusterChild = g_Patches.InvalidIndex();
child->child1 = g_Patches.InvalidIndex();
child->child2 = g_Patches.InvalidIndex();
child->parent = nParentIndex;
child->m_IterationKey = 0;
child->winding = pWinding;
child->area = flArea;
VectorCopy( vecCenter, child->origin );
if ( ValidDispFace( g_pFaces + child->faceNumber ) )
{
// shouldn't get here anymore!!
Msg( "SubdividePatch: Error - Should not be here!\n" );
StaticDispMgr()->GetDispSurfNormal( child->faceNumber, child->origin, child->normal, true );
}
else
{
GetPhongNormal( child->faceNumber, child->origin, child->normal );
}
child->planeDist = child->plane->dist;
WindingBounds(child->winding, child->mins, child->maxs);
if ( !VectorCompare( child->baselight, vec3_origin ) )
{
// don't check edges on surf lights
return nChildIndex;
}
// Subdivide patch towards minchop if on the edge of the face
Vector total;
VectorSubtract( child->maxs, child->mins, total );
VectorScale( total, child->luxscale, total );
if ( child->chop > minchop && (total[0] < child->chop) && (total[1] < child->chop) && (total[2] < child->chop) )
{
for ( int i=0; i<3; ++i )
{
if ( (child->face_maxs[i] == child->maxs[i] || child->face_mins[i] == child->mins[i] )
&& total[i] > minchop )
{
child->chop = max( minchop, child->chop / 2 );
break;
}
}
}
return nChildIndex;
}
//-----------------------------------------------------------------------------
// Purpose: subdivide the "parent" patch
//-----------------------------------------------------------------------------
void SubdividePatch( int ndxPatch )
{
winding_t *w, *o1, *o2;
Vector total;
Vector split;
vec_t dist;
vec_t widest = -1;
int i, widest_axis = -1;
bool bSubdivide = false;
// get the current patch
CPatch *patch = &g_Patches.Element( ndxPatch );
if ( !patch )
return;
// never subdivide sky patches
if ( patch->sky )
return;
// get the patch winding
w = patch->winding;
// subdivide along the widest axis
VectorSubtract (patch->maxs, patch->mins, total);
VectorScale( total, patch->luxscale, total );
for (i=0 ; i<3 ; i++)
{
if ( total[i] > widest )
{
widest_axis = i;
widest = total[i];
}
if ( (total[i] >= patch->chop) && (total[i] >= minchop) )
{
bSubdivide = true;
}
}
if ((!bSubdivide) && widest_axis != -1)
{
// make more square
if (total[widest_axis] > total[(widest_axis + 1) % 3] * 2 && total[widest_axis] > total[(widest_axis + 2) % 3] * 2)
{
if (patch->chop > minchop)
{
bSubdivide = true;
patch->chop = max( minchop, patch->chop / 2 );
}
}
}
if ( !bSubdivide )
return;
// split the winding
VectorCopy (vec3_origin, split);
split[widest_axis] = 1;
dist = (patch->mins[widest_axis] + patch->maxs[widest_axis])*0.5f;
ClipWindingEpsilon (w, split, dist, ON_EPSILON, &o1, &o2);
// calculate the area of the patches to see if they are "significant"
Vector center1, center2;
float area1 = WindingAreaAndBalancePoint( o1, center1 );
float area2 = WindingAreaAndBalancePoint( o2, center2 );
if( area1 == 0 || area2 == 0 )
{
Msg( "zero area child patch\n" );
return;
}
// create new child patches
int ndxChild1Patch = CreateChildPatch( ndxPatch, o1, area1, center1 );
int ndxChild2Patch = CreateChildPatch( ndxPatch, o2, area2, center2 );
// FIXME: This could go into CreateChildPatch if child1, child2 were stored in the patch as child[0], child[1]
patch = &g_Patches.Element( ndxPatch );
patch->child1 = ndxChild1Patch;
patch->child2 = ndxChild2Patch;
SubdividePatch( ndxChild1Patch );
SubdividePatch( ndxChild2Patch );
}
/*
=============
SubdividePatches
=============
*/
void SubdividePatches (void)
{
unsigned i, num;
if (numbounce == 0)
return;
unsigned int uiPatchCount = g_Patches.Size();
Msg( "%i patches before subdivision\n", uiPatchCount );
for (i = 0; i < uiPatchCount; i++)
{
CPatch *pCur = &g_Patches.Element( i );
pCur->planeDist = pCur->plane->dist;
pCur->ndxNextParent = faceParents.Element( pCur->faceNumber );
faceParents[pCur->faceNumber] = pCur - g_Patches.Base();
}
for (i=0 ; i< uiPatchCount; i++)
{
CPatch *patch = &g_Patches.Element( i );
patch->parent = -1;
if ( PreventSubdivision(patch) )
continue;
if (!do_fast)
{
if( g_pFaces[patch->faceNumber].dispinfo == -1 )
{
SubdividePatch( i );
}
else
{
StaticDispMgr()->SubdividePatch( i );
}
}
}
// fixup next pointers
for (i = 0; i < (unsigned)numfaces; i++)
{
g_FacePatches[i] = g_FacePatches.InvalidIndex();
}
uiPatchCount = g_Patches.Size();
for (i = 0; i < uiPatchCount; i++)
{
CPatch *pCur = &g_Patches.Element( i );
pCur->ndxNext = g_FacePatches.Element( pCur->faceNumber );
g_FacePatches[pCur->faceNumber] = pCur - g_Patches.Base();
#if 0
CPatch *prev;
prev = face_g_Patches[g_Patches[i].faceNumber];
g_Patches[i].next = prev;
face_g_Patches[g_Patches[i].faceNumber] = &g_Patches[i];
#endif
}
// Cache off the leaf number:
// We have to do this after subdivision because some patches span leaves.
// (only the faces for model #0 are split by it's BSP which is what governs the PVS, and the leaves we're interested in)
// Sub models (1-255) are only split for the BSP that their model forms.
// When those patches are subdivided their origins can end up in a different leaf.
// The engine will split (clip) those faces at run time to the world BSP because the models
// are dynamic and can be moved. In the software renderer, they must be split exactly in order
// to sort per polygon.
for ( i = 0; i < uiPatchCount; i++ )
{
g_Patches[i].clusterNumber = ClusterFromPoint( g_Patches[i].origin );
//
// test for point in solid space (can happen with detail and displacement surfaces)
//