forked from ericwa/ericw-tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlight.cc
1755 lines (1461 loc) · 62.5 KB
/
light.cc
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 (C) 1996-1997 Id Software, Inc.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
See file, 'COPYING', for details.
*/
#include <light/light.hh>
#include <cstdint>
#include <iostream>
#include <fmt/chrono.h>
#include <light/lightgrid.hh>
#include <light/phong.hh>
#include <light/bounce.hh>
#include <light/surflight.hh> //mxd
#include <light/entities.hh>
#include <light/ltface.hh>
#include <light/litfile.hh> // for facesup_t
#include <light/trace_embree.hh>
#include <common/log.hh>
#include <common/bsputils.hh>
#include <common/numeric_cast.hh>
#include <common/fs.hh>
#include <common/imglib.hh>
#include <common/parallel.hh>
#include <common/ostream.hh>
#if defined(HAVE_EMBREE) && defined(__SSE2__)
#include <xmmintrin.h>
// #include <pmmintrin.h>
#endif
#include <memory>
#include <vector>
#include <map>
#include <set>
#include <algorithm>
#include <mutex>
#include <string>
#include <common/qvec.hh>
#include <common/json.hh>
bool dirt_in_use = false;
// intermediate representation of lightmap surfaces
static std::vector<std::unique_ptr<lightsurf_t>> light_surfaces;
// light_surfaces filtered down to just the emissive ones
static std::vector<lightsurf_t*> emissive_light_surfaces;
std::vector<std::unique_ptr<lightsurf_t>> &LightSurfaces()
{
return light_surfaces;
}
std::vector<lightsurf_t*> &EmissiveLightSurfaces()
{
return emissive_light_surfaces;
}
static void UpdateEmissiveLightSurfacesList()
{
emissive_light_surfaces.clear();
for (const auto &surf_ptr : light_surfaces) {
if (!surf_ptr || !surf_ptr->vpl) {
// didn't emit anthing
continue;
}
emissive_light_surfaces.push_back(surf_ptr.get());
}
}
static std::vector<facesup_t> faces_sup; // lit2/bspx stuff
static std::vector<bspx_decoupled_lm_perface> facesup_decoupled_global;
bool IsOutputtingSupplementaryData()
{
return !faces_sup.empty();
}
/// start of lightmap data
std::vector<uint8_t> filebase;
/// offset of start of free space after data (should be kept a multiple of 4)
static int file_p;
/// offset of end of free space for lightmap data
static int file_end;
/// start of litfile data
std::vector<uint8_t> lit_filebase;
/// offset of start of free space after litfile data (should be kept a multiple of 12)
static int lit_file_p;
/// offset of end of space for litfile data
static int lit_file_end;
/// start of litfile data
std::vector<uint32_t> hdr_filebase;
/// offset of start of free space after litfile data (should be kept a multiple of 12)
static int hdr_file_p;
/// offset of end of space for litfile data
static int hdr_file_end;
/// start of luxfile data
std::vector<uint8_t> lux_filebase;
/// offset of start of free space after luxfile data (should be kept a multiple of 12)
static int lux_file_p;
/// offset of end of space for luxfile data
static int lux_file_end;
static std::unordered_map<int, std::vector<uint8_t>> all_uncompressed_vis;
const std::unordered_map<int, std::vector<uint8_t>> &UncompressedVis()
{
return all_uncompressed_vis;
}
std::vector<modelinfo_t *> modelinfo;
std::vector<const modelinfo_t *> tracelist;
std::vector<const modelinfo_t *> selfshadowlist;
std::vector<const modelinfo_t *> shadowworldonlylist;
std::vector<const modelinfo_t *> switchableshadowlist;
std::vector<surfflags_t> extended_texinfo_flags;
int dump_facenum = -1;
int dump_vertnum = -1;
// modelinfo_t
float modelinfo_t::getResolvedPhongAngle() const
{
const float s = phong_angle.value();
if (s != 0) {
return s;
}
if (phong.value() > 0) {
return DEFAULT_PHONG_ANGLE;
}
return 0;
}
bool modelinfo_t::isWorld() const
{
return &bsp->dmodels[0] == model;
}
modelinfo_t::modelinfo_t(const mbsp_t *b, const dmodelh2_t *m, float lmscale)
: bsp{b},
model{m},
lightmapscale{lmscale},
offset{},
minlight{this, "minlight", 0},
maxlight{this, "maxlight", 0},
minlightMottle{this, {"minlight_mottle", "minlightMottle"}, false},
shadow{this, "shadow", 0},
shadowself{this, {"shadowself", "selfshadow"}, 0},
shadowworldonly{this, "shadowworldonly", 0},
switchableshadow{this, "switchableshadow", 0},
switchshadstyle{this, "switchshadstyle", 0},
dirt{this, "dirt", 0},
phong{this, "phong", 0},
phong_angle{this, "phong_angle", 0},
alpha{this, "alpha", 1.0},
minlight_color{this, {"minlight_color", "mincolor"}, 255.0, 255.0, 255.0},
lightignore{this, "lightignore", false},
lightcolorscale{this, "lightcolorscale", 1},
object_channel_mask{this, "object_channel_mask", CHANNEL_MASK_DEFAULT},
surflight_minlight_scale{this, "surflight_minlight_scale", 1.f},
autominlight{this, "autominlight", false},
autominlight_target{this, "autominlight_target", ""}
{
}
namespace settings
{
// worldspawn_keys
worldspawn_keys::worldspawn_keys()
: scaledist{this, "dist", 1.0, 0.0, 100.0, &worldspawn_group},
rangescale{this, "range", 0.5, 0.0, 100.0, &worldspawn_group},
global_anglescale{this, {"anglescale", "anglesense"}, 0.5, 0.0, 1.0, &worldspawn_group},
lightmapgamma{this, "gamma", 1.0, 0.0, 100.0, &worldspawn_group},
addminlight{this, "addmin", false, &worldspawn_group},
minlight{this, {"light", "minlight"}, 0, &worldspawn_group},
minlightMottle{this, {"minlight_mottle", "minlightMottle"}, false, &worldspawn_group},
maxlight{this, "maxlight", 0, &worldspawn_group},
minlight_color{this, {"minlight_color", "mincolor"}, 255.0, 255.0, 255.0, &worldspawn_group},
spotlightautofalloff{this, "spotlightautofalloff", false, &worldspawn_group},
compilerstyle_start{this, "compilerstyle_start", 32, &worldspawn_group},
compilerstyle_max{this, "compilerstyle_max", 64, &worldspawn_group},
dirt{this, {"dirt", "dirty"}, false, &worldspawn_group,
"apply dirt to all lights (unless they override it) + sunlight + minlight"},
dirtmode{this, "dirtmode", 0.0f, &worldspawn_group},
dirtdepth{this, "dirtdepth", 128.0, 1.0, std::numeric_limits<vec_t>::infinity(), &worldspawn_group},
dirtscale{this, "dirtscale", 1.0, 0.0, 100.0, &worldspawn_group},
dirtgain{this, "dirtgain", 1.0, 0.0, 100.0, &worldspawn_group},
dirtangle{this, "dirtangle", 88.0, 1.0, 90.0, &worldspawn_group},
minlight_dirt{this, "minlight_dirt", false, &worldspawn_group},
phongallowed{this, "phong", true, &worldspawn_group},
phongangle{this, "phong_angle", 0, &worldspawn_group},
bounce{this, "bounce", 0, &worldspawn_group},
bouncestyled{this, "bouncestyled", false, &worldspawn_group},
bouncescale{this, "bouncescale", 1.0, 0.0, 100.0, &worldspawn_group},
bouncecolorscale{this, "bouncecolorscale", 0.0, 0.0, 1.0, &worldspawn_group},
bouncelightsubdivision{this, "bouncelightsubdivision", 64.0, 1.0, 8192.0, &worldspawn_group},
surflightscale{this, "surflightscale", 1.0, &worldspawn_group},
surflightskyscale{this, "surflightskyscale", 1.0, &worldspawn_group},
surflightskydist{this, "surflightskydist", 0.0, &worldspawn_group},
surflightsubdivision{this, {"surflightsubdivision", "choplight"}, 16.0, 1.0, 8192.0, &worldspawn_group},
surflight_minlight_scale{this, "surflight_minlight_scale", 1.0f, 0.f, 510.f, &worldspawn_group},
sunlight{this, {"sunlight", "sun_light"}, 0.0, &worldspawn_group},
sunlight_color{this, {"sunlight_color", "sun_color"}, 255.0, 255.0, 255.0, &worldspawn_group},
sun2{this, "sun2", 0.0, &worldspawn_group},
sun2_color{this, "sun2_color", 255.0, 255.0, 255.0, &worldspawn_group},
sunlight2{this, "sunlight2", 0.0, &worldspawn_group},
sunlight2_color{this, {"sunlight2_color", "sunlight_color2"}, 255.0, 255.0, 255.0, &worldspawn_group},
sunlight3{this, "sunlight3", 0.0, &worldspawn_group},
sunlight3_color{this, {"sunlight3_color", "sunlight_color3"}, 255.0, 255.0, 255.0, &worldspawn_group},
sunlight_dirt{this, "sunlight_dirt", 0.0, &worldspawn_group},
sunlight2_dirt{this, "sunlight2_dirt", 0.0, &worldspawn_group},
// NOTE: the default mangle needs to be in direction vector form, not euler angle
sunvec{this, {"sunlight_mangle", "sun_mangle", "sun_angle"}, 0.0, 0.0, -1.0, &worldspawn_group},
sun2vec{this, "sun2_mangle", 0.0, 0.0, -1.0, &worldspawn_group},
sun_deviance{this, "sunlight_penumbra", 0.0, 0.0, 180.0, &worldspawn_group},
sky_surface{this, {"sky_surface", "sun_surface"}, 0, 0, 0, &worldspawn_group},
surflight_radiosity{this, "surflight_radiosity", SURFLIGHT_Q1, &worldspawn_group,
"whether to use Q1-style surface subdivision (0) or Q2-style surface radiosity"}
{
}
// light_settings::setting_soft
bool light_settings::setting_soft::parse(const std::string &setting_name, parser_base_t &parser, source source)
{
if (!parser.parse_token(PARSE_PEEK)) {
return false;
}
try {
int32_t f = static_cast<int32_t>(std::stoull(parser.token));
set_value(f, source);
parser.parse_token();
return true;
} catch (std::exception &) {
// if we didn't provide a (valid) number, then
// assume it's meant to be the default of -1
set_value(-1, source);
return true;
}
}
std::string light_settings::setting_soft::format() const
{
return "[n]";
}
// light_settings::setting_extra
bool light_settings::setting_extra::parse(const std::string &setting_name, parser_base_t &parser, source source)
{
if (setting_name.back() == '4') {
set_value(4, source);
} else {
set_value(2, source);
}
return true;
}
std::string light_settings::setting_extra::string_value() const
{
return std::to_string(_value);
};
std::string light_settings::setting_extra::format() const
{
return "";
};
void light_settings::CheckNoDebugModeSet()
{
if (debugmode != debugmodes::none) {
Error("Only one debug mode is allowed at a time");
}
}
setting_group worldspawn_group{"Overridable worldspawn keys", 500, expected_source::worldspawn};
setting_group output_group{"Output format options", 30, expected_source::commandline};
setting_group debug_group{"Debug modes", 40, expected_source::commandline};
setting_group postprocessing_group{"Postprocessing options", 50, expected_source::commandline};
setting_group experimental_group{"Experimental options", 60, expected_source::commandline};
light_settings::light_settings()
: surflight_dump{this, "surflight_dump", false, &debug_group, "dump surface lights to a .map file"},
surflight_subdivide{
this, "surflight_subdivide", 128.0, 1.0, 2048.0, &performance_group, "surface light subdivision size"},
onlyents{this, "onlyents", false, &output_group, "only update entities"},
write_normals{this, "wrnormals", false, &output_group, "output normals, tangents and bitangents in a BSPX lump"},
novanilla{this, "novanilla", false, &experimental_group, "implies -bspxlit; don't write vanilla lighting"},
gate{this, "gate", LIGHT_EQUAL_EPSILON, &performance_group, "cutoff lights at this brightness level"},
sunsamples{this, "sunsamples", 64, 8, 2048, &performance_group, "set samples for _sunlight2, default 64"},
arghradcompat{this, "arghradcompat", false, &output_group, "enable compatibility for Arghrad-specific keys"},
nolighting{this, "nolighting", false, &output_group, "don't output main world lighting (Q2RTX)"},
debugface{this, "debugface", std::numeric_limits<vec_t>::quiet_NaN(), std::numeric_limits<vec_t>::quiet_NaN(),
std::numeric_limits<vec_t>::quiet_NaN(), &debug_group, ""},
debugvert{this, "debugvert", std::numeric_limits<vec_t>::quiet_NaN(), std::numeric_limits<vec_t>::quiet_NaN(),
std::numeric_limits<vec_t>::quiet_NaN(), &debug_group, ""},
highlightseams{this, "highlightseams", false, &debug_group, ""},
soft{this, "soft", 0, -1, std::numeric_limits<int32_t>::max(), &postprocessing_group,
"blurs the lightmap. specify n to blur radius in samples, otherwise auto"},
radlights{this, "radlights", "\"filename.rad\"", &experimental_group,
"loads a <surfacename> <r> <g> <b> <intensity> file"},
lightmap_scale{
this, "lightmap_scale", 0, &experimental_group, "force change lightmap scale; vanilla engines only allow 16"},
extra{
this, {"extra", "extra4"}, 1, &performance_group, "supersampling; 2x2 (extra) or 4x4 (extra4) respectively"},
emissivequality{this, "emissivequality", emissivequality_t::LOW,
{{"LOW", emissivequality_t::LOW}, {"MEDIUM", emissivequality_t::MEDIUM}, {"HIGH", emissivequality_t::HIGH}},
&performance_group,
"low = one point in the center of the face, med = center + all verts, high = spread points out for antialiasing"},
visapprox{this, "visapprox", visapprox_t::AUTO,
{{"auto", visapprox_t::AUTO}, {"none", visapprox_t::NONE}, {"vis", visapprox_t::VIS},
{"rays", visapprox_t::RAYS}},
&debug_group,
"change approximate visibility algorithm. auto = choose default based on format. vis = use BSP vis data (slow but precise). rays = use sphere culling with fired rays (fast but may miss faces)"},
lit{this, "lit", [&](source) { write_litfile |= lightfile::external; }, &output_group, "write .lit file"},
lit2{this, "lit2", [&](source) { write_litfile = lightfile::lit2; }, &experimental_group, "write .lit2 file"},
bspxlit{this, "bspxlit", [&](source) { write_litfile |= lightfile::bspx; }, &experimental_group,
"writes rgb data into the bsp itself"},
hdr{this, "hdr", [&](source) { write_litfile |= lightfile::external; write_litfile |= lightfile::hdr; }, &experimental_group, "write .lit file as e5bgr9"},
bspxhdr{this, "bspxhdr", [&](source) { write_litfile |= lightfile::bspx; write_litfile |= lightfile::hdr; }, &experimental_group,
"writes rgb data into the bsp itself as e5bgr9"},
lux{this, "lux", [&](source) { write_luxfile |= lightfile::external; }, &experimental_group, "write .lux file"},
bspxlux{this, "bspxlux", [&](source) { write_luxfile |= lightfile::bspx; }, &experimental_group,
"writes lux data into the bsp itself"},
bspxonly{this, "bspxonly",
[&](source source) {
write_litfile = lightfile::bspx;
write_luxfile = lightfile::bspx;
novanilla.set_value(true, source);
},
&experimental_group, "writes both rgb and directions data *only* into the bsp itself"},
bspx{this, "bspx",
[&](source source) {
write_litfile = lightfile::bspx;
write_luxfile = lightfile::bspx;
},
&experimental_group, "writes both rgb and directions data into the bsp itself"},
world_units_per_luxel{
this, "world_units_per_luxel", 0, 0, 1024, &output_group, "enables output of DECOUPLED_LM BSPX lump"},
litonly{this, "litonly", false, &output_group, "only write .lit file, don't modify BSP"},
nolights{this, "nolights", false, &output_group, "ignore light entities (only sunlight/minlight)"},
facestyles{this, "facestyles", 4, &output_group, "max amount of styles per face; requires BSPX lump if > 4"},
exportobj{this, "exportobj", false, &output_group, "export an .OBJ for inspection"},
lmshift{this, "lmshift", 4, &output_group,
"force a specified lmshift to be applied to the entire map; this is useful if you want to re-light a map with higher quality BSPX lighting without the sources. Will add the LMSHIFT lump to the BSP."},
lightgrid{this, "lightgrid", false, &experimental_group,
"generates a lightgrid and writes it to a bspx lump (LIGHTGRID_OCTREE)"},
lightgrid_dist{this, "lightgrid_dist", 32.f, 32.f, 32.f, &experimental_group,
"distance between lightgrid sample points, in world units. controls lightgrid size."},
lightgrid_format{this, "lightgrid_format", lightgrid_format_t::OCTREE, {{"octree", lightgrid_format_t::OCTREE}},
&experimental_group, "lightgrid BSPX lump to use"},
dirtdebug{this, {"dirtdebug", "debugdirt"},
[&](source) {
CheckNoDebugModeSet();
debugmode = debugmodes::dirt;
},
&debug_group, "only save the AO values to the lightmap"},
bouncedebug{this, "bouncedebug",
[&](source) {
CheckNoDebugModeSet();
debugmode = debugmodes::bounce;
},
&debug_group, "only save bounced lighting to the lightmap"},
bouncelightsdebug{this, "bouncelightsdebug",
[&](source) {
CheckNoDebugModeSet();
debugmode = debugmodes::bouncelights;
},
&debug_group, "only save bounced emitters lighting to the lightmap"},
phongdebug{this, "phongdebug",
[&](source) {
CheckNoDebugModeSet();
debugmode = debugmodes::phong;
},
&debug_group, "only save phong normals to the lightmap"},
phongdebug_obj{this, "phongdebug_obj",
[&](source) {
CheckNoDebugModeSet();
debugmode = debugmodes::phong_obj;
},
&debug_group, "save map as .obj with phonged normals"},
debugoccluded{this, "debugoccluded",
[&](source) {
CheckNoDebugModeSet();
debugmode = debugmodes::debugoccluded;
},
&debug_group, "save light occlusion data to lightmap"},
debugneighbours{this, "debugneighbours",
[&](source) {
CheckNoDebugModeSet();
debugmode = debugmodes::debugneighbours;
},
&debug_group, "save neighboring faces data to lightmap (requires -debugface)"},
debugmottle{this, "debugmottle",
[&](source) {
CheckNoDebugModeSet();
debugmode = debugmodes::mottle;
},
&debug_group, "save mottle pattern to lightmap"}
{
}
void light_settings::set_parameters(int argc, const char **argv)
{
common_settings::set_parameters(argc, argv);
program_description = "light compiles lightmap data for BSPs\n\n";
remainder_name = "mapname.bsp";
}
void light_settings::initialize(int argc, const char **argv)
{
try {
token_parser_t p(argc - 1, argv + 1, {"command line"});
auto remainder = parse(p);
if (remainder.size() <= 0 || remainder.size() > 1) {
print_help();
}
sourceMap = remainder[0];
} catch (parse_exception &ex) {
logging::print(ex.what());
print_help();
}
}
void light_settings::postinitialize(int argc, const char **argv)
{
if (gate.value() > 1) {
logging::print("WARNING: -gate value greater than 1 may cause artifacts\n");
}
if (radlights.is_changed()) {
if (!ParseLightsFile(*radlights.values().begin())) {
logging::print("Unable to read surface lights file {}\n", *radlights.values().begin());
}
}
if (soft.value() == -1) {
switch (extra.value()) {
case 2: soft.set_value(1, settings::source::COMMANDLINE); break;
case 4: soft.set_value(2, settings::source::COMMANDLINE); break;
default: soft.set_value(0, settings::source::COMMANDLINE); break;
}
}
if (debugmode != debugmodes::none) {
write_litfile |= lightfile::external;
}
if (litonly.value()) {
write_litfile |= lightfile::external;
}
if (write_litfile == lightfile::lit2) {
logging::print("generating lit2 output only.\n");
} else {
if (write_litfile & lightfile::external)
logging::print(".lit colored light output requested on command line.\n");
if (write_litfile & lightfile::external && write_litfile & lightfile::hdr)
logging::print(".lit colored E5BGR9 light output requested on command line.\n");
if (write_litfile & lightfile::bspx)
logging::print("BSPX colored light output requested on command line.\n");
if (write_litfile & lightfile::bspx && write_litfile & lightfile::hdr)
logging::print("BSPX colored E5BGR9 light output requested on command line.\n");
if (write_luxfile & lightfile::external)
logging::print(".lux light directions output requested on command line.\n");
if (write_luxfile & lightfile::bspx)
logging::print("BSPX light directions output requested on command line.\n");
}
if (debugmode == debugmodes::dirt) {
light_options.dirt.set_value(true, settings::source::COMMANDLINE);
} else if (debugmode == debugmodes::bounce || debugmode == debugmodes::bouncelights) {
light_options.bounce.set_value(true, settings::source::COMMANDLINE);
} else if (debugmode == debugmodes::debugneighbours && !debugface.is_changed()) {
FError("-debugneighbours without -debugface specified\n");
}
if (light_options.q2rtx.value()) {
if (!light_options.nolighting.is_changed()) {
light_options.nolighting.set_value(true, settings::source::GAME_TARGET);
}
if (!light_options.write_normals.is_changed()) {
light_options.write_normals.set_value(true, settings::source::GAME_TARGET);
}
}
// upgrade to uint16 if facestyles is specified
if (light_options.facestyles.value() > MAXLIGHTMAPS && !light_options.compilerstyle_max.is_changed()) {
light_options.compilerstyle_max.set_value(INVALID_LIGHTSTYLE, settings::source::COMMANDLINE);
}
common_settings::postinitialize(argc, argv);
}
void light_settings::reset()
{
common_settings::reset();
sourceMap = fs::path();
write_litfile = lightfile::none;
write_luxfile = lightfile::none;
debugmode = debugmodes::none;
}
} // namespace settings
settings::light_settings light_options;
void FixupGlobalSettings()
{
// NOTE: This is confusing.. Setting "dirt" "1" implies "minlight_dirt" "1"
// (and sunlight_dir/sunlight2_dirt as well), unless those variables were
// set by the user to "0".
//
// We can't just default "minlight_dirt" to "1" because that would enable
// dirtmapping by default.
if (light_options.dirt.value()) {
if (!light_options.minlight_dirt.is_changed()) {
light_options.minlight_dirt.set_value(true, settings::source::COMMANDLINE);
}
if (!light_options.sunlight_dirt.is_changed()) {
light_options.sunlight_dirt.set_value(1, settings::source::COMMANDLINE);
}
if (!light_options.sunlight2_dirt.is_changed()) {
light_options.sunlight2_dirt.set_value(1, settings::source::COMMANDLINE);
}
}
}
static std::mutex light_mutex;
/*
* Return space for the lightmap and colourmap at the same time so it can
* be done in a thread-safe manner.
*
* size is the number of greyscale pixels = number of bytes to allocate
* and return in *lightdata
*/
void GetFileSpace(uint8_t **lightdata, uint8_t **colordata, uint32_t **hdrdata, uint8_t **deluxdata, int size)
{
light_mutex.lock();
*lightdata = *colordata = *deluxdata = nullptr;
*hdrdata = nullptr;
if (!filebase.empty()) {
*lightdata = filebase.data() + file_p;
}
if (!lit_filebase.empty()) {
*colordata = lit_filebase.data() + lit_file_p;
}
if (!hdr_filebase.empty()) {
*hdrdata = hdr_filebase.data() + hdr_file_p;
}
if (!lux_filebase.empty()) {
*deluxdata = lux_filebase.data() + lux_file_p;
}
// if size isn't a multiple of 4, round up to the next multiple of 4
if ((size % 4) != 0) {
size += (4 - (size % 4));
}
// increment the next writing offsets, aligning them to 4 uint8_t boundaries (file_p)
// and 12-uint8_t boundaries (lit_file_p/lux_file_p)
if (!filebase.empty()) {
file_p += size;
}
if (!lit_filebase.empty()) {
lit_file_p += 3 * size;
}
if (!hdr_filebase.empty()) {
hdr_file_p += size;
}
if (!lux_filebase.empty()) {
lux_file_p += 3 * size;
}
light_mutex.unlock();
if (file_p > file_end)
FError("overrun");
if (lit_file_p > lit_file_end)
FError("overrun");
if (hdr_file_p > hdr_file_end)
FError("overrun");
}
/**
* Special version of GetFileSpace for when we're relighting a .bsp and can't modify it.
* In this case the offsets are already known.
*/
void GetFileSpace_PreserveOffsetInBsp(uint8_t **lightdata, uint8_t **colordata, uint32_t **hdrdata, uint8_t **deluxdata, int lightofs)
{
Q_assert(lightofs >= 0);
*lightdata = *colordata = *deluxdata = nullptr;
if (!filebase.empty()) {
*lightdata = filebase.data() + lightofs;
}
if (colordata && !lit_filebase.empty()) {
*colordata = lit_filebase.data() + (lightofs * 3);
}
if (hdrdata && !hdr_filebase.empty()) {
*hdrdata = hdr_filebase.data() + lightofs;
}
if (deluxdata && !lux_filebase.empty()) {
*deluxdata = lux_filebase.data() + (lightofs * 3);
}
// NOTE: file_p et. al. are not updated, since we're not dynamically allocating the lightmaps
}
const modelinfo_t *ModelInfoForModel(const mbsp_t *bsp, int modelnum)
{
return modelinfo.at(modelnum);
}
const modelinfo_t *ModelInfoForFace(const mbsp_t *bsp, int facenum)
{
int i;
const dmodelh2_t *model;
/* Find the correct model offset */
for (i = 0, model = bsp->dmodels.data(); i < bsp->dmodels.size(); i++, model++) {
if (facenum < model->firstface)
continue;
if (facenum < model->firstface + model->numfaces)
break;
}
if (i == bsp->dmodels.size()) {
return NULL;
}
return modelinfo.at(i);
}
struct face_texture_cache
{
const img::texture *image;
qvec3b averageColor;
qvec3d bounceColor;
};
static std::vector<face_texture_cache> face_textures;
const img::texture *Face_Texture(const mbsp_t *bsp, const mface_t *face)
{
return face_textures[face - bsp->dfaces.data()].image;
}
const qvec3b &Face_LookupTextureColor(const mbsp_t *bsp, const mface_t *face)
{
return face_textures[face - bsp->dfaces.data()].averageColor;
}
const qvec3d &Face_LookupTextureBounceColor(const mbsp_t *bsp, const mface_t *face)
{
return face_textures[face - bsp->dfaces.data()].bounceColor;
}
static void CacheTextures(const mbsp_t &bsp)
{
face_textures.resize(bsp.dfaces.size());
for (size_t i = 0; i < bsp.dfaces.size(); i++) {
const char *name = Face_TextureName(&bsp, &bsp.dfaces[i]);
if (!name || !*name) {
face_textures[i] = {nullptr, {127}, {0.5}};
} else {
auto tex = img::find(name);
auto &ext = extended_texinfo_flags[bsp.dfaces[i].texinfo];
auto avg = ext.surflight_color.value_or(tex->averageColor);
face_textures[i] = {tex, avg,
// lerp between gray and the texture color according to `bouncecolorscale` (0 = use gray, 1 = use
// texture color)
mix(qvec3d{127}, qvec3d(avg), light_options.bouncecolorscale.value()) / 255.0};
}
}
}
static void CreateLightmapSurfaces(mbsp_t *bsp)
{
light_surfaces.resize(bsp->dfaces.size());
logging::funcheader();
logging::parallel_for(static_cast<size_t>(0), bsp->dfaces.size(), [&bsp](size_t i) {
auto facesup = faces_sup.empty() ? nullptr : &faces_sup[i];
auto facesup_decoupled = facesup_decoupled_global.empty() ? nullptr : &facesup_decoupled_global[i];
auto face = &bsp->dfaces[i];
/* One extra lightmap is allocated to simplify handling overflow */
if (!light_options.litonly.value()) {
// if litonly is set we need to preserve the existing lightofs
/* some surfaces don't need lightmaps */
if (facesup) {
facesup->lightofs = -1;
for (size_t i = 0; i < MAXLIGHTMAPSSUP; i++) {
facesup->styles[i] = INVALID_LIGHTSTYLE;
}
} else {
face->lightofs = -1;
for (size_t i = 0; i < MAXLIGHTMAPS; i++) {
face->styles[i] = INVALID_LIGHTSTYLE_OLD;
}
if (facesup_decoupled) {
facesup_decoupled->offset = -1;
}
}
}
light_surfaces[i] = CreateLightmapSurface(bsp, face, facesup, facesup_decoupled, light_options);
});
}
static void SaveLightmapSurfaces(mbsp_t *bsp)
{
logging::funcheader();
logging::parallel_for(static_cast<size_t>(0), bsp->dfaces.size(), [&bsp](size_t i) {
auto &surf = light_surfaces[i];
if (!surf || surf->samples.empty()) {
return;
}
FinishLightmapSurface(bsp, surf.get());
auto f = &bsp->dfaces[i];
const modelinfo_t *face_modelinfo = ModelInfoForFace(bsp, i);
if (!facesup_decoupled_global.empty()) {
SaveLightmapSurface(
bsp, f, nullptr, &facesup_decoupled_global[i], surf.get(), surf->extents, surf->extents);
} else if (faces_sup.empty()) {
SaveLightmapSurface(bsp, f, nullptr, nullptr, surf.get(), surf->extents, surf->extents);
} else if (light_options.novanilla.value() || faces_sup[i].lmscale == face_modelinfo->lightmapscale) {
if (faces_sup[i].lmscale == face_modelinfo->lightmapscale) {
f->lightofs = faces_sup[i].lightofs;
} else {
f->lightofs = -1;
}
SaveLightmapSurface(bsp, f, &faces_sup[i], nullptr, surf.get(), surf->extents, surf->extents);
for (int j = 0; j < MAXLIGHTMAPS; j++) {
f->styles[j] =
faces_sup[i].styles[j] == INVALID_LIGHTSTYLE ? INVALID_LIGHTSTYLE_OLD : faces_sup[i].styles[j];
}
} else {
SaveLightmapSurface(bsp, f, nullptr, nullptr, surf.get(), surf->extents, surf->vanilla_extents);
SaveLightmapSurface(bsp, f, &faces_sup[i], nullptr, surf.get(), surf->extents, surf->extents);
}
});
}
void ClearLightmapSurfaces(mbsp_t *bsp)
{
logging::funcheader();
logging::parallel_for(static_cast<size_t>(0), bsp->dfaces.size(), [](size_t i) { light_surfaces[i].reset(); });
}
static void FindModelInfo(const mbsp_t *bsp)
{
Q_assert(modelinfo.size() == 0);
Q_assert(tracelist.size() == 0);
Q_assert(selfshadowlist.size() == 0);
Q_assert(shadowworldonlylist.size() == 0);
Q_assert(switchableshadowlist.size() == 0);
if (!bsp->dmodels.size()) {
FError("Corrupt .BSP: bsp->nummodels is 0!");
}
if (light_options.lightmap_scale.is_changed()) {
WorldEnt().set("_lightmap_scale", light_options.lightmap_scale.string_value());
}
float lightmapscale = WorldEnt().get_int("_lightmap_scale");
if (!lightmapscale)
lightmapscale = LMSCALE_DEFAULT; /* the default */
if (lightmapscale <= 0)
FError("lightmap scale is 0 or negative\n");
if (light_options.lightmap_scale.is_changed() || lightmapscale != LMSCALE_DEFAULT)
logging::print("Forcing lightmap scale of {}qu\n", lightmapscale);
/*I'm going to do this check in the hopes that there's a benefit to cheaper scaling in engines (especially software
* ones that might be able to just do some mip hacks). This tool doesn't really care.*/
{
int i;
for (i = 1; i < lightmapscale;) {
i++;
}
if (i != lightmapscale) {
logging::print("WARNING: lightmap scale is not a power of 2\n");
}
}
/* The world always casts shadows */
modelinfo_t *world = new modelinfo_t{bsp, &bsp->dmodels[0], lightmapscale};
world->shadow.set_value(1.0f, settings::source::MAP); /* world always casts shadows */
world->phong_angle.copy_from(light_options.phongangle);
modelinfo.push_back(world);
tracelist.push_back(world);
for (int i = 1; i < bsp->dmodels.size(); i++) {
modelinfo_t *info = new modelinfo_t{bsp, &bsp->dmodels[i], lightmapscale};
modelinfo.push_back(info);
/* Find the entity for the model */
std::string modelname = fmt::format("*{}", i);
const entdict_t *entdict = FindEntDictWithKeyPair("model", modelname);
if (entdict == nullptr)
FError("Couldn't find entity for model {}.\n", modelname);
// apply settings
info->set_settings(*entdict, settings::source::MAP);
/* Check if this model will cast shadows (shadow => shadowself) */
if (info->switchableshadow.boolValue()) {
Q_assert(info->switchshadstyle.value() != 0);
switchableshadowlist.push_back(info);
} else if (info->shadow.boolValue()) {
tracelist.push_back(info);
} else if (info->shadowself.boolValue()) {
selfshadowlist.push_back(info);
} else if (info->shadowworldonly.boolValue()) {
shadowworldonlylist.push_back(info);
}
/* Set up the offset for rotate_* entities */
entdict->get_vector("origin", info->offset);
}
Q_assert(modelinfo.size() == bsp->dmodels.size());
}
// FIXME: in theory can't we calculate the exact amount of
// storage required? we'd have to expand it by 4 to account for
// lightstyles though
static constexpr size_t MAX_MAP_LIGHTING = 0x8000000;
/*
* =============
* LightWorld
* =============
*/
static void LightWorld(bspdata_t *bspdata, bool forcedscale)
{
logging::funcheader();
mbsp_t &bsp = std::get<mbsp_t>(bspdata->bsp);
light_surfaces.clear();
filebase.clear();
lit_filebase.clear();
hdr_filebase.clear();
lux_filebase.clear();
if (!bsp.loadversion->game->has_rgb_lightmap) {
/* greyscale data stored in a separate buffer */
filebase.resize(MAX_MAP_LIGHTING);
file_p = 0;
file_end = MAX_MAP_LIGHTING;
}
if (bsp.loadversion->game->has_rgb_lightmap || light_options.write_litfile) {
/* litfile data stored in a separate buffer */
lit_filebase.resize(MAX_MAP_LIGHTING * 3);
lit_file_p = 0;
lit_file_end = (MAX_MAP_LIGHTING * 3);
}
if (bsp.loadversion->game->has_rgb_lightmap || light_options.write_litfile) {
/* hdr data stored in a separate buffer */
hdr_filebase.resize(MAX_MAP_LIGHTING);
hdr_file_p = 0;
hdr_file_end = MAX_MAP_LIGHTING;
}
if (light_options.write_luxfile) {
/* lux data stored in a separate buffer */
lux_filebase.resize(MAX_MAP_LIGHTING * 3);
lux_file_p = 0;
lux_file_end = (MAX_MAP_LIGHTING * 3);
}
if (forcedscale) {
bspdata->bspx.entries.erase("LMSHIFT");
} else if (light_options.lmshift.is_changed()) {
// if we forcefully specified an lmshift lump, we have to generate one.
bspdata->bspx.entries.erase("LMSHIFT");
std::vector<uint8_t> shifts(bsp.dfaces.size());
for (auto &shift : shifts) {
shift = light_options.lmshift.value();
}
bspdata->bspx.transfer("LMSHIFT", shifts);
}
auto lmshift_lump = bspdata->bspx.entries.find("LMSHIFT");
if (lmshift_lump == bspdata->bspx.entries.end() && light_options.write_litfile != lightfile::lit2 &&
light_options.facestyles.value() <= 4) {
faces_sup.clear(); // no scales, no lit2
} else { // we have scales or lit2 output. yay...
faces_sup.resize(bsp.dfaces.size());
if (lmshift_lump != bspdata->bspx.entries.end()) {
for (int i = 0; i < bsp.dfaces.size(); i++) {
faces_sup[i].lmscale = nth_bit(reinterpret_cast<const char *>(lmshift_lump->second.data())[i]);
}
} else {
for (int i = 0; i < bsp.dfaces.size(); i++) {
faces_sup[i].lmscale = modelinfo.at(0)->lightmapscale;
}
}
}
// decoupled lightmaps
facesup_decoupled_global.clear();
if (light_options.world_units_per_luxel.is_changed()) {
facesup_decoupled_global.resize(bsp.dfaces.size());
}
CalculateVertexNormals(&bsp);
// create lightmap surfaces
CreateLightmapSurfaces(&bsp);
const bool bouncerequired =
light_options.bounce.value() &&
(light_options.debugmode == debugmodes::none || light_options.debugmode == debugmodes::bounce ||
light_options.debugmode == debugmodes::bouncelights); // mxd
MakeRadiositySurfaceLights(light_options, &bsp);
UpdateEmissiveLightSurfacesList();
logging::header("Direct Lighting"); // mxd
logging::parallel_for(static_cast<size_t>(0), bsp.dfaces.size(), [&bsp](size_t i) {
if (light_surfaces[i] && Face_IsLightmapped(&bsp, &bsp.dfaces[i])) {
#if defined(HAVE_EMBREE) && defined(__SSE2__)
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
#endif
DirectLightFace(&bsp, *light_surfaces[i].get(), light_options);
}
});
if (bouncerequired && !light_options.nolighting.value()) {
for (size_t i = 0; i < light_options.bounce.value(); i++) {