/
materials.c
2190 lines (1857 loc) · 68.8 KB
/
materials.c
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.c
*\section License
* License: GPL
* Online License Link: http://www.gnu.org/licenses/gpl.html
*
*\author Copyright © 2003-2012 Jaakko Keränen <jaakko.keranen@iki.fi>
*\author Copyright © 2006-2012 Daniel Swanson <danij@dengine.net>
*
* 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
*/
/**
* Materials collection, namespaces, bindings and other management.
*/
#include "de_base.h"
#include "de_console.h"
#include "de_system.h"
#include "de_filesys.h"
#include "de_network.h"
#include "de_refresh.h"
#include "de_render.h"
#include "de_graphics.h"
#include "de_misc.h"
#include "de_audio.h" // For texture, environmental audio properties.
#include "blockset.h"
#include "texture.h"
#include "texturevariant.h"
#include "materialvariant.h"
#include "pathdirectory.h"
/// Number of materials to block-allocate.
#define MATERIALS_BLOCK_ALLOC (32)
/// Number of elements to block-allocate in the material index to materialbind map.
#define MATERIALS_BINDINGMAP_BLOCK_ALLOC (32)
typedef struct materialvariantspecificationlist_node_s {
struct materialvariantspecificationlist_node_s* next;
materialvariantspecification_t* spec;
} materialvariantspecificationlist_node_t;
typedef materialvariantspecificationlist_node_t variantspecificationlist_t;
typedef struct materiallist_node_s {
struct materiallist_node_s* next;
material_t* mat;
} materiallist_node_t;
typedef materiallist_node_t materiallist_t;
typedef struct variantcachequeue_node_s {
struct variantcachequeue_node_s* next;
material_t* mat;
const materialvariantspecification_t* spec;
boolean smooth;
} variantcachequeue_node_t;
typedef variantcachequeue_node_t variantcachequeue_t;
/**
* Info attached to a MaterialBind upon successfull preparation of the first
* derived variant of the associated Material.
*/
typedef struct materialbindinfo_s {
ded_decor_t* decorationDefs[2];
ded_detailtexture_t* detailtextureDefs[2];
ded_ptcgen_t* ptcgenDefs[2];
ded_reflection_t* reflectionDefs[2];
} materialbindinfo_t;
typedef struct materialbind_s {
/// Pointer to this binding's node in the directory.
PathDirectoryNode* _directoryNode;
/// Bound material.
material_t* _material;
/// Unique identifier for this binding.
materialid_t _id;
/// Extended info about this binding if present.
materialbindinfo_t* _info;
} materialbind_t;
/// @return Unique identifier associated with this.
materialid_t MaterialBind_Id(const materialbind_t* mb);
/// @return Material associated with this else @c NULL.
material_t* MaterialBind_Material(const materialbind_t* mb);
/**
* Change the Material associated with this binding. Note that only the
* relationship between MaterialBind and Material is updated!
*
* \post If @a material differs from that currently associated with this,
* any MaterialBindInfo presently owned by this is destroyed (it is
* now invalid).
*
* @param material New Material to associate with this.
* @return Same as @a material for caller convenience.
*/
material_t* MaterialBind_SetMaterial(materialbind_t* mb, material_t* material);
/// @return PathDirectory node associated with this.
PathDirectoryNode* MaterialBind_DirectoryNode(const materialbind_t* mb);
/// @return Extended info owned by this else @c NULL.
materialbindinfo_t* MaterialBind_Info(const materialbind_t* mb);
/**
* Attach extended info data to this. If existing info is present it is replaced.
* MaterialBind is given ownership of the info.
* @param info Extended info data to attach.
*/
void MaterialBind_AttachInfo(materialbind_t* mb, materialbindinfo_t* info);
/**
* Detach any extended info owned by this and relinquish ownership to the caller.
* @return Extended info or else @c NULL if not present.
*/
materialbindinfo_t* MaterialBind_DetachInfo(materialbind_t* mb);
/// @return Detail texture definition associated with this else @c NULL
ded_detailtexture_t* MaterialBind_DetailTextureDef(const materialbind_t* mb);
/// @return Decoration definition associated with this else @c NULL
ded_decor_t* MaterialBind_DecorationDef(const materialbind_t* mb);
/// @return Particle generator definition associated with this else @c NULL
ded_ptcgen_t* MaterialBind_PtcGenDef(const materialbind_t* mb);
/// @return Reflection definition associated with this else @c NULL
ded_reflection_t* MaterialBind_ReflectionDef(const materialbind_t* mb);
static void updateMaterialBindInfo(materialbind_t* mb, boolean canCreate);
typedef struct materialanim_frame_s {
material_t* material;
ushort tics;
ushort random;
} materialanim_frame_t;
typedef struct materialanim_s {
int id;
int flags;
int index;
int maxTimer;
int timer;
int count;
materialanim_frame_t* frames;
} materialanim_t;
static int numgroups;
static materialanim_t* groups;
D_CMD(InspectMaterial);
D_CMD(ListMaterials);
#if _DEBUG
D_CMD(PrintMaterialStats);
#endif
static void animateAnimGroups(void);
extern boolean ddMapSetup;
static boolean initedOk = false;
static variantspecificationlist_t* variantSpecs;
static variantcachequeue_t* variantCacheQueue;
/**
* The following data structures and variables are intrinsically linked and
* are inter-dependant. The scheme 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 array.
* 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 namespace.
* 5) Super-fast look up by public material identifier.
* 6) Fast look up by material name (a hashing scheme is used).
*/
static blockset_t* materialsBlockSet;
static materiallist_t* materials;
static uint materialCount;
static uint bindingCount = 0;
/// LUT which translates materialid_t to materialbind_t*. Index with materialid_t-1
static uint bindingIdMapSize = 0;
static materialbind_t** bindingIdMap = NULL;
// Material namespaces contain mappings between names and MaterialBind instances.
static PathDirectory* namespaces[MATERIALNAMESPACE_COUNT];
void Materials_Register(void)
{
C_CMD("inspectmaterial", "s", InspectMaterial)
C_CMD("listmaterials", NULL, ListMaterials)
#if _DEBUG
C_CMD("materialstats", NULL, PrintMaterialStats)
#endif
}
static void errorIfNotInited(const char* callerName)
{
if(initedOk) return;
Con_Error("%s: Materials collection is not presently initialized.", callerName);
// Unreachable. Prevents static analysers from getting rather confused, poor things.
exit(1);
}
static __inline PathDirectory* getDirectoryForNamespaceId(materialnamespaceid_t id)
{
assert(VALID_MATERIALNAMESPACEID(id));
return namespaces[id-MATERIALNAMESPACE_FIRST];
}
static materialnamespaceid_t namespaceIdForDirectory(PathDirectory* pd)
{
materialnamespaceid_t id;
assert(pd);
for(id = MATERIALNAMESPACE_FIRST; id <= MATERIALNAMESPACE_LAST; ++id)
{
if(namespaces[id-MATERIALNAMESPACE_FIRST] == pd) return id;
}
// Should never happen.
Con_Error("Materials::namespaceIdForDirectory: Failed to determine id for directory %p.", (void*)pd);
exit(1); // Unreachable.
}
static materialnamespaceid_t namespaceIdForDirectoryNode(const PathDirectoryNode* node)
{
return namespaceIdForDirectory(PathDirectoryNode_Directory(node));
}
/// @return Newly composed path for @a node. Must be released with Str_Delete()
static ddstring_t* composePathForDirectoryNode(const PathDirectoryNode* node, char delimiter)
{
return PathDirectory_ComposePath(PathDirectoryNode_Directory(node), node, Str_New(), NULL, delimiter);
}
/// @return Newly composed Uri for @a node. Must be released with Uri_Delete()
static Uri* composeUriForDirectoryNode(const PathDirectoryNode* node)
{
const ddstring_t* namespaceName = Materials_NamespaceName(namespaceIdForDirectoryNode(node));
ddstring_t* path = composePathForDirectoryNode(node, MATERIALS_PATH_DELIMITER);
Uri* uri = Uri_NewWithPath2(Str_Text(path), RC_NULL);
Uri_SetScheme(uri, Str_Text(namespaceName));
Str_Delete(path);
return uri;
}
static materialanim_t* getAnimGroup(int number)
{
if(--number < 0 || number >= numgroups) return NULL;
return &groups[number];
}
static boolean isInAnimGroup(const materialanim_t* group, const material_t* mat)
{
int i;
assert(group);
if(!mat) return false;
for(i = 0; i < group->count; ++i)
{
if(group->frames[i].material == mat)
return true;
}
return false;
}
static materialvariantspecification_t* copyVariantSpecification(
const materialvariantspecification_t* tpl)
{
materialvariantspecification_t* spec = (materialvariantspecification_t*) malloc(sizeof *spec);
if(!spec)
Con_Error("Materials::copyVariantSpecification: Failed on allocation of %lu bytes for new MaterialVariantSpecification.", (unsigned long) sizeof *spec);
memcpy(spec, tpl, sizeof *spec);
return spec;
}
static int compareVariantSpecifications(const materialvariantspecification_t* a,
const materialvariantspecification_t* b)
{
assert(a && b);
if(a == b) return 0;
if(a->context != b->context) return 1;
return GL_CompareTextureVariantSpecifications(a->primarySpec, b->primarySpec);
}
static materialvariantspecification_t* applyVariantSpecification(
materialvariantspecification_t* spec, materialcontext_t mc,
texturevariantspecification_t* primarySpec)
{
assert(spec && (mc == MC_UNKNOWN || VALID_MATERIALCONTEXT(mc)) && primarySpec);
spec->context = mc;
spec->primarySpec = primarySpec;
return spec;
}
static materialvariantspecification_t* linkVariantSpecification(
materialvariantspecification_t* spec)
{
assert(initedOk && spec);
{
materialvariantspecificationlist_node_t* node;
if(NULL == (node = (materialvariantspecificationlist_node_t*) malloc(sizeof(*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_t*)node;
return spec;
}
}
static materialvariantspecification_t* findVariantSpecification(
const materialvariantspecification_t* tpl, boolean canCreate)
{
assert(initedOk && tpl);
{
materialvariantspecificationlist_node_t* node;
for(node = variantSpecs; node; node = node->next)
{
if(!compareVariantSpecifications(node->spec, tpl))
return node->spec;
}
if(!canCreate)
return NULL;
return linkVariantSpecification(copyVariantSpecification(tpl));
}
}
static materialvariantspecification_t* getVariantSpecificationForContext(
materialcontext_t mc, int flags, byte border, int tClass,
int tMap, int wrapS, int wrapT, int minFilter, int magFilter, int anisoFilter,
boolean mipmapped, boolean gammaCorrection, boolean noStretch, boolean toAlpha)
{
static materialvariantspecification_t tpl;
assert(initedOk && (mc == MC_UNKNOWN || VALID_MATERIALCONTEXT(mc)));
{
texturevariantspecification_t* primarySpec;
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;
}
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);
}
}
static void destroyVariantSpecifications(void)
{
assert(initedOk);
while(variantSpecs)
{
materialvariantspecificationlist_node_t* next = variantSpecs->next;
free(variantSpecs->spec);
free(variantSpecs);
variantSpecs = next;
}
}
typedef struct {
const materialvariantspecification_t* spec;
materialvariant_t* chosen;
} choosevariantworker_paramaters_t;
static int chooseVariantWorker(materialvariant_t* variant, void* paramaters)
{
choosevariantworker_paramaters_t* p = (choosevariantworker_paramaters_t*) paramaters;
const materialvariantspecification_t* cand = MaterialVariant_Spec(variant);
assert(p);
if(!compareVariantSpecifications(cand, p->spec))
{
// This will do fine.
p->chosen = variant;
return true; // Stop iteration.
}
return false; // Continue iteration.
}
static materialvariant_t* chooseVariant(material_t* mat, const materialvariantspecification_t* spec)
{
choosevariantworker_paramaters_t params;
assert(mat && spec);
params.spec = spec;
params.chosen = NULL;
Material_IterateVariants(mat, chooseVariantWorker, ¶ms);
return params.chosen;
}
static materialbind_t* getMaterialBindForId(materialid_t id)
{
if(0 == id || id > bindingCount) return NULL;
return bindingIdMap[id-1];
}
static void updateMaterialBindInfo(materialbind_t* mb, boolean canCreate)
{
materialbindinfo_t* info = MaterialBind_Info(mb);
material_t* mat = MaterialBind_Material(mb);
materialid_t matId = Materials_Id(mat);
boolean isCustom = (mat? Material_IsCustom(mat) : false);
if(!info)
{
if(!canCreate) return;
// Create new info and attach to this binding.
info = (materialbindinfo_t*) malloc(sizeof *info);
if(!info)
Con_Error("MaterialBind::LinkDefinitions: Failed on allocation of %lu bytes for "
"new MaterialBindInfo.", (unsigned long) sizeof *info);
MaterialBind_AttachInfo(mb, info);
}
// Surface decorations (lights and models).
info->decorationDefs[0] = Def_GetDecoration(matId, 0, isCustom);
info->decorationDefs[1] = Def_GetDecoration(matId, 1, isCustom);
// Reflection (aka shiny surface).
info->reflectionDefs[0] = Def_GetReflection(matId, 0, isCustom);
info->reflectionDefs[1] = Def_GetReflection(matId, 1, isCustom);
// Generator (particles).
info->ptcgenDefs[0] = Def_GetGenerator(matId, 0, isCustom);
info->ptcgenDefs[1] = Def_GetGenerator(matId, 1, isCustom);
// Detail texture.
info->detailtextureDefs[0] = Def_GetDetailTex(matId, 0, isCustom);
info->detailtextureDefs[1] = Def_GetDetailTex(matId, 1, isCustom);
}
static boolean newMaterialBind(const Uri* uri, material_t* material)
{
PathDirectory* matDirectory = getDirectoryForNamespaceId(Materials_ParseNamespace(Str_Text(Uri_Scheme(uri))));
PathDirectoryNode* node;
materialbind_t* mb;
node = PathDirectory_Insert(matDirectory, Str_Text(Uri_Path(uri)), MATERIALS_PATH_DELIMITER);
// Is this a new binding?
mb = (materialbind_t*) PathDirectoryNode_UserData(node);
if(!mb)
{
// Acquire a new unique identifier for this binding.
const materialid_t bindId = ++bindingCount;
mb = (materialbind_t*) malloc(sizeof *mb);
if(!mb)
{
Con_Error("Materials::newMaterialBind: Failed on allocation of %lu bytes for new MaterialBind.",
(unsigned long) sizeof *mb);
exit(1); // Unreachable.
}
// Init the new binding.
mb->_material = NULL;
mb->_info = NULL;
mb->_directoryNode = node;
PathDirectoryNode_AttachUserData(node, mb);
mb->_id = bindId;
if(material)
{
Material_SetPrimaryBind(material, bindId);
}
// Add the new binding to the bindings index/map.
if(bindingCount > bindingIdMapSize)
{
// Allocate more memory.
bindingIdMapSize += MATERIALS_BINDINGMAP_BLOCK_ALLOC;
bindingIdMap = (materialbind_t**) realloc(bindingIdMap, sizeof *bindingIdMap * bindingIdMapSize);
if(!bindingIdMap)
Con_Error("Materials::newMaterialBind: Failed on (re)allocation of %lu bytes enlarging MaterialBind map.", (unsigned long) sizeof *bindingIdMap * bindingIdMapSize);
}
bindingIdMap[bindingCount-1] = mb; /* 1-based index */
}
// (Re)configure the binding.
mb->_material = material;
updateMaterialBindInfo(mb, false/*do not create, only update if present*/);
return true;
}
static material_t* allocMaterial(void)
{
material_t* mat = BlockSet_Allocate(materialsBlockSet);
Material_Initialize(mat);
materialCount++;
return mat;
}
/**
* Link the material into the global list of materials.
* \assume material is NOT already present in the global list.
*/
static material_t* linkMaterialToGlobalList(material_t* mat)
{
materiallist_node_t* node = (materiallist_node_t*)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 Materials_Init(void)
{
int i;
if(initedOk) return; // Already been here.
VERBOSE( Con_Message("Initializing Materials collection...\n") )
variantSpecs = NULL;
variantCacheQueue = NULL;
materialsBlockSet = BlockSet_New(sizeof(material_t), MATERIALS_BLOCK_ALLOC);
materials = NULL;
materialCount = 0;
bindingCount = 0;
bindingIdMap = NULL;
bindingIdMapSize = 0;
for(i = 0; i < MATERIALNAMESPACE_COUNT; ++i)
{
namespaces[i] = PathDirectory_New();
}
initedOk = true;
}
static int destroyVariant(materialvariant_t* variant, void* paramaters)
{
MaterialVariant_Delete(variant);
return 1; // Continue iteration.
}
static void destroyMaterials(void)
{
assert(initedOk);
while(materials)
{
materiallist_node_t* next = materials->next;
Material_Destroy(materials->mat);
free(materials);
materials = next;
}
BlockSet_Delete(materialsBlockSet);
materialsBlockSet = NULL;
materialCount = 0;
}
static int clearBinding(PathDirectoryNode* node, void* paramaters)
{
materialbind_t* mb = PathDirectoryNode_DetachUserData(node);
materialbindinfo_t* info = MaterialBind_DetachInfo(mb);
if(info)
{
free(info);
}
free(mb);
return 0; // Continue iteration.
}
static void destroyBindings(void)
{
int i;
assert(initedOk);
for(i = 0; i < MATERIALNAMESPACE_COUNT; ++i)
{
PathDirectory_Iterate(namespaces[i], PCF_NO_BRANCH, NULL, PATHDIRECTORY_NOHASH, clearBinding);
PathDirectory_Delete(namespaces[i]), namespaces[i] = NULL;
}
// Clear the binding index/map.
if(bindingIdMap)
{
free(bindingIdMap), bindingIdMap = NULL;
bindingIdMapSize = 0;
}
bindingCount = 0;
}
void Materials_Shutdown(void)
{
if(!initedOk) return;
Materials_PurgeCacheQueue();
destroyBindings();
destroyMaterials();
destroyVariantSpecifications();
initedOk = false;
}
materialnamespaceid_t Materials_ParseNamespace(const char* str)
{
if(!str || 0 == strlen(str)) return MN_ANY;
if(!stricmp(str, MN_TEXTURES_NAME)) return MN_TEXTURES;
if(!stricmp(str, MN_FLATS_NAME)) return MN_FLATS;
if(!stricmp(str, MN_SPRITES_NAME)) return MN_SPRITES;
if(!stricmp(str, MN_SYSTEM_NAME)) return MN_SYSTEM;
return MN_INVALID; // Unknown.
}
const ddstring_t* Materials_NamespaceName(materialnamespaceid_t id)
{
static const ddstring_t namespaces[1+MATERIALNAMESPACE_COUNT] = {
/* No namespace name */ { "" },
/* MN_SYSTEM */ { MN_SYSTEM_NAME },
/* MN_FLATS */ { MN_FLATS_NAME },
/* MN_TEXTURES */ { MN_TEXTURES_NAME },
/* MN_SPRITES */ { MN_SPRITES_NAME }
};
if(VALID_MATERIALNAMESPACEID(id))
return namespaces + 1 + (id - MATERIALNAMESPACE_FIRST);
return namespaces + 0;
}
materialnamespaceid_t Materials_Namespace(materialid_t id)
{
materialbind_t* bind = getMaterialBindForId(id);
if(!bind)
{
#if _DEBUG
Con_Message("Warning:Materials::Namespace: Attempted with unbound materialId #%u, returning 'any' namespace.\n", id);
#endif
return MN_ANY;
}
return namespaceIdForDirectoryNode(MaterialBind_DirectoryNode(bind));
}
static int clearBindingDefinitionLinks(const PathDirectoryNode* node, void* paramaters)
{
materialbind_t* mb = (materialbind_t*)PathDirectoryNode_UserData(node);
materialbindinfo_t* info = MaterialBind_Info(mb);
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;
}
return 0; // Continue iteration.
}
void Materials_ClearDefinitionLinks(void)
{
materiallist_node_t* node;
materialnamespaceid_t namespaceId;
errorIfNotInited("Materials::ClearDefinitionLinks");
for(node = materials; node; node = node->next)
{
material_t* mat = node->mat;
Material_SetDefinition(mat, NULL);
}
for(namespaceId = MATERIALNAMESPACE_FIRST; namespaceId <= MATERIALNAMESPACE_LAST; ++namespaceId)
{
PathDirectory* matDirectory = getDirectoryForNamespaceId(namespaceId);
PathDirectory_Iterate_Const(matDirectory, PCF_NO_BRANCH, NULL, PATHDIRECTORY_NOHASH, clearBindingDefinitionLinks);
}
}
void Materials_Rebuild(material_t* mat, ded_material_t* def)
{
uint i;
if(!initedOk || !mat || !def) return;
/// \todo We should be able to rebuild the variants.
Material_DestroyVariants(mat);
Material_SetDefinition(mat, def);
Material_SetFlags(mat, def->flags);
Material_SetWidth(mat, def->width);
Material_SetHeight(mat, def->height);
Material_SetEnvironmentClass(mat, S_MaterialEnvClassForUri(def->uri));
// Textures are updated automatically at prepare-time, so just clear them.
Material_SetDetailTexture(mat, NULL);
Material_SetShinyTexture(mat, NULL);
Material_SetShinyMaskTexture(mat, NULL);
// Update bindings.
for(i = 0; i < bindingCount; ++i)
{
materialbind_t* mb = bindingIdMap[i];
if(!mb || MaterialBind_Material(mb) != mat) continue;
updateMaterialBindInfo(mb, false /*do not create, only update if present*/);
}
}
void Materials_PurgeCacheQueue(void)
{
errorIfNotInited("Materials::PurgeCacheQueue");
while(variantCacheQueue)
{
variantcachequeue_node_t* next = variantCacheQueue->next;
free(variantCacheQueue);
variantCacheQueue = next;
}
}
void Materials_ProcessCacheQueue(void)
{
errorIfNotInited("Materials::ProcessCacheQueue");
while(variantCacheQueue)
{
variantcachequeue_node_t* node = variantCacheQueue, *next = node->next;
Materials_Prepare(node->mat, node->spec, node->smooth);
free(node);
variantCacheQueue = next;
}
}
material_t* Materials_ToMaterial(materialid_t id)
{
materialbind_t* mb;
if(!initedOk) return NULL;
mb = getMaterialBindForId(id);
if(!mb) return NULL;
return MaterialBind_Material(mb);
}
materialid_t Materials_Id(material_t* mat)
{
materialbind_t* bind;
if(!initedOk || !mat) return NOMATERIALID;
bind = getMaterialBindForId(Material_PrimaryBind(mat));
if(!bind) return NOMATERIALID;
return MaterialBind_Id(bind);
}
/**
* @defgroup validateMaterialUriFlags Validate Material Uri Flags
* @{
*/
#define VMUF_ALLOW_NAMESPACE_ANY 0x1 /// The Scheme component of the uri may be of zero-length; signifying "any namespace".
/**@}*/
/**
* @param uri Uri to be validated.
* @param flags @see validateMaterialUriFlags
* @param quiet @c true= Do not output validation remarks to the log.
* @return @c true if @a Uri passes validation.
*/
static boolean validateMaterialUri2(const Uri* uri, int flags, boolean quiet)
{
materialnamespaceid_t namespaceId;
if(!uri || Str_IsEmpty(Uri_Path(uri)))
{
if(!quiet)
{
ddstring_t* uriStr = Uri_ToString(uri);
Con_Message("Invalid path '%s' in Material uri \"%s\".\n", Str_Text(Uri_Path(uri)), Str_Text(uriStr));
Str_Delete(uriStr);
}
return false;
}
namespaceId = Materials_ParseNamespace(Str_Text(Uri_Scheme(uri)));
if(!((flags & VMUF_ALLOW_NAMESPACE_ANY) && namespaceId == MN_ANY) &&
!VALID_MATERIALNAMESPACEID(namespaceId))
{
if(!quiet)
{
ddstring_t* uriStr = Uri_ToString(uri);
Con_Message("Unknown namespace '%s' in Material uri \"%s\".\n", Str_Text(Uri_Scheme(uri)), Str_Text(uriStr));
Str_Delete(uriStr);
}
return false;
}
return true;
}
static boolean validateMaterialUri(const Uri* uri, int flags)
{
return validateMaterialUri2(uri, flags, false);
}
/**
* Given a directory and path, search the Materials collection for a match.
*
* @param directory Namespace-specific PathDirectory to search in.
* @param path Path of the material to search for.
* @return Found Material else @c NULL
*/
static materialbind_t* findMaterialBindForPath(PathDirectory* matDirectory, const char* path)
{
PathDirectoryNode* node = PathDirectory_Find(matDirectory,
PCF_NO_BRANCH|PCF_MATCH_FULL, path, MATERIALS_PATH_DELIMITER);
if(node)
{
return (materialbind_t*) PathDirectoryNode_UserData(node);
}
return NULL; // Not found.
}
/// \assume @a uri has already been validated and is well-formed.
static materialbind_t* findMaterialBindForUri(const Uri* uri)
{
materialnamespaceid_t namespaceId = Materials_ParseNamespace(Str_Text(Uri_Scheme(uri)));
const char* path = Str_Text(Uri_Path(uri));
materialbind_t* bind = NULL;
if(namespaceId != MN_ANY)
{
// Caller wants a material in a specific namespace.
bind = findMaterialBindForPath(getDirectoryForNamespaceId(namespaceId), path);
}
else
{
// Caller does not care which namespace.
// Check for the material in these namespaces in priority order.
static const materialnamespaceid_t order[] = {
MN_SPRITES, MN_TEXTURES, MN_FLATS, MN_ANY
};
int n = 0;
do
{
bind = findMaterialBindForPath(getDirectoryForNamespaceId(order[n]), path);
} while(!bind && order[++n] != MN_ANY);
}
return bind;
}
materialid_t Materials_ResolveUri2(const Uri* uri, boolean quiet)
{
materialbind_t* bind;
if(!initedOk || !uri) return NOMATERIALID;
if(!validateMaterialUri2(uri, VMUF_ALLOW_NAMESPACE_ANY, true /*quiet please*/))
{
#if _DEBUG
ddstring_t* uriStr = Uri_ToString(uri);
Con_Message("Warning:Materials::ResolveUri: Uri \"%s\" failed to validate, returing NULL.\n", Str_Text(uriStr));
Str_Delete(uriStr);
#endif
return NOMATERIALID;
}
// Perform the search.
bind = findMaterialBindForUri(uri);
if(bind) return MaterialBind_Id(bind);
// Not found.
if(!quiet && !ddMapSetup) // Do not announce during map setup.
{
ddstring_t* path = Uri_ToString(uri);
Con_Message("Materials::ResolveUri: \"%s\" not found!\n", Str_Text(path));
Str_Delete(path);
}
return NOMATERIALID;
}
/// \note Part of the Doomsday public API.
materialid_t Materials_ResolveUri(const Uri* uri)
{
return Materials_ResolveUri2(uri, !(verbose >= 1)/*log warnings if verbose*/);
}
materialid_t Materials_ResolveUriCString2(const char* path, boolean quiet)
{
if(path && path[0])
{
Uri* uri = Uri_NewWithPath2(path, RC_NULL);
materialid_t matId = Materials_ResolveUri2(uri, quiet);
Uri_Delete(uri);
return matId;
}
return NOMATERIALID;
}
/// \note Part of the Doomsday public API.
materialid_t Materials_ResolveUriCString(const char* path)
{
return Materials_ResolveUriCString2(path, !(verbose >= 1)/*log warnings if verbose*/);
}
ddstring_t* Materials_ComposePath(materialid_t id)
{
materialbind_t* bind = getMaterialBindForId(id);
if(!bind)
{
#if _DEBUG
Con_Message("Warning:Materials::ComposePath: Attempted with unbound materialId #%u, returning null-object.\n", id);
#endif
return Str_New();
}
return composePathForDirectoryNode(MaterialBind_DirectoryNode(bind), MATERIALS_PATH_DELIMITER);
}
/// \note Part of the Doomsday public API.
Uri* Materials_ComposeUri(materialid_t id)
{
materialbind_t* bind = getMaterialBindForId(id);
if(!bind)
{
#if _DEBUG
Con_Message("Warning:Materials::ComposeUri: Attempted with unbound materialId #%u, returning null-object.\n", id);
#endif
return Uri_New();
}
return composeUriForDirectoryNode(MaterialBind_DirectoryNode(bind));
}
material_t* Materials_CreateFromDef(ded_material_t* def)
{
const Uri* uri = def->uri;
materialbind_t* bind;
textureid_t texId;
material_t* mat;
assert(def);
if(!initedOk) return NULL;
// We require a properly formed uri.
if(!validateMaterialUri2(uri, 0, (verbose >= 1)))
{
ddstring_t* uriStr = Uri_ToString(uri);
Con_Message("Warning: Failed creating Material \"%s\" from definition %p, ignoring.\n", Str_Text(uriStr), (void*)def);
Str_Delete(uriStr);
return NULL;
}
// Have we already created a material for this?
bind = findMaterialBindForUri(uri);
if(bind && MaterialBind_Material(bind))
{
#if _DEBUG
ddstring_t* path = Uri_ToString(uri);
Con_Message("Warning:Materials::CreateFromDef: A Material with uri \"%s\" already exists, returning existing.\n", Str_Text(path));
Str_Delete(path);
#endif
return MaterialBind_Material(bind);
}
// Ensure the primary layer has a valid texture reference.
texId = NOTEXTUREID;
if(def->layers[0].stageCount.num > 0)
{
const ded_material_layer_t* l = &def->layers[0];
if(l->stages[0].texture) // Not unused.
{
texId = Textures_ResolveUri2(l->stages[0].texture, true/*quiet please*/);
if(texId == NOTEXTUREID)
{
ddstring_t* materialPath = Uri_ToString(def->uri);
ddstring_t* texturePath = Uri_ToString(l->stages[0].texture);
Con_Message("Warning: Unknown texture \"%s\" in Material \"%s\" (layer %i stage %i).\n", Str_Text(texturePath), Str_Text(materialPath), 0, 0);