/
materials.cpp
1695 lines (1433 loc) · 51.5 KB
/
materials.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 materials.cpp
* Materials collection, schemes, bindings and other management. @ingroup resource
*
* @authors Copyright © 2003-2012 Jaakko Keränen <jaakko.keranen@iki.fi>
* @authors Copyright © 2006-2012 Daniel Swanson <danij@dengine.net>
*
* @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, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include <cstdlib>
#include <cstring>
#include "de_base.h"
#include "de_console.h"
#include "de_system.h"
#include "de_filesys.h"
#include "de_network.h"
#include "de_render.h"
#include "de_graphics.h"
#include "de_misc.h"
#include "de_audio.h" // For texture, environmental audio properties.
#include "de_resource.h"
#include "gl/sys_opengl.h" /// @todo: get rid of this -jk
#include <QtAlgorithms>
#include <QList>
#include <de/Error>
#include <de/Log>
#include <de/PathTree>
#include <de/memory.h>
#include <de/memoryzone.h>
#include <cstring>
#include "resource/materialbind.h"
#include "resource/materials.h"
#include "resource/materialsnapshot.h"
/// Number of elements to block-allocate in the material index to materialbind map.
#define MATERIALS_BINDINGMAP_BLOCK_ALLOC (32)
D_CMD(InspectMaterial);
D_CMD(ListMaterials);
#if _DEBUG
D_CMD(PrintMaterialStats);
#endif
namespace de {
static void clearBindingDefinitionLinks(MaterialBind &mb)
{
MaterialBind::Info *info = mb.info();
if(info)
{
info->decorationDefs[0] = info->decorationDefs[1] = NULL;
info->detailtextureDefs[0] = info->detailtextureDefs[1] = NULL;
info->ptcgenDefs[0] = info->ptcgenDefs[1] = NULL;
info->reflectionDefs[0] = info->reflectionDefs[1] = NULL;
}
}
static void updateMaterialBindInfo(MaterialBind &mb, bool canCreateInfo)
{
MaterialBind::Info *info = mb.info();
material_t *mat = mb.material();
bool isCustom = (mat? Material_IsCustom(mat) : false);
if(!info)
{
if(!canCreateInfo) return;
// Create new info and attach to this binding.
info = (MaterialBind::Info *) M_Malloc(sizeof *info);
if(!info) Con_Error("Materials::updateMaterialBindInfo: Failed on allocation of %lu bytes for new MaterialBindInfo.", (unsigned long) sizeof *info);
mb.attachInfo(*info);
}
// Surface decorations (lights and models).
info->decorationDefs[0] = Def_GetDecoration(mat, 0, isCustom);
info->decorationDefs[1] = Def_GetDecoration(mat, 1, isCustom);
// Reflection (aka shiny surface).
info->reflectionDefs[0] = Def_GetReflection(mat, 0, isCustom);
info->reflectionDefs[1] = Def_GetReflection(mat, 1, isCustom);
// Generator (particles).
info->ptcgenDefs[0] = Def_GetGenerator(mat, 0, isCustom);
info->ptcgenDefs[1] = Def_GetGenerator(mat, 1, isCustom);
// Detail texture.
info->detailtextureDefs[0] = Def_GetDetailTex(mat, 0, isCustom);
info->detailtextureDefs[1] = Def_GetDetailTex(mat, 1, isCustom);
}
typedef struct materialvariantspecificationlistnode_s {
struct materialvariantspecificationlistnode_s *next;
materialvariantspecification_t *spec;
} MaterialVariantSpecificationListNode;
typedef MaterialVariantSpecificationListNode VariantSpecificationList;
typedef struct materiallistnode_s {
struct materiallistnode_s *next;
material_t *mat;
} MaterialListNode;
typedef MaterialListNode MaterialList;
typedef struct variantcachequeuenode_s {
struct variantcachequeuenode_s *next;
material_t *mat;
materialvariantspecification_t const *spec;
bool smooth;
} VariantCacheQueueNode;
typedef VariantCacheQueueNode VariantCacheQueue;
typedef struct materialanim_frame_s {
material_t* material;
ushort tics;
ushort random;
} MaterialAnimFrame;
typedef struct materialanim_s {
int id;
int flags;
int index;
int maxTimer;
int timer;
int count;
MaterialAnimFrame* frames;
} MaterialAnim;
static void animateGroup(MaterialAnim *group);
static int compareVariantSpecifications(materialvariantspecification_t const &a,
materialvariantspecification_t const &b);
struct Materials::Instance
{
int numgroups;
MaterialAnim* groups;
VariantSpecificationList *variantSpecs;
VariantCacheQueue *variantCacheQueue;
/**
* The following data structures and variables are intrinsically linked and
* are inter-dependant. The model used is somewhat complicated due to the
* required traits of the materials themselves and in of the system itself:
*
* 1) Pointers to Material are eternal, they are always valid and continue
* to reference the same logical material data even after engine reset.
* 2) Public material identifiers (materialid_t) are similarly eternal.
* Note that they are used to index the material name bindings map.
* 3) Dynamic creation/update of materials.
* 4) Material name bindings are semi-independant from the materials. There
* may be multiple name bindings for a given material (aliases).
* The only requirement is that their symbolic names must be unique among
* those in the same scheme.
* 5) Super-fast look up by public material identifier.
* 6) Fast look up by material name (hashing is used).
*/
MaterialList *materials;
uint materialCount;
uint bindingCount;
/// LUT which translates materialid_t to MaterialBind*. Index with materialid_t-1
uint bindingIdMapSize;
MaterialBind **bindingIdMap;
/// System subspace schemes containing the materials.
Materials::Schemes schemes;
Instance()
: numgroups(0), groups(0), variantSpecs(0), variantCacheQueue(0),
materials(0), materialCount(0),
bindingCount(0), bindingIdMapSize(0), bindingIdMap(0)
{}
~Instance()
{
clearBindings();
clearMaterials();
clearVariantSpecifications();
}
void clearVariantSpecifications()
{
while(variantSpecs)
{
MaterialVariantSpecificationListNode *next = variantSpecs->next;
M_Free(variantSpecs->spec);
M_Free(variantSpecs);
variantSpecs = next;
}
}
void clearMaterials()
{
while(materials)
{
MaterialListNode *next = materials->next;
Material_Delete(materials->mat);
M_Free(materials);
materials = next;
}
materialCount = 0;
}
void clearBindings()
{
DENG2_FOR_EACH(Materials::Schemes, i, schemes)
{
delete *i;
}
schemes.clear();
// Clear the binding index/map.
if(bindingIdMap)
{
M_Free(bindingIdMap); bindingIdMap = 0;
bindingIdMapSize = 0;
}
bindingCount = 0;
}
MaterialAnim* getAnimGroup(int number)
{
if(--number < 0 || number >= numgroups) return NULL;
return &groups[number];
}
bool isInAnimGroup(MaterialAnim const &group, material_t const &mat)
{
for(int i = 0; i < group.count; ++i)
{
if(group.frames[i].material == &mat)
return true;
}
return false;
}
void animateAllGroups()
{
for(int i = 0; i < numgroups; ++i)
{
animateGroup(&groups[i]);
}
}
materialvariantspecification_t *dupVariantSpecification(
materialvariantspecification_t const &tpl)
{
materialvariantspecification_t *spec = (materialvariantspecification_t *) M_Malloc(sizeof *spec);
if(!spec) Con_Error("Materials::copyVariantSpecification: Failed on allocation of %lu bytes for new MaterialVariantSpecification.", (unsigned long) sizeof *spec);
std::memcpy(spec, &tpl, sizeof *spec);
return spec;
}
void applyVariantSpecification(materialvariantspecification_t &spec, materialcontext_t mc,
texturevariantspecification_t *primarySpec)
{
DENG2_ASSERT(mc == MC_UNKNOWN || VALID_MATERIALCONTEXT(mc) && primarySpec);
spec.context = mc;
spec.primarySpec = primarySpec;
}
materialvariantspecification_t *linkVariantSpecification(
materialvariantspecification_t &spec)
{
MaterialVariantSpecificationListNode * node = (MaterialVariantSpecificationListNode *) M_Malloc(sizeof(*node));
if(!node) Con_Error("Materials::linkVariantSpecification: Failed on allocation of %lu bytes for new MaterialVariantSpecificationListNode.", (unsigned long) sizeof(*node));
node->spec = &spec;
node->next = variantSpecs;
variantSpecs = (VariantSpecificationList *)node;
return &spec;
}
materialvariantspecification_t *findVariantSpecification(
materialvariantspecification_t const &tpl, bool canCreate)
{
for(MaterialVariantSpecificationListNode* node = variantSpecs; node; node = node->next)
{
if(compareVariantSpecifications(*node->spec, tpl))
{
return node->spec;
}
}
if(!canCreate) return 0;
return linkVariantSpecification(*dupVariantSpecification(tpl));
}
materialvariantspecification_t *getVariantSpecificationForContext(
materialcontext_t mc, 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 materialvariantspecification_t tpl;
DENG2_ASSERT(mc == MC_UNKNOWN || VALID_MATERIALCONTEXT(mc));
texturevariantusagecontext_t primaryContext;
switch(mc)
{
case MC_UI: primaryContext = TC_UI; break;
case MC_MAPSURFACE: primaryContext = TC_MAPSURFACE_DIFFUSE; break;
case MC_SPRITE: primaryContext = TC_SPRITE_DIFFUSE; break;
case MC_MODELSKIN: primaryContext = TC_MODELSKIN_DIFFUSE; break;
case MC_PSPRITE: primaryContext = TC_PSPRITE_DIFFUSE; break;
case MC_SKYSPHERE: primaryContext = TC_SKYSPHERE_DIFFUSE; break;
default: primaryContext = TC_UNKNOWN; break;
}
texturevariantspecification_t* primarySpec =
GL_TextureVariantSpecificationForContext(primaryContext, flags, border, tClass, tMap, wrapS, wrapT,
minFilter, magFilter, anisoFilter, mipmapped,
gammaCorrection, noStretch, toAlpha);
applyVariantSpecification(tpl, mc, primarySpec);
return findVariantSpecification(tpl, true);
}
MaterialBind *getMaterialBindForId(materialid_t id)
{
if(0 == id || id > bindingCount) return NULL;
return bindingIdMap[id-1];
}
/**
* Link the material into the global list of materials.
* @pre material is NOT already present in the global list.
*/
material_t *linkMaterialToGlobalList(material_t *mat)
{
MaterialListNode *node = (MaterialListNode *)M_Malloc(sizeof *node);
if(!node) Con_Error("linkMaterialToGlobalList: Failed on allocation of %lu bytes for new MaterialList::Node.", (unsigned long) sizeof *node);
node->mat = mat;
node->next = materials;
materials = node;
return mat;
}
void pushVariantCacheQueue(material_t &mat, materialvariantspecification_t const &spec, bool smooth)
{
VariantCacheQueueNode *node = (VariantCacheQueueNode *) M_Malloc(sizeof *node);
if(!node) Con_Error("Materials::pushVariantCacheQueue: Failed on allocation of %lu bytes for new VariantCacheQueueNode.", (unsigned long) sizeof *node);
node->mat = &mat;
node->spec = &spec;
node->smooth = smooth;
node->next = variantCacheQueue;
variantCacheQueue = node;
}
};
void Materials::consoleRegister()
{
C_CMD("inspectmaterial", "ss", InspectMaterial)
C_CMD("inspectmaterial", "s", InspectMaterial)
C_CMD("listmaterials", "ss", ListMaterials)
C_CMD("listmaterials", "s", ListMaterials)
C_CMD("listmaterials", "", ListMaterials)
#ifdef DENG_DEBUG
C_CMD("materialstats", NULL, PrintMaterialStats)
#endif
}
Materials::Materials()
{
LOG_VERBOSE("Initializing Materials collection...");
d = new Instance();
createScheme("System");
createScheme("Flats");
createScheme("Textures");
createScheme("Sprites");
}
Materials::~Materials()
{
purgeCacheQueue();
delete d;
}
bool Materials::knownScheme(String name) const
{
if(!name.isEmpty())
{
DENG2_FOR_EACH(Schemes, i, d->schemes)
{
if(!(*i)->name().compareWithoutCase(name))
return true;
}
//Schemes::iterator found = d->schemes.find(name.toLower());
//if(found != d->schemes.end()) return true;
}
return false;
}
Materials::Scheme &Materials::scheme(String name) const
{
LOG_AS("Materials::scheme");
DENG2_FOR_EACH(Schemes, i, d->schemes)
{
if(!(*i)->name().compareWithoutCase(name))
return **i;
}
/// @throw UnknownSchemeError An unknown scheme was referenced.
throw Materials::UnknownSchemeError("Materials::scheme", "No scheme found matching '" + name + "'");
}
Materials::Schemes const& Materials::allSchemes() const
{
return d->schemes;
}
void Materials::clearDefinitionLinks()
{
for(MaterialListNode *node = d->materials; node; node = node->next)
{
material_t *mat = node->mat;
Material_SetDefinition(mat, NULL);
}
DENG2_FOR_EACH_CONST(Schemes, i, d->schemes)
{
PathTreeIterator<MaterialScheme::Index> iter((*i)->index().leafNodes());
while(iter.hasNext())
{
clearBindingDefinitionLinks(iter.next());
}
}
}
void Materials::rebuild(material_t *mat, ded_material_t *def)
{
if(!mat || !def) return;
/// @todo We should be able to rebuild the variants.
Material_DestroyVariants(mat);
Material_SetDefinition(mat, def);
// Update bindings.
for(uint i = 0; i < d->bindingCount; ++i)
{
MaterialBind *mb = d->bindingIdMap[i];
if(!mb || mb->material() != mat) continue;
updateMaterialBindInfo(*mb, false /*do not create, only update if present*/);
}
}
void Materials::purgeCacheQueue()
{
while(d->variantCacheQueue)
{
VariantCacheQueueNode *node = d->variantCacheQueue, *next = node->next;
M_Free(node);
d->variantCacheQueue = next;
}
}
void Materials::processCacheQueue()
{
while(d->variantCacheQueue)
{
VariantCacheQueueNode *node = d->variantCacheQueue, *next = node->next;
prepare(*node->mat, *node->spec, node->smooth);
M_Free(node);
d->variantCacheQueue = next;
}
}
MaterialBind *Materials::toMaterialBind(materialid_t id)
{
MaterialBind *mb = d->getMaterialBindForId(id);
if(!mb) return 0;
return mb;
}
Materials::Scheme& Materials::createScheme(String name)
{
DENG_ASSERT(name.length() >= Scheme::min_name_length);
// Ensure this is a unique name.
if(knownScheme(name)) return scheme(name);
// Create a new scheme.
Scheme* newScheme = new Scheme(name);
d->schemes.push_back(newScheme);
return *newScheme;
}
bool Materials::validateUri(Uri const &uri, UriValidationFlags flags, bool quiet) const
{
LOG_AS("Materials::validateUri");
if(uri.isEmpty())
{
if(!quiet) LOG_MSG("Empty path in material URI \"%s\".") << uri;
return false;
}
if(uri.scheme().isEmpty())
{
if(!flags.testFlag(AnyScheme))
{
if(!quiet) LOG_MSG("Missing scheme in material URI \"%s\".") << uri;
return false;
}
}
else if(!knownScheme(uri.scheme()))
{
if(!quiet) LOG_MSG("Unknown scheme in material URI \"%s\".") << uri;
return false;
}
return true;
}
MaterialBind &Materials::find(Uri const &uri) const
{
LOG_AS("Materials::find");
if(!validateUri(uri, AnyScheme, true /*quiet please*/))
/// @throw NotFoundError Failed to locate a matching bind.
throw NotFoundError("Materials::find", "URI \"" + uri.asText() + "\" failed validation");
// Perform the search.
String const &path = uri.path();
// Does the user want a bind in a specific scheme?
if(!uri.scheme().isEmpty())
{
try
{
return scheme(uri.scheme()).find(path);
}
catch(MaterialScheme::NotFoundError const &)
{} // Ignore, we'll throw our own...
}
else
{
// No, check in each of these schemes (in priority order).
/// @todo This priorty order should be defined by the user.
static String const order[] = {
"Sprites",
"Textures",
"Flats",
""
};
for(int i = 0; !order[i].isEmpty(); ++i)
{
try
{
return scheme(order[i]).find(path);
}
catch(MaterialScheme::NotFoundError const &)
{} // Ignore this error.
}
}
/// @throw NotFoundError Failed to locate a matching bind.
throw NotFoundError("Materials::find", "Failed to locate a bind matching \"" + uri.asText() + "\"");
}
bool Materials::has(Uri const &path) const
{
try
{
find(path);
return true;
}
catch(NotFoundError const &)
{} // Ignore this error.
return false;
}
MaterialBind &Materials::newBind(MaterialScheme &scheme, Path const &path, material_t *material)
{
LOG_AS("Materials::newBind");
// Have we already created a bind for this?
MaterialBind *bind = 0;
try
{
bind = &find(de::Uri(scheme.name(), path));
}
catch(NotFoundError const &)
{
// Acquire a new unique identifier for this binding.
materialid_t const bindId = ++d->bindingCount;
bind = &scheme.insertBind(path, bindId);
if(material)
{
Material_SetPrimaryBind(material, bindId);
}
// Add the new binding to the bindings index/map.
if(d->bindingCount > d->bindingIdMapSize)
{
// Allocate more memory.
d->bindingIdMapSize += MATERIALS_BINDINGMAP_BLOCK_ALLOC;
d->bindingIdMap = (MaterialBind **) M_Realloc(d->bindingIdMap, sizeof *d->bindingIdMap * d->bindingIdMapSize);
if(!d->bindingIdMap) Con_Error("Materials::newBind: Failed on (re)allocation of %lu bytes enlarging MaterialBind map.", (unsigned long) sizeof *d->bindingIdMap * d->bindingIdMapSize);
}
d->bindingIdMap[d->bindingCount - 1] = bind; /* 1-based index */
}
if(!bind)
throw Error("Materials::newBind", "Unexpected error creating bind \"" + de::Uri(scheme.name(), path) + "\"");
// (Re)configure the binding.
bind->setMaterial(material);
updateMaterialBindInfo(*bind, false/*do not create, only update if present*/);
return *bind;
}
material_t *Materials::newFromDef(ded_material_t *def)
{
DENG2_ASSERT(def);
LOG_AS("Materials::newFromDef");
if(!def->uri) return 0;
de::Uri &uri = reinterpret_cast<de::Uri &>(*def->uri);
if(uri.isEmpty()) return 0;
// We require a properly formed uri (but not a urn - this is a path).
if(!validateUri(uri, 0, (verbose >= 1)))
{
LOG_WARNING("Failed creating Material \"%s\" from definition %p, ignoring.") << uri << dintptr(def);
return 0;
}
// Have we already created a material for this?
MaterialBind *bind = 0;
try
{
bind = &find(uri);
if(bind->material())
{
LOG_DEBUG("A Material with uri \"%s\" already exists, returning existing.") << uri;
return bind->material();
}
}
catch(NotFoundError const &)
{} // Ignore for now.
// Ensure the primary layer has a valid texture reference.
Texture *tex = 0;
if(def->layers[0].stageCount.num > 0)
{
ded_material_layer_t const &layer = def->layers[0];
de::Uri *texUri = reinterpret_cast<de::Uri *>(layer.stages[0].texture);
if(texUri) // Not unused.
{
try
{
tex = App_Textures()->find(*texUri).texture();
}
catch(Textures::NotFoundError const &er)
{
// Log but otherwise ignore this error.
LOG_WARNING(er.asText() + ". Unknown texture \"%s\" in Material \"%s\" (layer %i stage %i), ignoring.")
<< reinterpret_cast<de::Uri*>(layer.stages[0].texture)
<< reinterpret_cast<de::Uri*>(def->uri)
<< 0 << 0;
}
}
}
if(!tex) return 0;
// A new Material.
d->materialCount++;
material_t *mat = Material_New();
d->linkMaterialToGlobalList(mat);
mat->_flags = def->flags;
mat->_isCustom = tex->flags().testFlag(Texture::Custom);
mat->_def = def;
Size2_SetWidthHeight(mat->_size, MAX_OF(0, def->width), MAX_OF(0, def->height));
mat->_envClass = S_MaterialEnvClassForUri(reinterpret_cast<struct uri_s const *>(&uri));
if(!bind)
{
newBind(scheme(uri.scheme()), uri.path(), mat);
}
else
{
bind->setMaterial(mat);
}
return mat;
}
void Materials::cache(material_t &mat, materialvariantspecification_t const &spec,
bool smooth, bool cacheGroup)
{
#ifdef __SERVER__
return;
#endif
#ifdef __CLIENT__
// Don't precache when playing demo.
if(isDedicated || playback) return;
#endif
// Already in the queue?
for(VariantCacheQueueNode* node = d->variantCacheQueue; node; node = node->next)
{
if(&mat == node->mat && &spec == node->spec) return;
}
d->pushVariantCacheQueue(mat, spec, smooth);
if(cacheGroup && Material_IsGroupAnimated(&mat))
{
// Material belongs in one or more animgroups; precache the group.
for(int i = 0; i < d->numgroups; ++i)
{
if(!d->isInAnimGroup(d->groups[i], mat)) continue;
for(int k = 0; k < d->groups[i].count; ++k)
{
cache(*d->groups[i].frames[k].material, spec, smooth, false /* do not cache groups */);
}
}
}
}
void Materials::ticker(timespan_t time)
{
#ifdef __CLIENT__
// The animation will only progress when the game is not paused.
if(clientPaused) return;
#endif
if(novideo) return;
for(MaterialListNode *node = d->materials; node; node = node->next)
{
Material_Ticker(node->mat, time);
}
if(DD_IsSharpTick())
{
d->animateAllGroups();
}
}
static Texture *findTextureByResourceUri(String nameOfScheme, de::Uri const &resourceUri)
{
if(resourceUri.isEmpty()) return 0;
try
{
return App_Textures()->scheme(nameOfScheme).findByResourceUri(resourceUri).texture();
}
catch(Textures::Scheme::NotFoundError const &)
{} // Ignore this error.
return 0;
}
static inline Texture *findDetailTextureForDef(ded_detailtexture_t const &def)
{
if(!def.detailTex) return 0;
return findTextureByResourceUri("Details", reinterpret_cast<de::Uri const &>(*def.detailTex));
}
static inline Texture *findShinyTextureForDef(ded_reflection_t const &def)
{
if(!def.shinyMap) return 0;
return findTextureByResourceUri("Reflections", reinterpret_cast<de::Uri const &>(*def.shinyMap));
}
static inline Texture *findShinyMaskTextureForDef(ded_reflection_t const &def)
{
if(!def.maskMap) return 0;
return findTextureByResourceUri("Masks", reinterpret_cast<de::Uri const &>(*def.maskMap));
}
static void updateMaterialTextureLinks(MaterialBind &mb)
{
material_t *mat = mb.material();
// We may need to need to construct and attach the info.
updateMaterialBindInfo(mb, true /* create if not present */);
if(!mat) return;
ded_detailtexture_t const *dtlDef = mb.detailTextureDef();
Material_SetDetailTexture(mat, reinterpret_cast<texture_s *>(dtlDef? findDetailTextureForDef(*dtlDef) : NULL));
Material_SetDetailStrength(mat, (dtlDef? dtlDef->strength : 0));
Material_SetDetailScale(mat, (dtlDef? dtlDef->scale : 0));
ded_reflection_t const *refDef = mb.reflectionDef();
Material_SetShinyTexture(mat, reinterpret_cast<texture_s *>(refDef? findShinyTextureForDef(*refDef) : NULL));
Material_SetShinyMaskTexture(mat, reinterpret_cast<texture_s *>(refDef? findShinyMaskTextureForDef(*refDef) : NULL));
Material_SetShinyBlendmode(mat, (refDef? refDef->blendMode : BM_ADD));
float const black[3] = { 0, 0, 0 };
Material_SetShinyMinColor(mat, (refDef? refDef->minColor : black));
Material_SetShinyStrength(mat, (refDef? refDef->shininess : 0));
}
void Materials::updateTextureLinks(MaterialBind &bind)
{
updateMaterialTextureLinks(bind);
}
MaterialSnapshot const *Materials::prepareVariant(MaterialVariant &variant, bool updateSnapshot)
{
// Acquire the snapshot we are interested in.
MaterialSnapshot *snapshot = variant.snapshot();
if(!snapshot)
{
// Time to allocate the snapshot.
snapshot = new MaterialSnapshot(variant);
variant.attachSnapshot(*snapshot);
// Update the snapshot right away.
updateSnapshot = true;
}
else if(variant.snapshotPrepareFrame() != frameCount)
{
// Time to update the snapshot.
updateSnapshot = true;
}
// We have work to do?
if(updateSnapshot)
{
variant.setSnapshotPrepareFrame(frameCount);
snapshot->update();
}
return snapshot;
}
MaterialSnapshot const *Materials::prepare(material_t &mat, materialvariantspecification_t const &spec,
bool smooth, bool updateSnapshot)
{
return prepareVariant(*chooseVariant(mat, spec, smooth, true), updateSnapshot);
}
ded_decor_t const *Materials::decorationDef(material_t *mat)
{
if(!mat) return 0;
if(!Material_Prepared(mat))
{
prepare(*mat, *Rend_MapSurfaceDiffuseMaterialSpec(), false);
}
MaterialBind *mb = d->getMaterialBindForId(Material_PrimaryBind(mat));
return mb->decorationDef();
}
ded_ptcgen_t const *Materials::ptcGenDef(material_t *mat)
{
if(!mat || isDedicated) return 0;
if(!Material_Prepared(mat))
{
prepare(*mat, *Rend_MapSurfaceDiffuseMaterialSpec(), false);
}
MaterialBind *mb = d->getMaterialBindForId(Material_PrimaryBind(mat));
return mb->ptcGenDef();
}
uint Materials::size()
{
return d->materialCount;
}
struct materialvariantspecification_s const *Materials::variantSpecificationForContext(
materialcontext_t mc, 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)
{
return d->getVariantSpecificationForContext(mc, flags, border, tClass, tMap, wrapS, wrapT,
minFilter, magFilter, anisoFilter,
mipmapped, gammaCorrection, noStretch, toAlpha);
}
static int compareVariantSpecifications(materialvariantspecification_t const &a,
materialvariantspecification_t const &b)
{
if(&a == &b) return 1;
if(a.context != b.context) return 0;
return GL_CompareTextureVariantSpecifications(a.primarySpec, b.primarySpec);
}
typedef struct {
materialvariantspecification_t const *spec;
MaterialVariant* chosen;
} choosevariantworker_parameters_t;
static int chooseVariantWorker(struct materialvariant_s *_variant, void *parameters)
{
MaterialVariant *variant = reinterpret_cast<MaterialVariant *>(_variant);
choosevariantworker_parameters_t *p = (choosevariantworker_parameters_t *) parameters;
materialvariantspecification_t const &cand = variant->spec();
DENG2_ASSERT(p);
if(compareVariantSpecifications(cand, *p->spec))
{
// This will do fine.
p->chosen = variant;
return true; // Stop iteration.
}
return false; // Continue iteration.
}
static MaterialVariant *chooseVariant2(material_t &mat, materialvariantspecification_t const &spec)
{
choosevariantworker_parameters_t params;
params.spec = &spec;
params.chosen = NULL;
Material_IterateVariants(&mat, chooseVariantWorker, ¶ms);
return params.chosen;
}
MaterialVariant *Materials::chooseVariant(material_t &mat,
materialvariantspecification_t const &spec, bool smoothed, bool canCreate)
{
MaterialVariant* variant = chooseVariant2(mat, spec);
if(!variant)
{
if(!canCreate) return 0;
variant = new MaterialVariant(mat, spec, *Material_Definition(&mat));
Material_AddVariant(&mat, reinterpret_cast<materialvariant_s *>(variant));
}
if(smoothed)
{
variant = variant->translationCurrent();
}
return variant;
}
bool Materials::isMaterialInAnimGroup(material_t *mat, int groupNum)
{
MaterialAnim *group = d->getAnimGroup(groupNum);
if(!group) return false;
return d->isInAnimGroup(*group, *mat);
}
bool Materials::hasDecorations(material_t *mat)
{
DENG2_ASSERT(mat);
if(novideo) return false;
/// @todo We should not need to prepare to determine this.
/// Nor should we need to process the group each time. Cache this decision.
if(decorationDef(mat)) return true;
if(Material_IsGroupAnimated(mat))
{
int g, i, numGroups = animGroupCount();
for(g = 0; g < numGroups; ++g)
{
MaterialAnim *group = &d->groups[g];
// Precache groups don't apply.
if(isPrecacheAnimGroup(g)) continue;
// Is this material in this group?
if(!isMaterialInAnimGroup(mat, g)) continue;
// If any material in this group has decorations then this
// material is considered to be decorated also.
for(i = 0; i < group->count; ++i)
{