forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmatlightmaps.cpp
2191 lines (1863 loc) · 80.3 KB
/
cmatlightmaps.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:
//
//=============================================================================
#include "pch_materialsystem.h"
#define MATSYS_INTERNAL
#include "cmatlightmaps.h"
#include "colorspace.h"
#include "IHardwareConfigInternal.h"
#include "cmaterialsystem.h"
// NOTE: This must be the last file included!!!
#include "tier0/memdbgon.h"
#include "bitmap/float_bm.h"
static ConVar mat_lightmap_pfms( "mat_lightmap_pfms", "0", FCVAR_MATERIAL_SYSTEM_THREAD, "Outputs .pfm files containing lightmap data for each lightmap page when a level exits." ); // Write PFM files for each lightmap page in the game directory when exiting a level
#define USE_32BIT_LIGHTMAPS_ON_360 //uncomment to use 32bit lightmaps, be sure to keep this in sync with the same #define in stdshaders/lightmappedgeneric_ps2_3_x.h
#ifdef _X360
#define X360_USE_SIMD_LIGHTMAP
#endif
//-----------------------------------------------------------------------------
inline IMaterialInternal* CMatLightmaps::GetCurrentMaterialInternal() const
{
return GetMaterialSystem()->GetRenderContextInternal()->GetCurrentMaterialInternal();
}
inline void CMatLightmaps::SetCurrentMaterialInternal(IMaterialInternal* pCurrentMaterial)
{
return GetMaterialSystem()->GetRenderContextInternal()->SetCurrentMaterialInternal( pCurrentMaterial );
}
inline IMaterialInternal *CMatLightmaps::GetMaterialInternal( MaterialHandle_t idx ) const
{
return GetMaterialSystem()->GetMaterialInternal( idx );
}
inline const IMatRenderContextInternal *CMatLightmaps::GetRenderContextInternal() const
{
return GetMaterialSystem()->GetRenderContextInternal();
}
inline IMatRenderContextInternal *CMatLightmaps::GetRenderContextInternal()
{
return GetMaterialSystem()->GetRenderContextInternal();
}
inline const CMaterialDict *CMatLightmaps::GetMaterialDict() const
{
return GetMaterialSystem()->GetMaterialDict();
}
inline CMaterialDict *CMatLightmaps::GetMaterialDict()
{
return GetMaterialSystem()->GetMaterialDict();
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
CMatLightmaps::CMatLightmaps()
{
m_currentWhiteLightmapMaterial = NULL;
m_pLightmapPages = NULL;
m_NumLightmapPages = 0;
m_numSortIDs = 0;
m_nUpdatingLightmapsStackDepth = 0;
m_nLockedLightmap = -1;
m_pLightmapDataPtrArray = NULL;
m_eLightmapsState = STATE_DEFAULT;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CMatLightmaps::Shutdown( )
{
// Clean up all lightmaps
CleanupLightmaps();
}
//-----------------------------------------------------------------------------
// Assign enumeration IDs to all materials
//-----------------------------------------------------------------------------
void CMatLightmaps::EnumerateMaterials( void )
{
// iterate in sorted order
int id = 0;
for (MaterialHandle_t i = GetMaterialDict()->FirstMaterial(); i != GetMaterialDict()->InvalidMaterial(); i = GetMaterialDict()->NextMaterial(i) )
{
GetMaterialInternal(i)->SetEnumerationID( id );
++id;
}
}
//-----------------------------------------------------------------------------
// Gets the maximum lightmap page size...
//-----------------------------------------------------------------------------
int CMatLightmaps::GetMaxLightmapPageWidth() const
{
// FIXME: It's unclear which we want here.
// It doesn't drastically increase primitives per DrawIndexedPrimitive
// call at the moment to increase it, so let's not for now.
// If we're using dynamic textures though, we want bigger that's for sure.
// The tradeoff here is how much memory we waste if we don't fill the lightmap
// We need to go to 512x256 textures because that's the only way bumped
// lighting on displacements can work given the 128x128 allowance..
int nWidth = 512;
if ( nWidth > HardwareConfig()->MaxTextureWidth() )
nWidth = HardwareConfig()->MaxTextureWidth();
return nWidth;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int CMatLightmaps::GetMaxLightmapPageHeight() const
{
int nHeight = 256;
if ( nHeight > HardwareConfig()->MaxTextureHeight() )
nHeight = HardwareConfig()->MaxTextureHeight();
return nHeight;
}
//-----------------------------------------------------------------------------
// Returns the lightmap page size
//-----------------------------------------------------------------------------
void CMatLightmaps::GetLightmapPageSize( int lightmapPageID, int *pWidth, int *pHeight ) const
{
switch( lightmapPageID )
{
default:
Assert( lightmapPageID >= 0 && lightmapPageID < GetNumLightmapPages() );
*pWidth = m_pLightmapPages[lightmapPageID].m_Width;
*pHeight = m_pLightmapPages[lightmapPageID].m_Height;
break;
case MATERIAL_SYSTEM_LIGHTMAP_PAGE_USER_DEFINED:
*pWidth = *pHeight = 1;
AssertOnce( !"Can't use CMatLightmaps to get properties of MATERIAL_SYSTEM_LIGHTMAP_PAGE_USER_DEFINED" );
break;
case MATERIAL_SYSTEM_LIGHTMAP_PAGE_WHITE:
case MATERIAL_SYSTEM_LIGHTMAP_PAGE_WHITE_BUMP:
*pWidth = *pHeight = 1;
break;
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int CMatLightmaps::GetLightmapWidth( int lightmapPageID ) const
{
switch( lightmapPageID )
{
default:
Assert( lightmapPageID >= 0 && lightmapPageID < GetNumLightmapPages() );
return m_pLightmapPages[lightmapPageID].m_Width;
case MATERIAL_SYSTEM_LIGHTMAP_PAGE_USER_DEFINED:
AssertOnce( !"Can't use CMatLightmaps to get properties of MATERIAL_SYSTEM_LIGHTMAP_PAGE_USER_DEFINED" );
return 1;
case MATERIAL_SYSTEM_LIGHTMAP_PAGE_WHITE:
case MATERIAL_SYSTEM_LIGHTMAP_PAGE_WHITE_BUMP:
return 1;
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
int CMatLightmaps::GetLightmapHeight( int lightmapPageID ) const
{
switch( lightmapPageID )
{
default:
Assert( lightmapPageID >= 0 && lightmapPageID < GetNumLightmapPages() );
return m_pLightmapPages[lightmapPageID].m_Height;
case MATERIAL_SYSTEM_LIGHTMAP_PAGE_USER_DEFINED:
AssertOnce( !"Can't use CMatLightmaps to get properties of MATERIAL_SYSTEM_LIGHTMAP_PAGE_USER_DEFINED" );
return 1;
case MATERIAL_SYSTEM_LIGHTMAP_PAGE_WHITE:
case MATERIAL_SYSTEM_LIGHTMAP_PAGE_WHITE_BUMP:
return 1;
}
}
//-----------------------------------------------------------------------------
// Clean up lightmap pages.
//-----------------------------------------------------------------------------
void CMatLightmaps::CleanupLightmaps()
{
if ( mat_lightmap_pfms.GetBool())
{
// Write PFM files containing lightmap data for this page
for (int lightmap = 0; lightmap < GetNumLightmapPages(); lightmap++)
{
if ((NULL != m_pLightmapDataPtrArray) && (NULL != m_pLightmapDataPtrArray[lightmap]))
{
char szPFMFileName[MAX_PATH];
sprintf(szPFMFileName, "Lightmap-Page-%d.pfm", lightmap);
m_pLightmapDataPtrArray[lightmap]->WritePFM(szPFMFileName);
}
}
}
// Remove the lightmap data bitmap representations
if (m_pLightmapDataPtrArray)
{
int i;
for( i = 0; i < GetNumLightmapPages(); i++ )
{
delete m_pLightmapDataPtrArray[i];
}
delete [] m_pLightmapDataPtrArray;
m_pLightmapDataPtrArray = NULL;
}
// delete old lightmap pages
if( m_pLightmapPages )
{
int i;
for( i = 0; i < GetNumLightmapPages(); i++ )
{
g_pShaderAPI->DeleteTexture( m_LightmapPageTextureHandles[i] );
}
delete [] m_pLightmapPages;
m_pLightmapPages = 0;
}
m_NumLightmapPages = 0;
}
//-----------------------------------------------------------------------------
// Resets the lightmap page info for each material
//-----------------------------------------------------------------------------
void CMatLightmaps::ResetMaterialLightmapPageInfo( void )
{
for (MaterialHandle_t i = GetMaterialDict()->FirstMaterial(); i != GetMaterialDict()->InvalidMaterial(); i = GetMaterialDict()->NextMaterial(i) )
{
IMaterialInternal *pMaterial = GetMaterialInternal(i);
pMaterial->SetMinLightmapPageID( 9999 );
pMaterial->SetMaxLightmapPageID( -9999 );
pMaterial->SetNeedsWhiteLightmap( false );
}
}
//-----------------------------------------------------------------------------
// This is called before any lightmap allocations take place
//-----------------------------------------------------------------------------
void CMatLightmaps::BeginLightmapAllocation()
{
// delete old lightmap pages
CleanupLightmaps();
m_ImagePackers.RemoveAll();
int i = m_ImagePackers.AddToTail();
m_ImagePackers[i].Reset( 0, GetMaxLightmapPageWidth(), GetMaxLightmapPageHeight() );
SetCurrentMaterialInternal(0);
m_currentWhiteLightmapMaterial = 0;
m_numSortIDs = 0;
// need to set the min and max sorting id number for each material to
// a default value that basically means that it hasn't been used yet.
ResetMaterialLightmapPageInfo();
EnumerateMaterials();
}
//-----------------------------------------------------------------------------
// Allocates space in the lightmaps; must be called after BeginLightmapAllocation
//-----------------------------------------------------------------------------
int CMatLightmaps::AllocateLightmap( int width, int height,
int offsetIntoLightmapPage[2],
IMaterial *iMaterial )
{
IMaterialInternal *pMaterial = static_cast<IMaterialInternal *>( iMaterial );
if ( !pMaterial )
{
Warning( "Programming error: CMatRenderContext::AllocateLightmap: NULL material\n" );
return m_numSortIDs;
}
pMaterial = pMaterial->GetRealTimeVersion(); //always work with the real time versions of materials internally
// material change
int i;
int nPackCount = m_ImagePackers.Count();
if ( GetCurrentMaterialInternal() != pMaterial )
{
// If this happens, then we need to close out all image packers other than
// the last one so as to produce as few sort IDs as possible
for ( i = nPackCount - 1; --i >= 0; )
{
// NOTE: We *must* use the order preserving one here so the remaining one
// is the last lightmap
m_ImagePackers.Remove( i );
--nPackCount;
}
// If it's not the first material, increment the sort id
if (GetCurrentMaterialInternal())
{
m_ImagePackers[0].IncrementSortId( );
++m_numSortIDs;
}
SetCurrentMaterialInternal(pMaterial);
// This assertion guarantees we don't see the same material twice in this loop.
Assert( pMaterial->GetMinLightmapPageID( ) > pMaterial->GetMaxLightmapPageID() );
// NOTE: We may not use this lightmap page, but we might
// we won't know for sure until the next material is passed in.
// So, for now, we're going to forcibly add the current lightmap
// page to this material so the sort IDs work out correctly.
GetCurrentMaterialInternal()->SetMinLightmapPageID( GetNumLightmapPages() );
GetCurrentMaterialInternal()->SetMaxLightmapPageID( GetNumLightmapPages() );
}
// Try to add it to any of the current images...
bool bAdded = false;
for ( i = 0; i < nPackCount; ++i )
{
bAdded = m_ImagePackers[i].AddBlock( width, height, &offsetIntoLightmapPage[0], &offsetIntoLightmapPage[1] );
if ( bAdded )
break;
}
if ( !bAdded )
{
++m_numSortIDs;
i = m_ImagePackers.AddToTail();
m_ImagePackers[i].Reset( m_numSortIDs, GetMaxLightmapPageWidth(), GetMaxLightmapPageHeight() );
++m_NumLightmapPages;
if ( !m_ImagePackers[i].AddBlock( width, height, &offsetIntoLightmapPage[0], &offsetIntoLightmapPage[1] ) )
{
Error( "MaterialSystem_Interface_t::AllocateLightmap: lightmap (%dx%d) too big to fit in page (%dx%d)\n",
width, height, GetMaxLightmapPageWidth(), GetMaxLightmapPageHeight() );
}
// Add this lightmap to the material...
GetCurrentMaterialInternal()->SetMaxLightmapPageID( GetNumLightmapPages() );
}
return m_ImagePackers[i].GetSortId();
}
// UNDONE: This needs testing, but it appears as though creating these textures managed
// results in huge stalls whenever they are locked for modify.
// That makes sense given the d3d docs, but these have been flagged as managed for quite some time.
#define DYNAMIC_TEXTURES_NO_BACKING 1
void CMatLightmaps::EndLightmapAllocation()
{
// count the last page that we were on.if it wasn't
// and count the last sortID that we were on
m_NumLightmapPages++;
m_numSortIDs++;
m_firstDynamicLightmap = m_NumLightmapPages;
// UNDONE: Until we start using the separate dynamic lighting textures don't allocate them
// NOTE: Enable this if we want to stop locking the base lightmaps and instead only lock update
// these completely dynamic pages
// m_NumLightmapPages += COUNT_DYNAMIC_LIGHTMAP_PAGES;
m_dynamic.Init();
// Compute the dimensions of the last lightmap
int lastLightmapPageWidth, lastLightmapPageHeight;
int nLastIdx = m_ImagePackers.Count();
m_ImagePackers[nLastIdx - 1].GetMinimumDimensions( &lastLightmapPageWidth, &lastLightmapPageHeight );
m_ImagePackers.Purge();
m_pLightmapPages = new LightmapPageInfo_t[GetNumLightmapPages()];
Assert( m_pLightmapPages );
if ( mat_lightmap_pfms.GetBool())
{
// This array will be used to write PFM files full of lightmap data
m_pLightmapDataPtrArray = new FloatBitMap_t*[GetNumLightmapPages()];
}
int i;
m_LightmapPageTextureHandles.EnsureCapacity( GetNumLightmapPages() );
for ( i = 0; i < GetNumLightmapPages(); i++ )
{
// Compute lightmap dimensions
bool lastStaticLightmap = ( i == (m_firstDynamicLightmap-1));
m_pLightmapPages[i].m_Width = (unsigned short)(lastStaticLightmap ? lastLightmapPageWidth : GetMaxLightmapPageWidth());
m_pLightmapPages[i].m_Height = (unsigned short)(lastStaticLightmap ? lastLightmapPageHeight : GetMaxLightmapPageHeight());
m_pLightmapPages[i].m_Flags = 0;
AllocateLightmapTexture( i );
if ( mat_lightmap_pfms.GetBool())
{
// Initialize the pointers to lightmap data
m_pLightmapDataPtrArray[i] = NULL;
}
}
}
//-----------------------------------------------------------------------------
// Allocate lightmap textures
//-----------------------------------------------------------------------------
void CMatLightmaps::AllocateLightmapTexture( int lightmap )
{
bool bUseDynamicTextures = HardwareConfig()->PreferDynamicTextures();
int flags = bUseDynamicTextures ? TEXTURE_CREATE_DYNAMIC : TEXTURE_CREATE_MANAGED;
m_LightmapPageTextureHandles.EnsureCount( lightmap + 1 );
char debugName[256];
Q_snprintf( debugName, sizeof( debugName ), "[lightmap %d]", lightmap );
ImageFormat imageFormat;
switch ( HardwareConfig()->GetHDRType() )
{
default:
Assert( 0 );
// fall through.
case HDR_TYPE_NONE:
#if !defined( _X360 )
imageFormat = IMAGE_FORMAT_RGBA8888;
flags |= TEXTURE_CREATE_SRGB;
#else
imageFormat = IMAGE_FORMAT_LINEAR_RGBA8888;
#endif
break;
case HDR_TYPE_INTEGER:
#if !defined( _X360 )
imageFormat = IMAGE_FORMAT_RGBA16161616;
#else
# if ( defined( USE_32BIT_LIGHTMAPS_ON_360 ) )
imageFormat = IMAGE_FORMAT_LINEAR_RGBA8888;
# else
imageFormat = IMAGE_FORMAT_LINEAR_RGBA16161616;
# endif
#endif
break;
case HDR_TYPE_FLOAT:
imageFormat = IMAGE_FORMAT_RGBA16161616F;
break;
}
switch ( m_eLightmapsState )
{
case STATE_DEFAULT:
// Allow allocations in default state
{
m_LightmapPageTextureHandles[lightmap] = g_pShaderAPI->CreateTexture(
GetLightmapWidth(lightmap), GetLightmapHeight(lightmap), 1,
imageFormat,
1, 1, flags, debugName, TEXTURE_GROUP_LIGHTMAP ); // don't mipmap lightmaps
// Load up the texture data
g_pShaderAPI->ModifyTexture( m_LightmapPageTextureHandles[lightmap] );
g_pShaderAPI->TexMinFilter( SHADER_TEXFILTERMODE_LINEAR );
g_pShaderAPI->TexMagFilter( SHADER_TEXFILTERMODE_LINEAR );
if ( !bUseDynamicTextures )
{
g_pShaderAPI->TexSetPriority( 1 );
}
// Blat out the lightmap bits
InitLightmapBits( lightmap );
}
break;
case STATE_RELEASED:
// Not assigned m_LightmapPageTextureHandles[lightmap];
DevMsg( "AllocateLightmapTexture(%d) in released lightmap state (STATE_RELEASED), delayed till \"Restore\".\n", lightmap );
return;
default:
// Not assigned m_LightmapPageTextureHandles[lightmap];
Warning( "AllocateLightmapTexture(%d) in unknown lightmap state (%d), skipped.\n", lightmap, m_eLightmapsState );
Assert( !"AllocateLightmapTexture(?) in unknown lightmap state (?)" );
return;
}
}
int CMatLightmaps::AllocateWhiteLightmap( IMaterial *iMaterial )
{
IMaterialInternal *pMaterial = static_cast<IMaterialInternal *>( iMaterial );
if( !pMaterial )
{
Warning( "Programming error: CMatRenderContext::AllocateWhiteLightmap: NULL material\n" );
return m_numSortIDs;
}
pMaterial = pMaterial->GetRealTimeVersion(); //always work with the real time versions of materials internally
if ( !m_currentWhiteLightmapMaterial || ( m_currentWhiteLightmapMaterial != pMaterial ) )
{
if ( !GetCurrentMaterialInternal() && !m_currentWhiteLightmapMaterial )
{
// don't increment if this is the very first material (ie. no lightmaps
// allocated with AllocateLightmap
// Assert( 0 );
}
else
{
// material change
m_numSortIDs++;
#if 0
char buf[128];
Q_snprintf( buf, sizeof( buf ), "AllocateWhiteLightmap: m_numSortIDs = %d %s\n", m_numSortIDs, pMaterial->GetName() );
OutputDebugString( buf );
#endif
}
// Warning( "%d material: \"%s\" lightmapPageID: -1\n", m_numSortIDs, pMaterial->GetName() );
m_currentWhiteLightmapMaterial = pMaterial;
pMaterial->SetNeedsWhiteLightmap( true );
}
return m_numSortIDs;
}
//-----------------------------------------------------------------------------
// Releases/restores lightmap pages
//-----------------------------------------------------------------------------
void CMatLightmaps::ReleaseLightmapPages()
{
switch ( m_eLightmapsState )
{
case STATE_DEFAULT:
// Allow release in default state only
break;
default:
Warning( "ReleaseLightmapPages is expected in STATE_DEFAULT, current state = %d, discarded.\n", m_eLightmapsState );
Assert( !"ReleaseLightmapPages is expected in STATE_DEFAULT" );
return;
}
for( int i = 0; i < GetNumLightmapPages(); i++ )
{
g_pShaderAPI->DeleteTexture( m_LightmapPageTextureHandles[i] );
}
// We are now in released state
m_eLightmapsState = STATE_RELEASED;
}
void CMatLightmaps::RestoreLightmapPages()
{
switch ( m_eLightmapsState )
{
case STATE_RELEASED:
// Allow restore in released state only
break;
default:
Warning( "RestoreLightmapPages is expected in STATE_RELEASED, current state = %d, discarded.\n", m_eLightmapsState );
Assert( !"RestoreLightmapPages is expected in STATE_RELEASED" );
return;
}
// Switch to default state to allow allocations
m_eLightmapsState = STATE_DEFAULT;
for( int i = 0; i < GetNumLightmapPages(); i++ )
{
AllocateLightmapTexture( i );
}
}
//-----------------------------------------------------------------------------
// This initializes the lightmap bits
//-----------------------------------------------------------------------------
void CMatLightmaps::InitLightmapBits( int lightmap )
{
VPROF_( "CMatLightmaps::InitLightmapBits", 1, VPROF_BUDGETGROUP_DLIGHT_RENDERING, false, 0 );
int width = GetLightmapWidth(lightmap);
int height = GetLightmapHeight(lightmap);
CPixelWriter writer;
g_pShaderAPI->ModifyTexture( m_LightmapPageTextureHandles[lightmap] );
if ( !g_pShaderAPI->TexLock( 0, 0, 0, 0, width, height, writer ) )
return;
// Debug mode, make em green checkerboard
if ( writer.IsUsingFloatFormat() )
{
for ( int j = 0; j < height; ++j )
{
writer.Seek( 0, j );
for ( int k = 0; k < width; ++k )
{
#ifndef _DEBUG
writer.WritePixel( 1.0f, 1.0f, 1.0f );
#else // _DEBUG
if( ( j + k ) & 1 )
{
writer.WritePixelF( 0.0f, 1.0f, 0.0f );
}
else
{
writer.WritePixelF( 0.0f, 0.0f, 0.0f );
}
#endif // _DEBUG
}
}
}
else
{
for ( int j = 0; j < height; ++j )
{
writer.Seek( 0, j );
for ( int k = 0; k < width; ++k )
{
#ifndef _DEBUG
// note: make this white to find multisample centroid sampling problems.
// writer.WritePixel( 255, 255, 255 );
writer.WritePixel( 0, 0, 0 );
#else // _DEBUG
if ( ( j + k ) & 1 )
{
writer.WritePixel( 0, 255, 0 );
}
else
{
writer.WritePixel( 0, 0, 0 );
}
#endif // _DEBUG
}
}
}
g_pShaderAPI->TexUnlock();
}
bool CMatLightmaps::LockLightmap( int lightmap )
{
// Warning( "locking lightmap page: %d\n", lightmap );
VPROF_INCREMENT_COUNTER( "lightmap fullpage texlock", 1 );
if( m_nLockedLightmap != -1 )
{
g_pShaderAPI->TexUnlock();
}
g_pShaderAPI->ModifyTexture( m_LightmapPageTextureHandles[lightmap] );
int pageWidth = m_pLightmapPages[lightmap].m_Width;
int pageHeight = m_pLightmapPages[lightmap].m_Height;
if (!g_pShaderAPI->TexLock( 0, 0, 0, 0, pageWidth, pageHeight, m_LightmapPixelWriter ))
{
Assert( 0 );
return false;
}
m_nLockedLightmap = lightmap;
return true;
}
Vector4D ConvertLightmapColorToRGBScale( const float *lightmapColor )
{
Vector4D result;
float fScale = lightmapColor[0];
for( int i = 1; i != 3; ++i )
{
if( lightmapColor[i] > fScale )
fScale = lightmapColor[i];
}
fScale = ceil( fScale * (255.0f/16.0f) ) * (16.0f/255.0f);
fScale = min( fScale, 16.0f );
float fInvScale = 1.0f / fScale;
for( int i = 0; i != 3; ++i )
{
result[i] = lightmapColor[i] * fInvScale;
result[i] = ceil( result[i] * 255.0f ) * (1.0f/255.0f);
result[i] = min( result[i], 1.0f );
}
fScale /= 16.0f;
result.w = fScale;
return result;
}
#ifdef _X360
// SIMD version of above
// input numbers from pSrc are on the domain [0..16]
// output is RGBA
// ignores contents of w channel of input
// the shader does this: rOut = Rin * Ain * 16.0f
// where Rin is [0..1], a float computed from a byte value [0..255]
// Ain is therefore the brightest channel (say R) divided by 16 and quantized
// Rin is computed from pSrc->r by dividing by Ain
// this outputs RGBa where RGB are [0..255] and a is the shader's scaling factor (also 0..255)
//
// WARNING - this code appears to be vulnerable to a compiler bug. Be very careful modifying and be
// sure to test
fltx4 ConvertLightmapColorToRGBScale( FLTX4 lightmapColor )
{
static const fltx4 vTwoFiftyFive = {255.0f, 255.0f, 255.0f, 255.0f};
static const fltx4 FourPoint1s = { 0.1, 0.1, 0.1, 0.1 };
static const fltx4 vTwoFiftyFiveOverSixteen = {255.0f / 16.0f, 255.0f / 16.0f, 255.0f / 16.0f, 255.0f / 16.0f};
// static const fltx4 vSixteenOverTwoFiftyFive = { 16.0f / 255.0f, 16.0f / 255.0f, 16.0f / 255.0f, 16.0f / 255.0f };
// find the highest color value in lightmapColor and replicate it
fltx4 scale = FindHighestSIMD3( lightmapColor );
fltx4 minscale = FindLowestSIMD3( lightmapColor );
fltx4 fl4OutofRange = OrSIMD( CmpGeSIMD( scale, Four_Ones ), CmpLeSIMD( scale, FourPoint1s ) );
fl4OutofRange = OrSIMD( fl4OutofRange, CmpGtSIMD( minscale, MulSIMD( Four_PointFives, scale ) ) );
// scale needs to be divided by 16 (because the shader multiplies it by 16)
// then mapped to 0..255 and quantized.
scale = __vrfip(MulSIMD(scale, vTwoFiftyFiveOverSixteen)); // scale = ceil(scale * 255/16)
fltx4 result = MulSIMD(vTwoFiftyFive, lightmapColor); // start the scale cooking on the final result
fltx4 invScale = ReciprocalEstSIMD(scale); // invScale = (16/255)(1/scale). may be +inf
invScale = MulSIMD(invScale, vTwoFiftyFiveOverSixteen); // take the quantizing factor back out
// of the inverse scale (one less
// dependent op if you do it this way)
// scale the input channels
// compute so the numbers are all 0..255 ints. (if one happens to
// be 256 due to numerical error in the reciprocation, the unsigned-saturate
// store we'll use later on will bake it back down to 255)
result = MulSIMD(result, invScale);
// now, output --
// if the input color was nonzero, slip the scale into return value's w
// component and return. If the input was zero, return zero.
result = MaskedAssign(
fl4OutofRange,
SetWSIMD( result, scale ),
SetWSIMD( MulSIMD( lightmapColor, vTwoFiftyFive ), vTwoFiftyFiveOverSixteen ) );
return result;
}
#endif
// write bumped lightmap update to LDR 8-bit lightmap
void CMatLightmaps::BumpedLightmapBitsToPixelWriter_LDR( float* pFloatImage, float *pFloatImageBump1, float *pFloatImageBump2,
float *pFloatImageBump3, int pLightmapSize[2], int pOffsetIntoLightmapPage[2], FloatBitMap_t *pfmOut )
{
const int nLightmapSize0 = pLightmapSize[0];
const int nLightmap0WriterSizeBytes = nLightmapSize0 * m_LightmapPixelWriter.GetPixelSize();
const int nRewindToNextPixel = -( ( nLightmap0WriterSizeBytes * 3 ) - m_LightmapPixelWriter.GetPixelSize() );
for( int t = 0; t < pLightmapSize[1]; t++ )
{
int srcTexelOffset = ( sizeof( Vector4D ) / sizeof( float ) ) * ( 0 + t * nLightmapSize0 );
m_LightmapPixelWriter.Seek( pOffsetIntoLightmapPage[0], pOffsetIntoLightmapPage[1] + t );
for( int s = 0; s < nLightmapSize0;
s++, m_LightmapPixelWriter.SkipBytes(nRewindToNextPixel),srcTexelOffset += (sizeof(Vector4D)/sizeof(float)))
{
unsigned char color[4][3];
ColorSpace::LinearToBumpedLightmap( &pFloatImage[srcTexelOffset],
&pFloatImageBump1[srcTexelOffset], &pFloatImageBump2[srcTexelOffset],
&pFloatImageBump3[srcTexelOffset],
color[0], color[1], color[2], color[3] );
unsigned char alpha = RoundFloatToByte( pFloatImage[srcTexelOffset+3] * 255.0f );
m_LightmapPixelWriter.WritePixelNoAdvance( color[0][0], color[0][1], color[0][2], alpha );
m_LightmapPixelWriter.SkipBytes( nLightmap0WriterSizeBytes );
m_LightmapPixelWriter.WritePixelNoAdvance( color[1][0], color[1][1], color[1][2], alpha );
m_LightmapPixelWriter.SkipBytes( nLightmap0WriterSizeBytes );
m_LightmapPixelWriter.WritePixelNoAdvance( color[2][0], color[2][1], color[2][2], alpha );
m_LightmapPixelWriter.SkipBytes( nLightmap0WriterSizeBytes );
m_LightmapPixelWriter.WritePixelNoAdvance( color[3][0], color[3][1], color[3][2], alpha );
}
}
if ( pfmOut )
{
for( int t = 0; t < pLightmapSize[1]; t++ )
{
int srcTexelOffset = ( sizeof( Vector4D ) / sizeof( float ) ) * ( 0 + t * nLightmapSize0 );
for( int s = 0; s < nLightmapSize0; s++,srcTexelOffset += (sizeof(Vector4D)/sizeof(float)))
{
unsigned char color[4][3];
ColorSpace::LinearToBumpedLightmap( &pFloatImage[srcTexelOffset],
&pFloatImageBump1[srcTexelOffset], &pFloatImageBump2[srcTexelOffset],
&pFloatImageBump3[srcTexelOffset],
color[0], color[1], color[2], color[3] );
unsigned char alpha = RoundFloatToByte( pFloatImage[srcTexelOffset+3] * 255.0f );
// Write data to the bitmapped represenations so that PFM files can be written
PixRGBAF pixelData;
pixelData.Red = color[0][0];
pixelData.Green = color[0][1];
pixelData.Blue = color[0][2];
pixelData.Alpha = alpha;
pfmOut->WritePixelRGBAF( pOffsetIntoLightmapPage[0] + s, pOffsetIntoLightmapPage[1] + t, pixelData);
}
}
}
}
// write bumped lightmap update to HDR float lightmap
void CMatLightmaps::BumpedLightmapBitsToPixelWriter_HDRF( float* pFloatImage, float *pFloatImageBump1, float *pFloatImageBump2,
float *pFloatImageBump3, int pLightmapSize[2], int pOffsetIntoLightmapPage[2], FloatBitMap_t *pfmOut )
{
if ( IsX360() )
{
// 360 does not support HDR float mode
Assert( 0 );
return;
}
Assert( !pfmOut ); // unsupported in this mode
const int nLightmapSize0 = pLightmapSize[0];
const int nLightmap0WriterSizeBytes = nLightmapSize0 * m_LightmapPixelWriter.GetPixelSize();
const int nRewindToNextPixel = -( ( nLightmap0WriterSizeBytes * 3 ) - m_LightmapPixelWriter.GetPixelSize() );
for( int t = 0; t < pLightmapSize[1]; t++ )
{
int srcTexelOffset = ( sizeof( Vector4D ) / sizeof( float ) ) * ( 0 + t * nLightmapSize0 );
m_LightmapPixelWriter.Seek( pOffsetIntoLightmapPage[0], pOffsetIntoLightmapPage[1] + t );
for( int s = 0;
s < nLightmapSize0;
s++, m_LightmapPixelWriter.SkipBytes(nRewindToNextPixel),srcTexelOffset += (sizeof(Vector4D)/sizeof(float)))
{
m_LightmapPixelWriter.WritePixelNoAdvanceF( pFloatImage[srcTexelOffset], pFloatImage[srcTexelOffset+1],
pFloatImage[srcTexelOffset+2], pFloatImage[srcTexelOffset+3] );
m_LightmapPixelWriter.SkipBytes( nLightmap0WriterSizeBytes );
m_LightmapPixelWriter.WritePixelNoAdvanceF( pFloatImageBump1[srcTexelOffset], pFloatImageBump1[srcTexelOffset+1],
pFloatImageBump1[srcTexelOffset+2], pFloatImage[srcTexelOffset+3] );
m_LightmapPixelWriter.SkipBytes( nLightmap0WriterSizeBytes );
m_LightmapPixelWriter.WritePixelNoAdvanceF( pFloatImageBump2[srcTexelOffset], pFloatImageBump2[srcTexelOffset+1],
pFloatImageBump2[srcTexelOffset+2], pFloatImage[srcTexelOffset+3] );
m_LightmapPixelWriter.SkipBytes( nLightmap0WriterSizeBytes );
m_LightmapPixelWriter.WritePixelNoAdvanceF( pFloatImageBump3[srcTexelOffset], pFloatImageBump3[srcTexelOffset+1],
pFloatImageBump3[srcTexelOffset+2], pFloatImage[srcTexelOffset+3] );
}
}
}
#ifdef _X360
#pragma optimize("u", on)
#endif
#ifdef _X360
namespace {
// pack a pixel into BGRA8888 and return it with the data packed into the w component
FORCEINLINE fltx4 PackPixel_BGRA8888( FLTX4 rgba )
{
// this happens to be in an order such that we can use the handy builtin packing op
// clamp to 0..255 (coz it might have leaked over)
static const fltx4 vTwoFiftyFive = {255.0f, 255.0f, 255.0f, 255.0f};
// the magic number such that when mul-accummulated against rbga,
// gets us a representation 3.0 + (r)*2^-22 -- puts the bits at
// the bottom of the float
static const XMVECTOR PackScale = { (1.0f / (FLOAT)(1 << 22)), (1.0f / (FLOAT)(1 << 22)), (1.0f / (FLOAT)(1 << 22)), (1.0f / (FLOAT)(1 << 22))}; // 255.0f / (FLOAT)(1 << 22)
static const XMVECTOR Three = {3.0f, 3.0f, 3.0f, 3.0f};
fltx4 N = MinSIMD(vTwoFiftyFive, rgba);
N = __vmaddfp(N, PackScale, Three);
N = __vpkd3d(N, N, VPACK_D3DCOLOR, VPACK_32, 0); // pack into w word
return N;
}
// A small store-gather buffer used in the
// BumpedLightmapBitsToPixelWriter_HDRI_BGRA_X360().
// The store-gather buffers. Hopefully these will live in the L1
// cache, which will make writing to them, then to memory, faster
// than just using __stvewx to write directly into WC memory
// one noncontiguous float at a time. (If there weren't a huge
// compiler bug with __stvewx in the Apr07 XDK, that might not
// be the case.)
struct ALIGN128 CPixelWriterStoreGather
{
enum {
kRows = 4,
kWordsPerRow = 32,
};
ALIGN128 uint32 m_data[kRows][kWordsPerRow]; // four rows of bgra data, aligned to 4 cache lines. dwords so memcpy works better.
int m_wordsGathered;
int m_bytesBetweenWriterRows; // the number of bytes spacing the maps inside the writer from each other
// if we weren't gathering, we'd SkipBytes this many between the base map, bump1, etc.
// write four rows, as SIMD registers, into the buffers
inline void write( CPixelWriter * RESTRICT pLightmapPixelWriter, FLTX4 row0, FLTX4 row1, FLTX4 row2, FLTX4 row3 ) RESTRICT
{
// if full, commit
Assert(m_wordsGathered <= kWordsPerRow);
AssertMsg((m_wordsGathered & 3) == 0, "Don't call CPixelWriterStoreGather::write after ::writeJustX"); // single-word writes have misaligned me
if (m_wordsGathered >= kWordsPerRow)
{
commitWhenFull(pLightmapPixelWriter);
}
XMStoreVector4A( &m_data[0][m_wordsGathered], row0 );
XMStoreVector4A( &m_data[1][m_wordsGathered], row1 );
XMStoreVector4A( &m_data[2][m_wordsGathered], row2 );
XMStoreVector4A( &m_data[3][m_wordsGathered], row3 );
m_wordsGathered += 4 ; // four words per simd vec
}
// pluck the w component out of each of the rows, and store it into the gather buffer. Don't
// call the other write function after calling this.
inline void writeJustW( CPixelWriter * RESTRICT pLightmapPixelWriter, FLTX4 row0, FLTX4 row1, FLTX4 row2, FLTX4 row3 ) RESTRICT
{
// if full, commit
Assert(m_wordsGathered <= kWordsPerRow);
if (m_wordsGathered >= kWordsPerRow)
{
commitWhenFull(pLightmapPixelWriter);
}
// for each fltx4, splat out x and then use the __stvewx to store
// whichever word happens to align with the float pointer through
// that pointer.
__stvewx(__vspltw(row0, 3), &m_data[0][m_wordsGathered], 0 );
__stvewx(__vspltw(row1, 3), &m_data[1][m_wordsGathered], 0 );
__stvewx(__vspltw(row2, 3), &m_data[2][m_wordsGathered], 0 );
__stvewx(__vspltw(row3, 3), &m_data[3][m_wordsGathered], 0 );
m_wordsGathered += 1 ; // only stored one word
}
// Commit my buffers to the pixelwriter's memory, and advance its
// pointer.
void commit(CPixelWriter * RESTRICT pLightmapPixelWriter) RESTRICT
{
if (m_wordsGathered > 0)
{
unsigned char* RESTRICT pWriteInto = pLightmapPixelWriter->GetCurrentPixel();
// we have to use memcpy because we're writing to non-cacheable memory,
// but we can't even assume that the addresses we're writing to are
// vector-aligned.
#ifdef memcpy // if someone's overriden the intrinsic, complain
#pragma error("You have overridden memcpy(), which is an XBOX360 intrinsic. This function will not behave optimally.")
#endif
memcpy(pWriteInto, m_data[0], m_wordsGathered * sizeof(uint32));
pWriteInto += m_bytesBetweenWriterRows;
memcpy(pWriteInto, m_data[1], m_wordsGathered * sizeof(uint32));
pWriteInto += m_bytesBetweenWriterRows;
memcpy(pWriteInto, m_data[2], m_wordsGathered * sizeof(uint32));
pWriteInto += m_bytesBetweenWriterRows;
memcpy(pWriteInto, m_data[3], m_wordsGathered * sizeof(uint32));
pLightmapPixelWriter->SkipBytes(m_wordsGathered * sizeof(uint32));
m_wordsGathered = 0;
}
}
// like commit, but the version we use when we know we're full.
// Takes advantage of better compile-time generation for
// memcpy.