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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
|
#include "StarAssets.hpp"
#include "StarAssetPath.hpp"
#include "StarFile.hpp"
#include "StarTime.hpp"
#include "StarDirectoryAssetSource.hpp"
#include "StarPackedAssetSource.hpp"
#include "StarMemoryAssetSource.hpp"
#include "StarJsonBuilder.hpp"
#include "StarJsonExtra.hpp"
#include "StarJsonPatch.hpp"
#include "StarIterator.hpp"
#include "StarImageProcessing.hpp"
#include "StarLogging.hpp"
#include "StarRandom.hpp"
#include "StarFont.hpp"
#include "StarAudio.hpp"
#include "StarCasting.hpp"
#include "StarLexicalCast.hpp"
#include "StarSha256.hpp"
#include "StarDataStreamDevices.hpp"
#include "StarLua.hpp"
#include "StarImageLuaBindings.hpp"
#include "StarUtilityLuaBindings.hpp"
namespace Star {
static void validateBasePath(std::string_view const& basePath) {
if (basePath.empty() || basePath[0] != '/')
throw AssetException(strf("Path '{}' must be absolute", basePath));
bool first = true;
bool slashed = true;
bool dotted = false;
for (auto c : basePath) {
if (c == '/') {
if (!first) {
if (slashed)
throw AssetException(strf("Path '{}' contains consecutive //, not allowed", basePath));
else if (dotted)
throw AssetException(strf("Path '{}' '.' and '..' not allowed", basePath));
}
slashed = true;
dotted = false;
} else if (c == ':') {
if (slashed)
throw AssetException(strf("Path '{}' has ':' after directory", basePath));
break;
} else if (c == '?') {
if (slashed)
throw AssetException(strf("Path '{}' has '?' after directory", basePath));
break;
} else {
slashed = false;
dotted = c == '.';
}
first = false;
}
if (slashed)
throw AssetException(strf("Path '{}' cannot be a file", basePath));
}
static void validatePath(AssetPath const& components, bool canContainSubPath, bool canContainDirectives) {
validateBasePath(components.basePath.utf8());
if (!canContainSubPath && components.subPath)
throw AssetException::format("Path '{}' cannot contain sub-path", components);
if (!canContainDirectives && !components.directives.empty())
throw AssetException::format("Path '{}' cannot contain directives", components);
}
static void validatePath(StringView path, bool canContainSubPath, bool canContainDirectives) {
std::string_view const& str = path.utf8();
size_t end = str.find_first_of(":?");
auto basePath = str.substr(0, end);
validateBasePath(basePath);
bool subPath = false;
if (str[end] == ':') {
size_t beg = end + 1;
if (beg != str.size()) {
end = str.find_first_of('?', beg);
if (end == NPos && beg + 1 != str.size())
subPath = true;
else if (size_t len = end - beg)
subPath = true;
}
}
if (subPath)
throw AssetException::format("Path '{}' cannot contain sub-path", path);
if (end != NPos && str[end] == '?' && !canContainDirectives)
throw AssetException::format("Path '{}' cannot contain directives", path);
}
Maybe<RectU> FramesSpecification::getRect(String const& frame) const {
if (auto alias = aliases.ptr(frame)) {
return frames.get(*alias);
} else {
return frames.maybe(frame);
}
}
Json FramesSpecification::toJson() const {
return JsonObject{
{"aliases", jsonFromMap(aliases)},
{"frames", jsonFromMapV(frames, jsonFromRectU)},
{"file", framesFile}
};
}
Assets::Assets(Settings settings, StringList assetSources) {
const char* AssetsPatchSuffix = ".patch";
const char* AssetsPatchListSuffix = ".patchlist";
const char* AssetsLuaPatchSuffix = ".patch.lua";
m_settings = std::move(settings);
m_stopThreads = false;
m_assetSources = std::move(assetSources);
auto luaEngine = LuaEngine::create();
m_luaEngine = luaEngine;
auto pushGlobalContext = [&luaEngine](String const& name, LuaCallbacks && callbacks) {
auto table = luaEngine->createTable();
for (auto const& p : callbacks.callbacks())
table.set(p.first, luaEngine->createWrappedFunction(p.second));
luaEngine->setGlobal(name, table);
};
auto makeBaseAssetCallbacks = [this]() {
LuaCallbacks callbacks;
callbacks.registerCallbackWithSignature<StringSet, String>("byExtension", bind(&Assets::scanExtension, this, _1));
callbacks.registerCallbackWithSignature<Json, String>("json", bind(&Assets::json, this, _1));
callbacks.registerCallbackWithSignature<bool, String>("exists", bind(&Assets::assetExists, this, _1));
callbacks.registerCallback("sourcePaths", [this](LuaEngine& engine, Maybe<bool> withMetaData) -> LuaTable {
auto assetSources = this->assetSources();
auto table = engine.createTable(assetSources.size(), 0);
if (withMetaData.value()) {
for (auto& assetSource : assetSources)
table.set(assetSource, this->assetSourceMetadata(assetSource));
}
else {
size_t i = 0;
for (auto& assetSource : assetSources)
table.set(++i, assetSource);
}
return table;
});
callbacks.registerCallback("origin", [this](String const& path) -> Maybe<String> {
if (auto descriptor = this->assetDescriptor(path))
return this->assetSourcePath(descriptor->source);
return {};
});
callbacks.registerCallback("bytes", [this](String const& path) -> String {
auto assetBytes = bytes(path);
return String(assetBytes->ptr(), assetBytes->size());
});
callbacks.registerCallback("image", [this](String const& path) -> Image {
auto assetImage = image(path);
if (assetImage->bytesPerPixel() == 3)
return assetImage->convert(PixelFormat::RGBA32);
else
return *assetImage;
});
callbacks.registerCallback("frames", [this](String const& path) -> Json {
if (auto frames = imageFrames(path))
return frames->toJson();
return Json();
});
callbacks.registerCallback("scan", [this](Maybe<String> const& a, Maybe<String> const& b) -> StringList {
return b ? scan(a.value(), *b) : scan(a.value());
});
return callbacks;
};
pushGlobalContext("sb", LuaBindings::makeUtilityCallbacks());
pushGlobalContext("assets", makeBaseAssetCallbacks());
auto decorateLuaContext = [&](LuaContext& context, MemoryAssetSourcePtr newFiles) {
if (newFiles) {
// re-add the assets callbacks with more functions
context.remove("assets");
auto callbacks = makeBaseAssetCallbacks();
callbacks.registerCallback("add", [newFiles](LuaEngine& engine, String const& path, LuaValue const& data) {
ByteArray bytes;
if (auto str = engine.luaMaybeTo<String>(data))
bytes = ByteArray(str->utf8Ptr(), str->utf8Size());
else if (auto image = engine.luaMaybeTo<Image>(data)) {
newFiles->set(path, std::move(*image));
return;
} else {
auto json = engine.luaTo<Json>(data).repr();
bytes = ByteArray(json.utf8Ptr(), json.utf8Size());
}
newFiles->set(path, bytes);
});
callbacks.registerCallback("patch", [this, newFiles](String const& path, String const& patchPath) -> bool {
if (auto file = m_files.ptr(path)) {
if (newFiles->contains(patchPath)) {
file->patchSources.append(make_pair(patchPath, newFiles));
return true;
} else {
if (auto asset = m_files.ptr(patchPath)) {
file->patchSources.append(make_pair(patchPath, asset->source));
return true;
}
}
}
return false;
});
callbacks.registerCallback("erase", [this](String const& path) -> bool {
bool erased = m_files.erase(path);
if (erased)
m_filesByExtension[AssetPath::extension(path).toLower()].erase(path);
return erased;
});
context.setCallbacks("assets", callbacks);
}
};
auto addSource = [&](String const& sourcePath, AssetSourcePtr source) {
m_assetSourcePaths.add(sourcePath, source);
for (auto const& filename : source->assetPaths()) {
if (filename.contains(AssetsPatchSuffix, String::CaseInsensitive)) {
if (filename.endsWith(AssetsPatchSuffix, String::CaseInsensitive)) {
auto targetPatchFile = filename.substr(0, filename.size() - strlen(AssetsPatchSuffix));
if (auto p = m_files.ptr(targetPatchFile))
p->patchSources.append({filename, source});
} else if (filename.endsWith(AssetsLuaPatchSuffix, String::CaseInsensitive)) {
auto targetPatchFile = filename.substr(0, filename.size() - strlen(AssetsLuaPatchSuffix));
if (auto p = m_files.ptr(targetPatchFile))
p->patchSources.append({filename, source});
} else if (filename.endsWith(AssetsPatchListSuffix, String::CaseInsensitive)) {
auto stream = source->read(filename);
size_t patchIndex = 0;
for (auto const& patchPair : inputUtf8Json(stream.begin(), stream.end(), JsonParseType::Top).iterateArray()) {
auto patches = patchPair.getArray("patches");
for (auto& path : patchPair.getArray("paths")) {
if (auto p = m_files.ptr(path.toString())) {
for (size_t i = 0; i != patches.size(); ++i) {
auto& patch = patches[i];
if (patch.isType(Json::Type::String))
p->patchSources.append({patch.toString(), source});
else
p->patchSources.append({strf("{}:[{}].patches[{}]", filename, patchIndex, i), source});
}
}
}
patchIndex++;
}
} else {
for (int i = 0; i < 10; i++) {
if (filename.endsWith(AssetsPatchSuffix + toString(i), String::CaseInsensitive)) {
auto targetPatchFile = filename.substr(0, filename.size() - strlen(AssetsPatchSuffix) + 1);
if (auto p = m_files.ptr(targetPatchFile))
p->patchSources.append({filename, source});
break;
}
}
}
}
auto& descriptor = m_files[filename];
descriptor.sourceName = filename;
descriptor.source = source;
m_filesByExtension[AssetPath::extension(filename).toLower()].insert(filename);
}
};
auto runLoadScripts = [&](String const& groupName, String const& sourcePath, AssetSourcePtr source) {
auto metadata = source->metadata();
if (auto scripts = metadata.ptr("scripts")) {
if (auto scriptGroup = scripts->optArray(groupName)) {
auto memoryName = strf("{}::{}", metadata.value("name", File::baseName(sourcePath)), groupName);
JsonObject memoryMetadata{ {"name", memoryName} };
auto memoryAssets = make_shared<MemoryAssetSource>(memoryName, memoryMetadata);
Logger::info("Running {} scripts {}", groupName, *scriptGroup);
try {
auto context = luaEngine->createContext();
decorateLuaContext(context, memoryAssets);
for (auto& jPath : *scriptGroup) {
auto path = jPath.toString();
auto script = source->read(path);
context.load(script, path);
}
} catch (LuaException const& e) {
Logger::error("Exception while running {} scripts from asset source '{}': {}", groupName, sourcePath, e.what());
}
if (!memoryAssets->empty())
addSource(strf("{}::{}", sourcePath, groupName), memoryAssets);
}
}
// clear any caching that may have been trigered by load scripts as they may no longer be valid
m_framesSpecifications.clear();
m_assetsCache.clear();
};
List<pair<String, AssetSourcePtr>> sources;
for (auto& sourcePath : m_assetSources) {
Logger::info("Loading assets from: '{}'", sourcePath);
AssetSourcePtr source;
if (File::isDirectory(sourcePath))
source = std::make_shared<DirectoryAssetSource>(sourcePath, m_settings.pathIgnore);
else
source = std::make_shared<PackedAssetSource>(sourcePath);
addSource(sourcePath, source);
sources.append(make_pair(sourcePath, source));
runLoadScripts("onLoad", sourcePath, source);
}
for (auto& pair : sources)
runLoadScripts("postLoad", pair.first, pair.second);
Sha256Hasher digest;
for (auto const& assetPath : m_files.keys().transformed([](String const& s) {
return s.toLower();
}).sorted()) {
bool digestFile = true;
for (auto const& pattern : m_settings.digestIgnore) {
if (assetPath.regexMatch(pattern, false, false)) {
digestFile = false;
break;
}
}
auto const& descriptor = m_files.get(assetPath);
if (digestFile) {
digest.push(assetPath);
digest.push(DataStreamBuffer::serialize(descriptor.source->open(descriptor.sourceName)->size()));
for (auto const& pair : descriptor.patchSources)
digest.push(DataStreamBuffer::serialize(pair.second->open(AssetPath::removeSubPath(pair.first))->size()));
}
}
m_digest = digest.compute();
int workerPoolSize = m_settings.workerPoolSize;
for (int i = 0; i < workerPoolSize; i++)
m_workerThreads.append(Thread::invoke("Assets::workerMain", mem_fn(&Assets::workerMain), this));
// preload.config contains an array of files which will be loaded and then told to persist
Json preload = json("/preload.config");
Logger::info("Preloading assets");
for (auto script : preload.iterateArray()) {
auto type = AssetTypeNames.getLeft(script.getString("type"));
auto path = script.getString("path");
auto components = AssetPath::split(path);
validatePath(components, type == AssetType::Json || type == AssetType::Image, type == AssetType::Image);
auto asset = getAsset(AssetId{type, std::move(components)});
// make this asset never unload
asset->forcePersist = true;
}
}
Assets::~Assets() {
m_stopThreads = true;
{
// Should lock associated mutex to prevent loss of wakeups,
MutexLocker locker(m_assetsMutex);
// Notify all worker threads to allow them to stop
m_assetsQueued.broadcast();
}
// Join them all
m_workerThreads.clear();
}
void Assets::hotReload() const {
MutexLocker assetsLocker(m_assetsMutex);
m_assetsCache.clear();
m_queue.clear();
m_framesSpecifications.clear();
}
StringList Assets::assetSources() const {
MutexLocker assetsLocker(m_assetsMutex);
return m_assetSources;
}
JsonObject Assets::assetSourceMetadata(String const& sourceName) const {
MutexLocker assetsLocker(m_assetsMutex);
return m_assetSourcePaths.getRight(sourceName)->metadata();
}
ByteArray Assets::digest() const {
MutexLocker assetsLocker(m_assetsMutex);
return m_digest;
}
bool Assets::assetExists(String const& path) const {
MutexLocker assetsLocker(m_assetsMutex);
return m_files.contains(path);
}
Maybe<Assets::AssetFileDescriptor> Assets::assetDescriptor(String const& path) const {
MutexLocker assetsLocker(m_assetsMutex);
return m_files.maybe(path);
}
String Assets::assetSource(String const& path) const {
MutexLocker assetsLocker(m_assetsMutex);
if (auto p = m_files.ptr(path))
return m_assetSourcePaths.getLeft(p->source);
throw AssetException(strf("No such asset '{}'", path));
}
Maybe<String> Assets::assetSourcePath(AssetSourcePtr const& source) const {
MutexLocker assetsLocker(m_assetsMutex);
return m_assetSourcePaths.maybeLeft(source);
}
StringList Assets::scan(String const& suffix) const {
if (suffix.beginsWith(".") && !suffix.substr(1).hasChar('.')) {
return scanExtension(suffix).values();
} else if (suffix.empty()) {
return m_files.keys();
} else {
StringList result;
for (auto const& fileEntry : m_files) {
String const& file = fileEntry.first;
if (file.endsWith(suffix, String::CaseInsensitive))
result.append(file);
}
return result;
}
}
StringList Assets::scan(String const& prefix, String const& suffix) const {
StringList result;
if (suffix.beginsWith(".") && !suffix.substr(1).hasChar('.')) {
auto& filesWithExtension = scanExtension(suffix);
for (auto const& file : filesWithExtension) {
if (file.beginsWith(prefix, String::CaseInsensitive))
result.append(file);
}
} else {
for (auto const& fileEntry : m_files) {
String const& file = fileEntry.first;
if (file.beginsWith(prefix, String::CaseInsensitive) && file.endsWith(suffix, String::CaseInsensitive))
result.append(file);
}
}
return result;
}
const CaseInsensitiveStringSet NullExtensionScan;
CaseInsensitiveStringSet const& Assets::scanExtension(String const& extension) const {
auto find = m_filesByExtension.find(extension.beginsWith(".") ? extension.substr(1) : extension);
return find != m_filesByExtension.end() ? find->second : NullExtensionScan;
}
Json Assets::json(String const& path) const {
auto components = AssetPath::split(path);
validatePath(components, true, false);
return as<JsonData>(getAsset(AssetId{AssetType::Json, std::move(components)}))->json;
}
Json Assets::fetchJson(Json const& v, String const& dir) const {
if (v.isType(Json::Type::String))
return Assets::json(AssetPath::relativeTo(dir, v.toString()));
else
return v;
}
void Assets::queueJsons(StringList const& paths) const {
queueAssets(paths.transformed([](String const& path) {
auto components = AssetPath::split(path);
validatePath(components, true, false);
return AssetId{AssetType::Json, {components.basePath, {}, {}}};
}));
}
void Assets::queueJsons(CaseInsensitiveStringSet const& paths) const {
MutexLocker assetsLocker(m_assetsMutex);
for (String const& path : paths) {
auto components = AssetPath::split(path);
validatePath(components, true, false);
queueAsset(AssetId{AssetType::Json, {components.basePath, {}, {}}});
};
}
ImageConstPtr Assets::image(AssetPath const& path) const {
return as<ImageData>(getAsset(AssetId{AssetType::Image, path}))->image;
}
void Assets::queueImages(StringList const& paths) const {
queueAssets(paths.transformed([](String const& path) {
auto components = AssetPath::split(path);
validatePath(components, true, true);
return AssetId{AssetType::Image, std::move(components)};
}));
}
void Assets::queueImages(CaseInsensitiveStringSet const& paths) const {
MutexLocker assetsLocker(m_assetsMutex);
for (String const& path : paths) {
auto components = AssetPath::split(path);
validatePath(components, true, true);
queueAsset(AssetId{AssetType::Image, std::move(components)});
};
}
ImageConstPtr Assets::tryImage(AssetPath const& path) const {
validatePath(path, true, true);
if (auto imageData = as<ImageData>(tryAsset(AssetId{AssetType::Image, path})))
return imageData->image;
else
return {};
}
FramesSpecificationConstPtr Assets::imageFrames(String const& path) const {
auto components = AssetPath::split(path);
validatePath(components, false, false);
MutexLocker assetsLocker(m_assetsMutex);
return bestFramesSpecification(path);
}
AudioConstPtr Assets::audio(String const& path) const {
auto components = AssetPath::split(path);
validatePath(components, false, false);
return as<AudioData>(getAsset(AssetId{AssetType::Audio, std::move(components)}))->audio;
}
void Assets::queueAudios(StringList const& paths) const {
queueAssets(paths.transformed([](String const& path) {
auto components = AssetPath::split(path);
validatePath(components, false, false);
return AssetId{AssetType::Audio, std::move(components)};
}));
}
void Assets::queueAudios(CaseInsensitiveStringSet const& paths) const {
MutexLocker assetsLocker(m_assetsMutex);
for (String const& path : paths) {
auto components = AssetPath::split(path);
validatePath(components, false, true);
queueAsset(AssetId{AssetType::Audio, std::move(components)});
};
}
AudioConstPtr Assets::tryAudio(String const& path) const {
auto components = AssetPath::split(path);
validatePath(components, false, false);
if (auto audioData = as<AudioData>(tryAsset(AssetId{AssetType::Audio, std::move(components)})))
return audioData->audio;
else
return {};
}
FontConstPtr Assets::font(String const& path) const {
auto components = AssetPath::split(path);
validatePath(components, false, false);
return as<FontData>(getAsset(AssetId{AssetType::Font, std::move(components)}))->font;
}
ByteArrayConstPtr Assets::bytes(String const& path) const {
auto components = AssetPath::split(path);
validatePath(components, false, false);
return as<BytesData>(getAsset(AssetId{AssetType::Bytes, std::move(components)}))->bytes;
}
IODevicePtr Assets::openFile(String const& path) const {
return open(path);
}
void Assets::clearCache() {
MutexLocker assetsLocker(m_assetsMutex);
// Clear all assets that are not queued or broken.
auto it = makeSMutableMapIterator(m_assetsCache);
while (it.hasNext()) {
auto const& pair = it.next();
// Don't clean up queued, persistent, or broken assets.
if (pair.second && !pair.second->shouldPersist() && !m_queue.contains(pair.first))
it.remove();
}
}
void Assets::cleanup() {
MutexLocker assetsLocker(m_assetsMutex);
double time = Time::monotonicTime();
auto it = makeSMutableMapIterator(m_assetsCache);
while (it.hasNext()) {
auto pair = it.next();
// Don't clean up broken assets or queued assets.
if (pair.second && !m_queue.contains(pair.first)) {
double liveTime = time - pair.second->time;
if (liveTime > m_settings.assetTimeToLive) {
// If the asset should persist, just refresh the access time.
if (pair.second->shouldPersist())
pair.second->time = time;
else
it.remove();
}
}
}
}
bool Assets::AssetId::operator==(AssetId const& assetId) const {
return tie(type, path) == tie(assetId.type, assetId.path);
}
size_t Assets::AssetIdHash::operator()(AssetId const& id) const {
return hashOf(id.type, id.path.basePath, id.path.subPath, id.path.directives);
}
bool Assets::JsonData::shouldPersist() const {
return forcePersist || !json.unique();
}
bool Assets::ImageData::shouldPersist() const {
return forcePersist || (!alias && !image.unique());
}
bool Assets::AudioData::shouldPersist() const {
return forcePersist || !audio.unique();
}
bool Assets::FontData::shouldPersist() const {
return forcePersist || !font.unique();
}
bool Assets::BytesData::shouldPersist() const {
return forcePersist || !bytes.unique();
}
FramesSpecification Assets::parseFramesSpecification(Json const& frameConfig, String path) {
FramesSpecification framesSpecification;
framesSpecification.framesFile = std::move(path);
if (frameConfig.contains("frameList")) {
for (auto const& pair : frameConfig.get("frameList").toObject()) {
String frameName = pair.first;
RectU rect = RectU(jsonToRectI(pair.second));
if (rect.isEmpty())
throw AssetException(
strf("Empty rect in frame specification in image {} frame {}", framesSpecification.framesFile, frameName));
else
framesSpecification.frames[frameName] = rect;
}
}
if (frameConfig.contains("frameGrid")) {
auto grid = frameConfig.get("frameGrid").toObject();
Vec2U begin(jsonToVec2I(grid.value("begin", jsonFromVec2I(Vec2I()))));
Vec2U size(jsonToVec2I(grid.get("size")));
Vec2U dimensions(jsonToVec2I(grid.get("dimensions")));
if (dimensions[0] == 0 || dimensions[1] == 0)
throw AssetException(strf("Image {} \"dimensions\" in frameGrid cannot be zero", framesSpecification.framesFile));
if (grid.contains("names")) {
auto nameList = grid.get("names");
for (size_t y = 0; y < nameList.size(); ++y) {
if (y >= dimensions[1])
throw AssetException(strf("Image {} row {} is out of bounds for y-dimension {}",
framesSpecification.framesFile,
y + 1,
dimensions[1]));
auto rowList = nameList.get(y);
if (rowList.isNull())
continue;
for (unsigned x = 0; x < rowList.size(); ++x) {
if (x >= dimensions[0])
throw AssetException(strf("Image {} column {} is out of bounds for x-dimension {}",
framesSpecification.framesFile,
x + 1,
dimensions[0]));
auto frame = rowList.get(x);
if (frame.isNull())
continue;
auto frameName = frame.toString();
if (!frameName.empty())
framesSpecification.frames[frameName] =
RectU::withSize(Vec2U(begin[0] + x * size[0], begin[1] + y * size[1]), size);
}
}
} else {
// If "names" not specified, use auto naming algorithm
for (size_t y = 0; y < dimensions[1]; ++y)
for (size_t x = 0; x < dimensions[0]; ++x)
framesSpecification.frames[toString(y * dimensions[0] + x)] =
RectU::withSize(Vec2U(begin[0] + x * size[0], begin[1] + y * size[1]), size);
}
}
if (auto aliasesConfig = frameConfig.opt("aliases")) {
auto aliases = aliasesConfig->objectPtr();
for (auto const& pair : *aliases) {
String const& key = pair.first;
String value = pair.second.toString();
// Resolve aliases to aliases by checking to see if the alias value in
// the alias map itself. Don't do this more than aliases.size() times to
// avoid infinite cycles.
for (size_t i = 0; i <= aliases->size(); ++i) {
auto it = aliases->find(value);
if (it != aliases->end()) {
if (i == aliases->size())
throw AssetException(strf("Infinite alias loop detected for alias '{}'", key));
value = it->second.toString();
} else {
break;
}
}
if (!framesSpecification.frames.contains(value))
throw AssetException(strf("No such frame '{}' found for alias '{}'", value, key));
framesSpecification.aliases[key] = std::move(value);
}
}
return framesSpecification;
}
void Assets::queueAssets(List<AssetId> const& assetIds) const {
MutexLocker assetsLocker(m_assetsMutex);
for (auto const& id : assetIds)
queueAsset(id);
}
void Assets::queueAsset(AssetId const& assetId) const {
auto i = m_assetsCache.find(assetId);
if (i != m_assetsCache.end()) {
if (i->second)
freshen(i->second);
} else {
auto j = m_queue.find(assetId);
if (j == m_queue.end()) {
m_queue[assetId] = QueuePriority::Load;
m_assetsQueued.signal();
}
}
}
shared_ptr<Assets::AssetData> Assets::tryAsset(AssetId const& id) const {
MutexLocker assetsLocker(m_assetsMutex);
auto i = m_assetsCache.find(id);
if (i != m_assetsCache.end()) {
if (i->second) {
freshen(i->second);
return i->second;
} else {
throw AssetException::format("Error loading asset {}", id.path);
}
} else {
auto j = m_queue.find(id);
if (j == m_queue.end()) {
m_queue[id] = QueuePriority::Load;
m_assetsQueued.signal();
}
return {};
}
}
shared_ptr<Assets::AssetData> Assets::getAsset(AssetId const& id) const {
MutexLocker assetsLocker(m_assetsMutex);
while (true) {
auto j = m_assetsCache.find(id);
if (j != m_assetsCache.end()) {
if (j->second) {
auto asset = j->second;
freshen(asset);
return asset;
} else {
throw AssetException::format("Error loading asset {}", id.path);
}
} else {
// Try to load the asset in-thread, if we cannot, then the asset has been
// queued so wait for a worker thread to finish it.
if (!doLoad(id))
m_assetsDone.wait(m_assetsMutex);
}
}
}
void Assets::workerMain() {
while (true) {
if (m_stopThreads)
break;
{
RecursiveMutexLocker luaLocker(m_luaMutex);
as<LuaEngine>(m_luaEngine.get())->collectGarbage();
}
MutexLocker assetsLocker(m_assetsMutex);
AssetId assetId;
QueuePriority queuePriority = QueuePriority::None;
// Find the highest priority queue entry
for (auto const& pair : m_queue) {
if (pair.second == QueuePriority::Load || pair.second == QueuePriority::PostProcess) {
assetId = pair.first;
queuePriority = pair.second;
if (pair.second == QueuePriority::Load)
break;
}
}
if (queuePriority != QueuePriority::Load && queuePriority != QueuePriority::PostProcess) {
// Nothing in the queue that needs work
m_assetsQueued.wait(m_assetsMutex);
continue;
}
bool workIsBlocking;
if (queuePriority == QueuePriority::PostProcess)
workIsBlocking = !doPost(assetId);
else
workIsBlocking = !doLoad(assetId);
if (workIsBlocking) {
// We are blocking on some sort of busy asset, so need to wait on
// something to complete here, rather than spinning and burning cpu.
m_assetsDone.wait(m_assetsMutex);
continue;
}
// After processing an asset, unlock the main asset mutex and yield so we
// don't starve other threads.
assetsLocker.unlock();
Thread::yield();
}
}
template <typename Function>
decltype(auto) Assets::unlockDuring(Function f) const {
m_assetsMutex.unlock();
try {
auto r = f();
m_assetsMutex.lock();
return r;
} catch (...) {
m_assetsMutex.lock();
throw;
}
}
FramesSpecificationConstPtr Assets::bestFramesSpecification(String const& image) const {
if (auto framesSpecification = m_framesSpecifications.maybe(image)) {
return *framesSpecification;
}
String framesFile;
if (auto bestFramesFile = m_bestFramesFiles.maybe(image)) {
framesFile = *bestFramesFile;
} else {
String searchPath = AssetPath::directory(image);
String filePrefix = AssetPath::filename(image);
filePrefix = filePrefix.substr(0, filePrefix.findLast('.'));
auto subdir = [](String const& dir) -> String {
auto dirsplit = dir.substr(0, dir.size() - 1).rsplit("/", 1);
if (dirsplit.size() < 2)
return "";
else
return dirsplit[0] + "/";
};
Maybe<String> foundFramesFile;
// look for <full-path-minus-extension>.frames or default.frames up to root
while (!searchPath.empty()) {
String framesPath = searchPath + filePrefix + ".frames";
if (m_files.contains(framesPath)) {
foundFramesFile = framesPath;
break;
}
framesPath = searchPath + "default.frames";
if (m_files.contains(framesPath)) {
foundFramesFile = framesPath;
break;
}
searchPath = subdir(searchPath);
}
if (foundFramesFile) {
framesFile = foundFramesFile.take();
m_bestFramesFiles[image] = framesFile;
} else {
return {};
}
}
auto framesSpecification = unlockDuring([&]() {
return make_shared<FramesSpecification>(parseFramesSpecification(readJson(framesFile), framesFile));
});
m_framesSpecifications[image] = framesSpecification;
return framesSpecification;
}
IODevicePtr Assets::open(String const& path) const {
if (auto p = m_files.ptr(path))
return p->source->open(p->sourceName);
throw AssetException(strf("No such asset '{}'", path));
}
ByteArray Assets::read(String const& path) const {
if (auto p = m_files.ptr(path))
return p->source->read(p->sourceName);
throw AssetException(strf("No such asset '{}'", path));
}
ImageConstPtr Assets::readImage(String const& path) const {
if (auto p = m_files.ptr(path)) {
ImageConstPtr image;
if (auto memorySource = as<MemoryAssetSource>(p->source))
image = memorySource->image(p->sourceName);
if (!image)
image = make_shared<Image>(Image::readPng(p->source->open(p->sourceName)));
if (!p->patchSources.empty()) {
RecursiveMutexLocker luaLocker(m_luaMutex);
LuaEngine* luaEngine = as<LuaEngine>(m_luaEngine.get());
LuaValue result = luaEngine->createUserData(*image);
luaLocker.unlock();
for (auto const& pair : p->patchSources) {
auto& patchPath = pair.first;
auto& patchSource = pair.second;
auto patchStream = patchSource->read(patchPath);
if (patchPath.endsWith(".lua")) {
std::pair<AssetSource*, String> contextKey = make_pair(patchSource.get(), patchPath);
luaLocker.lock();
LuaContextPtr& context = m_patchContexts[contextKey];
if (!context) {
context = make_shared<LuaContext>(luaEngine->createContext());
context->load(patchStream, patchPath);
}
auto newResult = context->invokePath<LuaValue>("patch", result, path);
if (!newResult.is<LuaNilType>()) {
if (auto ud = newResult.ptr<LuaUserData>()) {
if (ud->is<Image>())
result = std::move(newResult);
else
Logger::warn("Patch '{}' for image '{}' returned a non-Image userdata value, ignoring");
} else {
Logger::warn("Patch '{}' for image '{}' returned a non-Image value, ignoring");
}
}
luaLocker.unlock();
} else {
Logger::warn("Patch '{}' for image '{}' isn't a Lua script, ignoring", patchPath, path);
}
}
image = make_shared<Image>(std::move(result.get<LuaUserData>().get<Image>()));
}
return image;
}
throw AssetException(strf("No such asset '{}'", path));
}
Json Assets::checkPatchArray(String const& path, AssetSourcePtr const& source, Json const result, JsonArray const patchData, Maybe<Json> const external) const {
auto externalRef = external.value();
auto newResult = result;
for (auto const& patch : patchData) {
switch(patch.type()) {
case Json::Type::Array: // if the patch is an array, go down recursively until we get objects
try {
newResult = checkPatchArray(path, source, newResult, patch.toArray(), externalRef);
} catch (JsonPatchTestFail const& e) {
Logger::debug("Patch test failure from file {} in source: '{}' at '{}'. Caused by: {}", path, source->metadata().value("name", ""), m_assetSourcePaths.getLeft(source), e.what());
} catch (JsonPatchException const& e) {
Logger::error("Could not apply patch from file {} in source: '{}' at '{}'. Caused by: {}", path, source->metadata().value("name", ""), m_assetSourcePaths.getLeft(source), e.what());
}
break;
case Json::Type::Object: // if its an object, check for operations, or for if an external file is needed for patches to reference
newResult = JsonPatching::applyOperation(newResult, patch, externalRef);
break;
case Json::Type::String:
try {
externalRef = json(patch.toString());
} catch (...) {
throw JsonPatchTestFail(strf("Unable to load reference asset: {}", patch.toString()));
}
break;
default:
throw JsonPatchException(strf("Patch data is wrong type: {}", Json::typeName(patch.type())));
break;
}
}
return newResult;
}
Json Assets::readJson(String const& path) const {
ByteArray streamData = read(path);
try {
Json result = inputUtf8Json(streamData.begin(), streamData.end(), JsonParseType::Top);
for (auto const& pair : m_files.get(path).patchSources) {
auto patchAssetPath = AssetPath::split(pair.first);
auto& patchBasePath = patchAssetPath.basePath;
auto& patchSource = pair.second;
auto patchStream = patchSource->read(patchBasePath);
if (patchBasePath.endsWith(".lua")) {
std::pair<AssetSource*, String> contextKey = make_pair(patchSource.get(), patchBasePath);
RecursiveMutexLocker luaLocker(m_luaMutex);
// Kae: i don't like that lock. perhaps have a LuaEngine and patch context cache per worker thread later on?
LuaContextPtr& context = m_patchContexts[contextKey];
if (!context) {
context = make_shared<LuaContext>(as<LuaEngine>(m_luaEngine.get())->createContext());
context->load(patchStream, patchBasePath);
}
auto newResult = context->invokePath<Json>("patch", result, path);
if (newResult)
result = std::move(newResult);
} else {
try {
auto patchJson = inputUtf8Json(patchStream.begin(), patchStream.end(), JsonParseType::Top);
if (patchAssetPath.subPath)
patchJson = patchJson.query(*patchAssetPath.subPath);
if (patchJson.isType(Json::Type::Array)) {
auto patchData = patchJson.toArray();
try {
result = checkPatchArray(pair.first, patchSource, result, patchData, {});
} catch (JsonPatchTestFail const& e) {
Logger::debug("Patch test failure from file {} in source: '{}' at '{}'. Caused by: {}", pair.first, patchSource->metadata().value("name", ""), m_assetSourcePaths.getLeft(patchSource), e.what());
} catch (JsonPatchException const& e) {
Logger::error("Could not apply patch from file {} in source: '{}' at '{}'. Caused by: {}", pair.first, patchSource->metadata().value("name", ""), m_assetSourcePaths.getLeft(patchSource), e.what());
}
} else if (patchJson.isType(Json::Type::Object)) {
result = jsonMergeNulling(result, patchJson.toObject());
}
} catch (std::exception const& e) {
throw JsonParsingException(strf("Cannot parse json patch file: {} in source {}", patchBasePath, patchSource->metadata().value("name", "")), e);
}
}
}
return result;
} catch (std::exception const& e) {
throw JsonParsingException(strf("Cannot parse json file: {}", path), e);
}
}
bool Assets::doLoad(AssetId const& id) const {
try {
// loadAsset automatically manages the queue and freshens the asset
// data.
return (bool)loadAsset(id);
} catch (std::exception const& e) {
Logger::error("Exception caught loading asset: {}, {}", id.path, outputException(e, true));
} catch (...) {
Logger::error("Unknown exception caught loading asset: {}", id.path);
}
// There was an exception, remove the asset from the queue and fill the cache
// with null so that getAsset will throw.
m_assetsCache[id] = {};
m_assetsDone.broadcast();
m_queue.remove(id);
return true;
}
bool Assets::doPost(AssetId const& id) const {
shared_ptr<AssetData> assetData;
try {
assetData = m_assetsCache.get(id);
if (id.type == AssetType::Audio)
assetData = postProcessAudio(assetData);
} catch (std::exception const& e) {
Logger::error("Exception caught post-processing asset: {}, {}", id.path, outputException(e, true));
} catch (...) {
Logger::error("Unknown exception caught post-processing asset: {}", id.path);
}
m_queue.remove(id);
if (assetData) {
assetData->needsPostProcessing = false;
m_assetsCache[id] = assetData;
freshen(assetData);
m_assetsDone.broadcast();
}
return true;
}
shared_ptr<Assets::AssetData> Assets::loadAsset(AssetId const& id) const {
if (auto asset = m_assetsCache.value(id))
return asset;
if (m_queue.value(id, QueuePriority::None) == QueuePriority::Working)
return {};
try {
m_queue[id] = QueuePriority::Working;
shared_ptr<AssetData> assetData;
try {
if (id.type == AssetType::Json) {
assetData = loadJson(id.path);
} else if (id.type == AssetType::Image) {
assetData = loadImage(id.path);
} else if (id.type == AssetType::Audio) {
assetData = loadAudio(id.path);
} else if (id.type == AssetType::Font) {
assetData = loadFont(id.path);
} else if (id.type == AssetType::Bytes) {
assetData = loadBytes(id.path);
}
} catch (StarException const& e) {
if (id.type == AssetType::Image && m_settings.missingImage) {
Logger::error("Could not load image asset '{}', using placeholder default.\n{}", id.path, outputException(e, false));
assetData = loadImage({*m_settings.missingImage, {}, {}});
} else if (id.type == AssetType::Audio && m_settings.missingAudio) {
Logger::error("Could not load audio asset '{}', using placeholder default.\n{}", id.path, outputException(e, false));
assetData = loadAudio({*m_settings.missingAudio, {}, {}});
} else {
throw;
}
}
if (assetData) {
if (assetData->needsPostProcessing)
m_queue[id] = QueuePriority::PostProcess;
else
m_queue.remove(id);
m_assetsCache[id] = assetData;
m_assetsDone.broadcast();
freshen(assetData);
} else {
// We have failed to load an asset because it depends on an asset
// currently being worked on. Mark it as needing loading and move it to
// the end of the queue.
m_queue[id] = QueuePriority::Load;
m_assetsQueued.signal();
m_queue.toBack(id);
}
return assetData;
} catch (...) {
m_queue.remove(id);
m_assetsCache[id] = {};
m_assetsDone.broadcast();
throw;
}
}
shared_ptr<Assets::AssetData> Assets::loadJson(AssetPath const& path) const {
Json json;
if (path.subPath) {
auto topJson =
as<JsonData>(loadAsset(AssetId{AssetType::Json, {path.basePath, {}, {}}}));
if (!topJson)
return {};
try {
auto newData = make_shared<JsonData>();
newData->json = topJson->json.query(*path.subPath);
return newData;
} catch (StarException const& e) {
throw AssetException(strf("Could not read JSON value {}", path), e);
}
} else {
return unlockDuring([&]() {
try {
auto newData = make_shared<JsonData>();
newData->json = readJson(path.basePath);
return newData;
} catch (StarException const& e) {
throw AssetException(strf("Could not read JSON asset {}", path), e);
}
});
}
}
shared_ptr<Assets::AssetData> Assets::loadImage(AssetPath const& path) const {
validatePath(path, true, true);
if (!path.directives.empty()) {
shared_ptr<ImageData> source =
as<ImageData>(loadAsset(AssetId{AssetType::Image, {path.basePath, path.subPath, {}}}));
if (!source)
return {};
StringMap<ImageConstPtr> references;
StringList referencePaths;
for (auto& directives : path.directives.list())
directives.loadOperations();
path.directives.forEach([&](auto const& entry, Directives const&) {
addImageOperationReferences(entry.operation, referencePaths);
}); // TODO: This can definitely be better, was changed quickly to support the new Directives.
for (auto const& ref : referencePaths) {
auto components = AssetPath::split(ref);
validatePath(components, true, false);
auto refImage = as<ImageData>(loadAsset(AssetId{AssetType::Image, std::move(components)}));
if (!refImage)
return {};
references[ref] = refImage->image;
}
return unlockDuring([&]() {
auto newData = make_shared<ImageData>();
Image newImage = *source->image;
path.directives.forEach([&](Directives::Entry const& entry, Directives const&) {
if (auto error = entry.operation.ptr<ErrorImageOperation>())
if (auto string = error->cause.ptr<std::string>())
throw DirectivesException::format("ImageOperation parse error: {}", *string);
else
std::rethrow_exception(error->cause.get<std::exception_ptr>());
else
processImageOperation(entry.operation, newImage, [&](String const& ref) { return references.get(ref).get(); });
});
newData->image = make_shared<Image>(std::move(newImage));
return newData;
});
} else if (path.subPath) {
auto imageData = as<ImageData>(loadAsset(AssetId{AssetType::Image, {path.basePath, {}, {}}}));
if (!imageData)
return {};
// Base image must have frames data associated with it.
if (!imageData->frames)
throw AssetException::format("No associated frames file found for image '{}' while resolving image frame '{}'", path.basePath, path);
if (auto alias = imageData->frames->aliases.ptr(*path.subPath)) {
imageData = as<ImageData>(loadAsset(AssetId{AssetType::Image, {path.basePath, *alias, path.directives}}));
if (!imageData)
return {};
auto newData = make_shared<ImageData>();
newData->image = imageData->image;
newData->alias = true;
return newData;
} else {
auto frameRect = imageData->frames->frames.ptr(*path.subPath);
if (!frameRect)
throw AssetException(strf("No such frame {} in frames spec {}", *path.subPath, imageData->frames->framesFile));
return unlockDuring([&]() {
// Need to flip frame coordinates because frame configs assume top
// down image coordinates
auto newData = make_shared<ImageData>();
newData->image = make_shared<Image>(imageData->image->subImage(
Vec2U(frameRect->xMin(), imageData->image->height() - frameRect->yMax()), frameRect->size()));
return newData;
});
}
} else {
auto imageData = make_shared<ImageData>();
imageData->image = unlockDuring([&]() {
return readImage(path.basePath);
});
imageData->frames = bestFramesSpecification(path.basePath);
return imageData;
}
}
shared_ptr<Assets::AssetData> Assets::loadAudio(AssetPath const& path) const {
return unlockDuring([&]() {
auto newData = make_shared<AudioData>();
newData->audio = make_shared<Audio>(open(path.basePath), path.basePath);
newData->needsPostProcessing = newData->audio->compressed();
return newData;
});
}
shared_ptr<Assets::AssetData> Assets::loadFont(AssetPath const& path) const {
return unlockDuring([&]() {
auto newData = make_shared<FontData>();
newData->font = Font::loadFont(make_shared<ByteArray>(read(path.basePath)));
return newData;
});
}
shared_ptr<Assets::AssetData> Assets::loadBytes(AssetPath const& path) const {
return unlockDuring([&]() {
auto newData = make_shared<BytesData>();
newData->bytes = make_shared<ByteArray>(read(path.basePath));
return newData;
});
}
shared_ptr<Assets::AssetData> Assets::postProcessAudio(shared_ptr<AssetData> const& original) const {
return unlockDuring([&]() -> shared_ptr<AssetData> {
if (auto audioData = as<AudioData>(original)) {
if (audioData->audio->totalTime() < m_settings.audioDecompressLimit) {
auto audio = make_shared<Audio>(*audioData->audio);
audio->uncompress();
auto newData = make_shared<AudioData>();
newData->audio = audio;
return newData;
} else {
return audioData;
}
} else {
return {};
}
});
}
void Assets::freshen(shared_ptr<AssetData> const& asset) const {
asset->time = Time::monotonicTime();
}
}
|