/
resourcesystem.cpp
4655 lines (3953 loc) · 145 KB
/
resourcesystem.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
/** @file resourcesystem.cpp Resource subsystem.
*
* @authors Copyright © 2003-2014 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2005-2014 Daniel Swanson <danij@dengine.net>
* @authors Copyright © 2006-2007 Jamie Jones <jamie_jones_au@yahoo.com.au>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>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, see:
* http://www.gnu.org/licenses</small>
*/
#include "de_platform.h"
#include "resource/resourcesystem.h"
#ifdef __CLIENT__
# include "clientapp.h"
# include "ui/progress.h"
# include "sys_system.h" // novideo
#endif
#include "def_main.h"
#include "dd_main.h"
#include "dd_def.h"
#include "resource/compositetexture.h"
#include "resource/patch.h"
#include "resource/patchname.h"
#ifdef __CLIENT__
# include "MaterialSnapshot"
# include "gl/gl_tex.h"
# include "gl/gl_texmanager.h"
# include "render/rend_model.h"
# include "render/rend_particle.h" // Rend_ParticleReleaseSystemTextures
// For smart caching logics:
# include "network/net_demo.h" // playback
# include "render/rend_main.h" // Rend_MapSurfaceMaterialSpec
# include "render/billboard.h" // Rend_SpriteMaterialSpec
# include "render/sky.h"
# include "world/worldsystem.h"
# include "world/map.h"
# include "world/p_object.h"
# include "world/thinkers.h"
# include "Sector"
# include "Surface"
#endif
#include <doomsday/console/cmd.h>
#include <doomsday/filesys/fs_main.h>
#include <doomsday/filesys/fs_util.h>
#include <doomsday/filesys/lumpindex.h>
#include <de/App>
#include <de/ByteRefArray>
#include <de/DirectoryFeed>
#include <de/game/SavedSession>
#include <de/game/Session>
#include <de/Log>
#include <de/Loop>
#include <de/Module>
#include <de/ArrayValue>
#include <de/NumberValue>
#include <de/Reader>
#include <de/Task>
#include <de/TaskPool>
#include <de/Time>
#ifdef __CLIENT__
# include <de/ByteOrder>
# include <de/NativePath>
# include <de/StringPool>
#endif
#include <de/stack.h> /// @todo remove me
#include <de/memory.h>
#include <QHash>
#include <QVector>
#include <QtAlgorithms>
namespace de {
namespace internal
{
/**
* Compose the path to the data resource.
* @note We do not use the lump name, instead we use the logical lump index
* in the global LumpIndex. This is necessary because of the way id tech 1
* manages graphic references in animations (intermediate frames are chosen
* by their 'original indices' rather than by name).
*/
static inline de::Uri composeLumpIndexResourceUrn(lumpnum_t lumpNum)
{
return de::Uri("LumpIndex", Path(String("%1").arg(lumpNum)));
}
/// Returns a value in the range [0..Sprite::max_angles] if @a rotCode can be
/// interpreted as a sprite rotation number; otherwise @c -1
static int toSpriteRotation(QChar rotCode)
{
int rot = -1; // Unknown.
if(rotCode.isDigit())
{
rot = rotCode.digitValue();
}
else if(rotCode.isLetter())
{
char charCodeLatin1 = rotCode.toUpper().toLatin1();
if(charCodeLatin1 >= 'A')
{
rot = charCodeLatin1 - 'A' + 10;
}
}
if(rot > Sprite::max_angles)
{
rot = -1;
}
else if(rot > 0)
{
if(rot <= Sprite::max_angles / 2)
{
rot = (rot - 1) * 2 + 1;
}
else
{
rot = (rot - 9) * 2 + 2;
}
}
return rot;
}
/// Returns @c true iff @a name is a well-formed sprite name.
static bool validateSpriteName(String name)
{
if(name.length() < 6) return false;
// Character at position 5 is a rotation number.
if(toSpriteRotation(name.at(5)) < 0)
{
return false;
}
// If defined, the character at position 7 is also a rotation number.
if(name.length() >= 7)
{
if(toSpriteRotation(name.at(7)) < 0)
{
return false;
}
}
return true;
}
/// Ensure a texture has been derived for @a manifest.
static Texture *deriveTexture(TextureManifest &manifest)
{
LOG_AS("deriveTexture");
Texture *tex = manifest.derive();
if(!tex)
{
LOGDEV_RES_WARNING("Failed to derive a Texture for \"%s\", ignoring") << manifest.composeUri();
}
return tex;
}
static QList<File1 *> collectPatchCompositeDefinitionFiles()
{
QList<File1 *> result;
/*
* Precedence order of definitions is defined by id tech1 which processes
* the TEXTURE1/2 lumps in the following order:
*
* (last)TEXTURE2 > (last)TEXTURE1
*/
LumpIndex const &index = App_FileSystem().nameIndex();
lumpnum_t firstTexLump = App_FileSystem().lumpNumForName("TEXTURE1");
lumpnum_t secondTexLump = App_FileSystem().lumpNumForName("TEXTURE2");
/*
* Also process all other lumps named TEXTURE1/2.
*/
for(int i = 0; i < index.size(); ++i)
{
File1 &file = index[i];
// Will this be processed anyway?
if(i == firstTexLump) continue;
if(i == secondTexLump) continue;
String fileName = file.name().fileNameWithoutExtension();
if(fileName.compareWithoutCase("TEXTURE1") &&
fileName.compareWithoutCase("TEXTURE2"))
{
continue;
}
result.append(&file);
}
if(firstTexLump >= 0)
{
result.append(&index[firstTexLump]);
}
if(secondTexLump >= 0)
{
result.append(&index[secondTexLump]);
}
return result;
}
typedef QList<CompositeTexture *> CompositeTextures;
typedef QList<PatchName> PatchNames;
static PatchNames readPatchNames(File1 &file)
{
LOG_AS("readPatchNames");
PatchNames names;
if(file.size() < 4)
{
LOG_RES_WARNING("File \"%s\" does not appear to be valid PNAMES data")
<< NativePath(file.composeUri().asText()).pretty();
return names;
}
ByteRefArray lumpData(file.cache(), file.size());
de::Reader from(lumpData);
// The data begins with the total number of patch names.
dint32 numNames;
from >> numNames;
// Followed by the names (eight character ASCII strings).
if(numNames > 0)
{
if((unsigned) numNames > (file.size() - 4) / 8)
{
// The data appears to be truncated.
LOG_RES_WARNING("File \"%s\" appears to be truncated (%u bytes, expected %u)")
<< NativePath(file.composeUri().asText()).pretty()
<< file.size() << (numNames * 8 + 4);
// We'll only read this many names.
numNames = (file.size() - 4) / 8;
}
// Read the names.
for(int i = 0; i < numNames; ++i)
{
PatchName name;
from >> name;
names.append(name);
}
}
file.unlock();
return names;
}
/**
* Reads patch composite texture definitions from @a file.
*
* @param file File to be read.
* @param origIndexBase Base value for the "original index" logic.
* @param archiveCount Will be updated with the total number of definitions
* in the file (which may not necessarily equal the total
* number of definitions which are actually read).
*/
static CompositeTextures readCompositeTextureDefs(File1 &file,
PatchNames const &patchNames, int origIndexBase, int &archiveCount)
{
LOG_AS("readCompositeTextureDefs");
CompositeTextures result; ///< The resulting set of validated definitions.
// The game data format determines the format of the archived data.
CompositeTexture::ArchiveFormat format =
(gameDataFormat == 0? CompositeTexture::DoomFormat : CompositeTexture::StrifeFormat);
ByteRefArray data(file.cache(), file.size());
de::Reader reader(data);
// First is a count of the total number of definitions.
dint32 definitionCount;
reader >> definitionCount;
// Next is directory of offsets to the definitions.
typedef QMap<dint32, int> Offsets;
Offsets offsets;
for(int i = 0; i < definitionCount; ++i)
{
dint32 offset;
reader >> offset;
// Ensure the offset is within valid range.
if(offset < 0 || (unsigned) offset < definitionCount * sizeof(offset) ||
(dsize) offset > reader.source()->size())
{
LOG_RES_WARNING("Ignoring definition #%i: invalid offset %i") << i << offset;
}
else
{
offsets.insert(offset, origIndexBase + i);
}
}
// Seek to each offset and deserialize the definition.
DENG2_FOR_EACH_CONST(Offsets, i, offsets)
{
// Read the next definition.
reader.setOffset(i.key());
CompositeTexture *def = CompositeTexture::constructFrom(reader, patchNames, format);
// Attribute the "original index".
def->setOrigIndex(i.value());
// If the composite contains at least one known component image it is
// considered valid and we will therefore produce a Texture for it.
DENG2_FOR_EACH_CONST(CompositeTexture::Components, it, def->components())
{
if(it->lumpNum() >= 0)
{
// Its valid - include in the result.
result.append(def);
def = 0;
break;
}
}
// Failed to validate? Dump it.
if(def) delete def;
}
file.unlock(); // We have now finished with this file.
archiveCount = definitionCount;
return result;
}
#ifdef __CLIENT__
static int hashDetailTextureSpec(detailvariantspecification_t const &spec)
{
return (spec.contrast * (1/255.f) * DETAILTEXTURE_CONTRAST_QUANTIZATION_FACTOR + .5f);
}
static variantspecification_t &configureTextureSpec(variantspecification_t &spec,
texturevariantusagecontext_t tc, int flags, byte border, int tClass, int tMap,
int wrapS, int wrapT, int minFilter, int magFilter, int anisoFilter,
dd_bool mipmapped, dd_bool gammaCorrection, dd_bool noStretch, dd_bool toAlpha)
{
DENG2_ASSERT(tc == TC_UNKNOWN || VALID_TEXTUREVARIANTUSAGECONTEXT(tc));
flags &= ~TSF_INTERNAL_MASK;
spec.context = tc;
spec.flags = flags;
spec.border = (flags & TSF_UPSCALE_AND_SHARPEN)? 1 : border;
spec.mipmapped = mipmapped;
spec.wrapS = wrapS;
spec.wrapT = wrapT;
spec.minFilter = de::clamp(-1, minFilter, spec.mipmapped? 3:1);
spec.magFilter = de::clamp(-3, magFilter, 1);
spec.anisoFilter = de::clamp(-1, anisoFilter, 4);
spec.gammaCorrection = gammaCorrection;
spec.noStretch = noStretch;
spec.toAlpha = toAlpha;
if(tClass || tMap)
{
spec.flags |= TSF_HAS_COLORPALETTE_XLAT;
spec.tClass = de::max(0, tClass);
spec.tMap = de::max(0, tMap);
}
return spec;
}
static detailvariantspecification_t &configureDetailTextureSpec(
detailvariantspecification_t &spec, float contrast)
{
int const quantFactor = DETAILTEXTURE_CONTRAST_QUANTIZATION_FACTOR;
spec.contrast = 255 * de::clamp<int>(0, contrast * quantFactor + .5f, quantFactor) * (1 / float(quantFactor));
return spec;
}
#endif // __CLIENT__
} // namespace internal
} // namespace de
#ifdef __CLIENT__
/// @c TST_DETAIL type specifications are stored separately into a set of
/// buckets. Bucket selection is determined by their quantized contrast value.
#define DETAILVARIANT_CONTRAST_HASHSIZE (DETAILTEXTURE_CONTRAST_QUANTIZATION_FACTOR+1)
#endif
using namespace de;
using namespace internal;
/**
* Native Doomsday Script utility for scheduling conversion of a single legacy savegame.
*/
Value *Function_SavedSession_Convert(Context &, Function::ArgumentValues const &args)
{
String gameId = args[0]->asText();
String sourcePath = args[1]->asText();
return new NumberValue(App_ResourceSystem().convertLegacySavegames(gameId, sourcePath));
}
/**
* Native Doomsday Script utility for scheduling conversion of @em all legacy savegames
* for the specified gameId.
*/
Value *Function_SavedSession_ConvertAll(Context &, Function::ArgumentValues const &args)
{
String gameId = args[0]->asText();
return new NumberValue(App_ResourceSystem().convertLegacySavegames(gameId));
}
DENG2_PIMPL(ResourceSystem)
, DENG2_OBSERVES(Loop, Iteration) // post savegame conversion FS population
, DENG2_OBSERVES(Games, Addition) // savegames folder setup
, DENG2_OBSERVES(MaterialScheme, ManifestDefined)
, DENG2_OBSERVES(MaterialManifest, MaterialDerived)
, DENG2_OBSERVES(MaterialManifest, Deletion)
, DENG2_OBSERVES(Material, Deletion)
, DENG2_OBSERVES(TextureScheme, ManifestDefined)
, DENG2_OBSERVES(TextureManifest, TextureDerived)
, DENG2_OBSERVES(Texture, Deletion)
#ifdef __CLIENT__
, DENG2_OBSERVES(FontScheme, ManifestDefined)
, DENG2_OBSERVES(FontManifest, Deletion)
, DENG2_OBSERVES(AbstractFont, Deletion)
, DENG2_OBSERVES(ColorPalette, ColorTableChange)
#endif
{
typedef QList<ResourceClass *> ResourceClasses;
ResourceClasses resClasses;
NullResourceClass nullResourceClass;
typedef QList<AnimGroup *> AnimGroups;
AnimGroups animGroups;
typedef QMap<colorpaletteid_t, ColorPalette *> ColorPalettes;
ColorPalettes colorPalettes;
typedef QMap<String, ColorPalette *> ColorPaletteNames;
ColorPaletteNames colorPaletteNames;
colorpaletteid_t defaultColorPalette;
/// System subspace schemes containing the textures.
TextureSchemes textureSchemes;
QList<TextureScheme *> textureSchemeCreationOrder;
/// All texture instances in the system (from all schemes).
AllTextures textures;
typedef QHash<lumpnum_t, rawtex_t *> RawTextureHash;
RawTextureHash rawTexHash;
/// System subspace schemes containing the manifests/resources.
MaterialSchemes materialSchemes;
QList<MaterialScheme *> materialSchemeCreationOrder;
AllMaterials materials; ///< From all schemes.
uint materialManifestCount; ///< Total number of material manifests (in all schemes).
MaterialManifestGroups materialGroups;
uint materialManifestIdMapSize;
MaterialManifest **materialManifestIdMap; ///< Index with materialid_t-1
MapDefs mapDefs;
#ifdef __CLIENT__
/// System subspace schemes containing the manifests/resources.
FontSchemes fontSchemes;
QList<FontScheme *> fontSchemeCreationOrder;
AllFonts fonts; ///< From all schemes.
uint fontManifestCount; ///< Total number of font manifests (in all schemes).
uint fontManifestIdMapSize;
FontManifest **fontManifestIdMap; ///< Index with fontid_t-1
typedef QVector<ModelDef> ModelDefs;
ModelDefs modefs;
QVector<int> stateModefs; // Index to the modefs array.
typedef StringPool ModelRepository;
ModelRepository *modelRepository; // Owns Model instances.
/// A list of specifications for material variants.
typedef QList<MaterialVariantSpec *> MaterialSpecs;
MaterialSpecs materialSpecs;
typedef QList<TextureVariantSpec *> TextureSpecs;
TextureSpecs textureSpecs;
TextureSpecs detailTextureSpecs[DETAILVARIANT_CONTRAST_HASHSIZE];
struct CacheTask
{
virtual ~CacheTask() {}
virtual void run() = 0;
};
/**
* Stores the arguments for a resource cache work item.
*/
struct MaterialCacheTask : public CacheTask
{
Material *material;
MaterialVariantSpec const *spec; /// Interned context specification.
MaterialCacheTask(Material &resource, MaterialVariantSpec const &contextSpec)
: CacheTask(), material(&resource), spec(&contextSpec)
{}
void run()
{
ResourceSystem &resSys = App_ResourceSystem();
// Ensure a variant for the specified context is created.
material->createVariant(*spec);
DENG2_ASSERT(material->chooseVariant(*spec) != 0);
// Prepare all layer textures.
foreach(MaterialLayer *layer, material->layers())
foreach(MaterialLayer::Stage *stage, layer->stages())
{
if(stage->texture)
{
stage->texture->prepareVariant(*spec->primarySpec);
}
}
// Do we need to prepare detail texture(s)?
if(!material->isSkyMasked() && material->isDetailed())
foreach(MaterialDetailLayer::Stage *stage, material->detailLayer().stages())
{
if(stage->texture)
{
float const contrast = de::clamp(0.f, stage->strength, 1.f)
* detailFactor /*Global strength multiplier*/;
stage->texture->prepareVariant(resSys.detailTextureSpec(contrast));
}
}
// Do we need to prepare a shiny texture (and possibly a mask)?
if(!material->isSkyMasked() && material->isShiny())
foreach(MaterialShineLayer::Stage *stage, material->shineLayer().stages())
{
if(stage->texture)
{
stage->texture->prepareVariant(Rend_MapSurfaceShinyTextureSpec());
if(stage->maskTexture)
{
stage->maskTexture->prepareVariant(Rend_MapSurfaceShinyMaskTextureSpec());
}
}
}
}
};
/// A FIFO queue of material variant caching tasks.
/// Implemented as a list because we may need to remove tasks from the queue if
/// the material is destroyed in the mean time.
typedef QList<CacheTask *> CacheQueue;
CacheQueue cacheQueue;
#endif
struct SpriteGroup {
SpriteSet sprites;
~SpriteGroup() {
qDeleteAll(sprites);
}
};
typedef QMap<spritenum_t, SpriteGroup> SpriteGroups;
SpriteGroups spriteGroups;
NativePath nativeSavePath;
Binder binder;
Record savedSessionModule; // SavedSession: manipulation, conversion, etc... (based on native class SavedSession)
Instance(Public *i)
: Base(i)
, defaultColorPalette (0)
, materialManifestCount (0)
, materialManifestIdMapSize(0)
, materialManifestIdMap (0)
#ifdef __CLIENT__
, fontManifestCount (0)
, fontManifestIdMapSize (0)
, fontManifestIdMap (0)
, modelRepository (0)
#endif
, nativeSavePath (App::app().nativeHomePath() / "savegames") // default
{
de::Uri::setResolverFunc(ResourceSystem::resolveSymbol);
LOG_AS("ResourceSystem");
resClasses.append(new ResourceClass("RC_PACKAGE", "Packages"));
resClasses.append(new ResourceClass("RC_DEFINITION", "Defs"));
resClasses.append(new ResourceClass("RC_GRAPHIC", "Graphics"));
resClasses.append(new ResourceClass("RC_MODEL", "Models"));
resClasses.append(new ResourceClass("RC_SOUND", "Sfx"));
resClasses.append(new ResourceClass("RC_MUSIC", "Music"));
resClasses.append(new ResourceClass("RC_FONT", "Fonts"));
/// @note Order here defines the ambigious-URI search order.
createTextureScheme("Sprites");
createTextureScheme("Textures");
createTextureScheme("Flats");
createTextureScheme("Patches");
createTextureScheme("System");
createTextureScheme("Details");
createTextureScheme("Reflections");
createTextureScheme("Masks");
createTextureScheme("ModelSkins");
createTextureScheme("ModelReflectionSkins");
createTextureScheme("Lightmaps");
createTextureScheme("Flaremaps");
/// @note Order here defines the ambigious-URI search order.
createMaterialScheme("Sprites");
createMaterialScheme("Textures");
createMaterialScheme("Flats");
createMaterialScheme("System");
#ifdef __CLIENT__
/// @note Order here defines the ambigious-URI search order.
createFontScheme("System");
createFontScheme("Game");
#endif
#ifdef __CLIENT__
// Setup the SavedSession module.
binder.init(savedSessionModule)
<< DENG2_FUNC(SavedSession_Convert, "convert", "gameId" << "savegamePath")
<< DENG2_FUNC(SavedSession_ConvertAll, "convertAll", "gameId");
App::scriptSystem().addNativeModule("SavedSession", savedSessionModule);
// Determine the root directory of the saved session repository.
if(int arg = App::commandLine().check("-savedir", 1))
{
// Using a custom root save directory.
App::commandLine().makeAbsolutePath(arg + 1);
nativeSavePath = App::commandLine().at(arg + 1);
}
// Else use the default.
#endif
App_Games().audienceForAddition() += this;
// Create the user saved session folder in the local FS if it doesn't yet exist.
// Once created, any SavedSessions in this folder will be found and indexed
// automatically into the file system.
App::fileSystem().makeFolder("/home/savegames");
// Create the legacy savegame folder.
App::fileSystem().makeFolder("/legacysavegames");
}
~Instance()
{
convertSavegameTasks.waitForDone();
App_Games().audienceForAddition() -= this;
qDeleteAll(resClasses);
self.clearAllAnimGroups();
#ifdef __CLIENT__
self.clearAllFontSchemes();
clearFontManifests();
#endif
self.clearAllTextureSchemes();
clearTextureManifests();
#ifdef __CLIENT__
self.clearAllRawTextures();
#endif
#ifdef __CLIENT__
self.purgeCacheQueue();
#endif
self.clearAllMaterialGroups();
self.clearAllMaterialSchemes();
clearMaterialManifests();
#ifdef __CLIENT__
clearAllTextureSpecs();
clearMaterialSpecs();
#endif
clearSprites();
#ifdef __CLIENT__
clearModels();
#endif
self.clearAllColorPalettes();
self.clearAllMapDefs();
}
inline de::FS1 &fileSys()
{
return App_FileSystem();
}
void gameAdded(Game &game)
{
// Called from a non-UI thread.
LOG_AS("ResourceSystem");
// Make the /home/savegames/<gameId> subfolder in the local FS if it does not yet exist.
App::fileSystem().makeFolder(String("/home/savegames") / game.id());
}
void clearMaterialManifests()
{
qDeleteAll(materialSchemes);
materialSchemes.clear();
materialSchemeCreationOrder.clear();
// Clear the manifest index/map.
if(materialManifestIdMap)
{
M_Free(materialManifestIdMap); materialManifestIdMap = 0;
materialManifestIdMapSize = 0;
}
materialManifestCount = 0;
}
void createMaterialScheme(String name)
{
DENG2_ASSERT(name.length() >= MaterialScheme::min_name_length);
// Create a new scheme.
MaterialScheme *newScheme = new MaterialScheme(name);
materialSchemes.insert(name.toLower(), newScheme);
materialSchemeCreationOrder.append(newScheme);
// We want notification when a new manifest is defined in this scheme.
newScheme->audienceForManifestDefined += this;
}
void clearTextureManifests()
{
qDeleteAll(textureSchemes);
textureSchemes.clear();
textureSchemeCreationOrder.clear();
}
void createTextureScheme(String name)
{
DENG2_ASSERT(name.length() >= TextureScheme::min_name_length);
// Create a new scheme.
TextureScheme *newScheme = new TextureScheme(name);
textureSchemes.insert(name.toLower(), newScheme);
textureSchemeCreationOrder.append(newScheme);
// We want notification when a new manifest is defined in this scheme.
newScheme->audienceForManifestDefined += this;
}
#ifdef __CLIENT__
void clearFontManifests()
{
qDeleteAll(fontSchemes);
fontSchemes.clear();
fontSchemeCreationOrder.clear();
// Clear the manifest index/map.
if(fontManifestIdMap)
{
M_Free(fontManifestIdMap); fontManifestIdMap = 0;
fontManifestIdMapSize = 0;
}
fontManifestCount = 0;
}
void createFontScheme(String name)
{
DENG2_ASSERT(name.length() >= FontScheme::min_name_length);
// Create a new scheme.
FontScheme *newScheme = new FontScheme(name);
fontSchemes.insert(name.toLower(), newScheme);
fontSchemeCreationOrder.append(newScheme);
// We want notification when a new manifest is defined in this scheme.
newScheme->audienceForManifestDefined += this;
}
#endif
void clearSprites()
{
spriteGroups.clear();
}
SpriteGroup *spriteGroup(spritenum_t spriteId)
{
SpriteGroups::iterator found = spriteGroups.find(spriteId);
if(found != spriteGroups.end())
{
return &found.value();
}
return 0;
}
SpriteGroup &newSpriteGroup(spritenum_t spriteId)
{
DENG2_ASSERT(!spriteGroup(spriteId)); // sanity check.
return spriteGroups.insert(spriteId, SpriteGroup()).value();
}
#ifdef __CLIENT__
void clearRuntimeFonts()
{
self.fontScheme("Game").clear();
self.pruneUnusedTextureSpecs();
}
void clearSystemFonts()
{
self.fontScheme("System").clear();
self.pruneUnusedTextureSpecs();
}
void clearMaterialSpecs()
{
qDeleteAll(materialSpecs);
materialSpecs.clear();
}
MaterialVariantSpec *findMaterialSpec(MaterialVariantSpec const &tpl,
bool canCreate)
{
foreach(MaterialVariantSpec *spec, materialSpecs)
{
if(spec->compare(tpl)) return spec;
}
if(!canCreate) return 0;
materialSpecs.append(new MaterialVariantSpec(tpl));
return materialSpecs.back();
}
MaterialVariantSpec &getMaterialSpecForContext(MaterialContextId contextId,
int flags, byte border, int tClass, int tMap, int wrapS, int wrapT,
int minFilter, int magFilter, int anisoFilter,
bool mipmapped, bool gammaCorrection, bool noStretch, bool toAlpha)
{
static MaterialVariantSpec tpl;
texturevariantusagecontext_t primaryContext = TC_UNKNOWN;
switch(contextId)
{
case UiContext: primaryContext = TC_UI; break;
case MapSurfaceContext: primaryContext = TC_MAPSURFACE_DIFFUSE; break;
case SpriteContext: primaryContext = TC_SPRITE_DIFFUSE; break;
case ModelSkinContext: primaryContext = TC_MODELSKIN_DIFFUSE; break;
case PSpriteContext: primaryContext = TC_PSPRITE_DIFFUSE; break;
case SkySphereContext: primaryContext = TC_SKYSPHERE_DIFFUSE; break;
default: DENG2_ASSERT(false);
}
TextureVariantSpec const &primarySpec =
self.textureSpec(primaryContext, flags, border, tClass, tMap,
wrapS, wrapT, minFilter, magFilter,
anisoFilter, mipmapped, gammaCorrection,
noStretch, toAlpha);
// Apply the normalized spec to the template.
tpl.context = contextId;
tpl.primarySpec = &primarySpec;
return *findMaterialSpec(tpl, true);
}
TextureVariantSpec &linkTextureSpec(TextureVariantSpec *spec)
{
DENG2_ASSERT(spec != 0);
switch(spec->type)
{
case TST_GENERAL:
textureSpecs.append(spec);
break;
case TST_DETAIL: {
int hash = hashDetailTextureSpec(spec->detailVariant);
detailTextureSpecs[hash].append(spec);
break; }
}
return *spec;
}
TextureVariantSpec *findTextureSpec(TextureVariantSpec const &tpl, bool canCreate)
{
// Do we already have a concrete version of the template specification?
switch(tpl.type)
{
case TST_GENERAL: {
foreach(TextureVariantSpec *varSpec, textureSpecs)
{
if(*varSpec == tpl)
{
return varSpec;
}
}
break; }
case TST_DETAIL: {
int hash = hashDetailTextureSpec(tpl.detailVariant);
foreach(TextureVariantSpec *varSpec, detailTextureSpecs[hash])
{
if(*varSpec == tpl)
{
return varSpec;
}
}
break; }
}
// Not found, can we create?
if(canCreate)
{
return &linkTextureSpec(new TextureVariantSpec(tpl));
}
return 0;
}
TextureVariantSpec *textureSpec(texturevariantusagecontext_t tc, int flags,
byte border, int tClass, int tMap, int wrapS, int wrapT, int minFilter,
int magFilter, int anisoFilter, dd_bool mipmapped, dd_bool gammaCorrection,
dd_bool noStretch, dd_bool toAlpha)
{
static TextureVariantSpec tpl;
tpl.type = TST_GENERAL;
configureTextureSpec(tpl.variant, tc, flags, border, tClass, tMap, wrapS,
wrapT, minFilter, magFilter, anisoFilter, mipmapped, gammaCorrection,
noStretch, toAlpha);
// Retrieve a concrete version of the rationalized specification.
return findTextureSpec(tpl, true);
}
TextureVariantSpec *detailTextureSpec(float contrast)
{
static TextureVariantSpec tpl;
tpl.type = TST_DETAIL;
configureDetailTextureSpec(tpl.detailVariant, contrast);
return findTextureSpec(tpl, true);
}
bool textureSpecInUse(TextureVariantSpec const &spec)
{
foreach(Texture *texture, textures)
foreach(TextureVariant *variant, texture->variants())
{
if(&variant->spec() == &spec)
{
return true; // Found one; stop.
}
}
return false;
}
int pruneUnusedTextureSpecs(TextureSpecs &list)
{
int numPruned = 0;
QMutableListIterator<TextureVariantSpec *> it(list);
while(it.hasNext())
{
TextureVariantSpec *spec = it.next();
if(!textureSpecInUse(*spec))