Repository navigation
Expand file tree
/
Copy pathinternal.cpp
More file actions
2283 lines (1805 loc) · 51.4 KB
/
Copy pathinternal.cpp
File metadata and controls
2283 lines (1805 loc) · 51.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright (C) 2020 Marcel Smit
https://www.facebook.com/marcel.smit981
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
#if defined(IPHONEOS)
#include <OpenGLES/ES3/gl.h>
#elif defined(ANDROID)
#include <GLES3/gl3.h>
#else
#include <GL/glew.h>
#endif
#include "audio.h"
#include "image.h"
#include "internal.h"
#include "spriter.h"
#include "Path.h"
#include "StringEx.h"
#if USE_GLYPH_ATLAS
#include "textureatlas.h"
#endif
#if ENABLE_MSDF_FONTS
#include "msdfgen.h"
#include "Float16.h" // for float to float16 conversion
#endif
#define STB_TRUETYPE_IMPLEMENTATION
#include "stb_truetype.h"
#if defined(DEBUG)
#include "Timer.h"
#endif
#define MSDF_FONT_CACHE_VERSION 6
Globals globals;
TextureCache g_textureCache;
Texture3dCache g_texture3dCache;
AnimCache g_animCache;
SpriterCache g_spriterCache;
SoundCache g_soundCache;
FontCache g_fontCache;
#if ENABLE_MSDF_FONTS
MsdfFontCache g_fontCacheMSDF;
#endif
GlyphCache g_glyphCache;
std::vector<ShaderOutput> g_shaderOutputs;
// -----
#if FRAMEWORK_ENABLE_GL_ERROR_LOG && ENABLE_OPENGL
void checkErrorGL_internal(const char * function, int line)
{
const GLenum error = glGetError();
if (error != GL_NO_ERROR)
{
logError("%s: %d: OpenGL error: %x", function, line, error);
AssertMsg(error == GL_NO_ERROR, "%s: %d: OpenGL error: %x", function, line, error);
}
}
#endif
#if FRAMEWORK_ENABLE_GL_DEBUG_CONTEXT && ENABLE_DESKTOP_OPENGL
static void formatDebugOutputGL(char * outStr, size_t outStrSize, GLenum source, GLenum type, GLuint id, GLenum severity, const char * msg)
{
char sourceStr[32];
const char *sourceFmt = "UNDEFINED(0x%04X)";
switch(source)
{
case GL_DEBUG_SOURCE_API_ARB: sourceFmt = "API"; break;
case GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB: sourceFmt = "WINDOW_SYSTEM"; break;
case GL_DEBUG_SOURCE_SHADER_COMPILER_ARB: sourceFmt = "SHADER_COMPILER"; break;
case GL_DEBUG_SOURCE_THIRD_PARTY_ARB: sourceFmt = "THIRD_PARTY"; break;
case GL_DEBUG_SOURCE_APPLICATION_ARB: sourceFmt = "APPLICATION"; break;
case GL_DEBUG_SOURCE_OTHER_ARB: sourceFmt = "OTHER"; break;
}
sprintf_s(sourceStr, 32, sourceFmt, source);
char typeStr[32];
const char *typeFmt = "UNDEFINED(0x%04X)";
switch(type)
{
case GL_DEBUG_TYPE_ERROR_ARB: typeFmt = "ERROR"; break;
case GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB: typeFmt = "DEPRECATED_BEHAVIOR"; break;
case GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB: typeFmt = "UNDEFINED_BEHAVIOR"; break;
case GL_DEBUG_TYPE_PORTABILITY_ARB: typeFmt = "PORTABILITY"; break;
case GL_DEBUG_TYPE_PERFORMANCE_ARB: typeFmt = "PERFORMANCE"; break;
case GL_DEBUG_TYPE_OTHER_ARB: typeFmt = "OTHER"; break;
}
sprintf_s(typeStr, 32, typeFmt, type);
char severityStr[32];
const char *severityFmt = "UNDEFINED";
switch(severity)
{
case GL_DEBUG_SEVERITY_HIGH_ARB: severityFmt = "HIGH"; break;
case GL_DEBUG_SEVERITY_MEDIUM_ARB: severityFmt = "MEDIUM"; break;
case GL_DEBUG_SEVERITY_LOW_ARB: severityFmt = "LOW"; break;
}
sprintf_s(severityStr, 32, severityFmt, severity);
sprintf_s(outStr, outStrSize, "OpenGL: %s [source=%s type=%s severity=%s id=%d]", msg, sourceStr, typeStr, severityStr, id);
}
#if defined(WIN32)
void __stdcall debugOutputGL(
#else
void debugOutputGL(
#endif
GLenum source,
GLenum type,
GLuint id,
GLenum severity,
GLsizei length,
const GLchar * message,
const GLvoid * userParam)
{
if (severity != GL_DEBUG_SEVERITY_NOTIFICATION)
{
FILE * file = (FILE*)userParam;
char formattedMessage[4096];
formatDebugOutputGL(formattedMessage, sizeof(formattedMessage), source, type, id, severity, message);
fprintf(file, "%s\n", formattedMessage);
}
}
#endif
//
#if defined(DEBUG)
ScopedLoadTimer::ScopedLoadTimer(const char * filename)
: m_filename(filename)
{
logDebug("load %s [begin]", m_filename);
m_startTime = g_TimerRT.TimeUS_get();
}
ScopedLoadTimer::~ScopedLoadTimer()
{
const uint64_t endTime = g_TimerRT.TimeUS_get();
logDebug("load %s [end] took %02.2fms", m_filename, (endTime - m_startTime) / 1000.f);
}
#endif
// -----
#if USE_STBFONT || ENABLE_MSDF_FONTS
StbFont::StbFont()
: buffer(nullptr)
, bufferSize(0)
{
}
StbFont::~StbFont()
{
free();
}
bool StbFont::load(const char * filename)
{
bool result = false;
FILE * file = fopen(filename, "rb");
if (file != nullptr)
{
// load source from file
Verify(fseek(file, 0, SEEK_END) == 0);
{
const int64_t fileSize = ftell(file);
Assert(fileSize >= 0);
bufferSize = (size_t)fileSize;
}
Verify(fseek(file, 0, SEEK_SET) == 0);
buffer = new uint8_t[bufferSize];
if (fread(buffer, 1, bufferSize, file) == (size_t)bufferSize)
{
if (stbtt_InitFont(&fontInfo, buffer, 0) != 0)
{
result = true;
}
}
fclose(file);
file = nullptr;
}
if (result == false)
{
free();
}
return result;
}
void StbFont::free()
{
delete[] buffer;
buffer = nullptr;
bufferSize = 0;
}
#endif
// -----
TextureCacheElem::TextureCacheElem()
{
textures = 0;
sx = sy = 0.f;
gridSx = gridSy = 0;
mipmapped = false;
contentScale = 0.f;
}
void TextureCacheElem::free()
{
if (textures != 0)
{
const int numTextures = gridSx * gridSy;
for (int i = 0; i < numTextures; ++i)
textures[i].free();
delete [] textures;
name.clear();
textures = 0;
sx = sy = 0.f;
gridSx = gridSy = 0;
mipmapped = false;
contentScale = 0.f;
}
}
#if defined(WINDOWS)
#include <Windows.h>
#include <Pathcch.h>
static std::string getCacheFilename(const char * filename, bool forRead)
{
const int kPathSize = 256;
char tempPath[kPathSize];
if (GetTempPathA(kPathSize, tempPath) > 0)
{
uint32_t hash = 0;
for (int i = 0; filename[i]; ++i)
hash = hash * 13 + filename[i];
char hashName[32];
sprintf_s(hashName, sizeof(hashName), "fwc-%08x.bin", hash);
strcat_s(tempPath, sizeof(tempPath), hashName);
if (forRead)
{
// check timestamp on both files
bool outdated = false;
const HANDLE file1 = CreateFile(filename, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
const HANDLE file2 = CreateFile(tempPath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (file1 == INVALID_HANDLE_VALUE || file2 == INVALID_HANDLE_VALUE)
outdated = true;
else
{
FILETIME fileTime1;
FILETIME fileTime2;
if (!GetFileTime(file1, NULL, NULL, &fileTime1) ||
!GetFileTime(file2, NULL, NULL, &fileTime2) ||
CompareFileTime(&fileTime1, &fileTime2) == 1)
outdated = true;
}
if (file1 != INVALID_HANDLE_VALUE)
CloseHandle(file1);
if (file2 != INVALID_HANDLE_VALUE)
CloseHandle(file2);
if (outdated)
return "";
}
return tempPath;
}
return "";
}
#elif defined(MACOS)
#include <sys/stat.h>
#include <unistd.h>
static std::string getCacheFilename(const char * filename, bool forRead)
{
char path[PATH_MAX];
size_t n = confstr(_CS_DARWIN_USER_CACHE_DIR, path, sizeof(path));
if (n == 0)
return "";
else
{
if (n >= 2 && path[n - 2] == '/')
path[n - 2] = 0;
uint32_t hash = 0;
for (int i = 0; filename[i]; ++i)
hash = hash * 13 + filename[i];
char tempPath[PATH_MAX];
sprintf_s(tempPath, sizeof(tempPath), "%s/fwc-%08x.bin", path, hash);
if (forRead)
{
// check timestamp on both files
bool outdated = false;
FILE * file1 = fopen(filename, "rb");
FILE * file2 = fopen(tempPath, "rb");
if (file1 == nullptr || file2 == nullptr)
outdated = true;
else
{
struct stat stat1;
struct stat stat2;
if (fstat(fileno(file1), &stat1) != 0 || fstat(fileno(file2), &stat2) != 0)
outdated = true;
else if (stat1.st_mtime > stat2.st_mtime)
outdated = true;
}
if (file1 != nullptr)
fclose(file1);
if (file2 != nullptr)
fclose(file2);
if (outdated)
return "";
}
return tempPath;
}
}
#else
static std::string getCacheFilename(const char * filename, bool forRead)
{
return "";
}
#endif
void TextureCacheElem::load(const char * filename, int gridSx, int gridSy, bool mipmapped, float contentScale)
{
ScopedLoadTimer loadTimer(filename);
free();
name = filename;
if (gridSx != 1 || gridSy != 1)
{
// make sure the content scale is an integer when we need to subdivide the texture into a grid
contentScale = int(ceilf(contentScale));
}
ImageData * imageData = loadImage(filename, contentScale);
if (!imageData)
{
logError("failed to load %s (%dx%d) @%.2fx", filename, gridSx, gridSy, contentScale);
}
else
{
#if 1 // imageFixAlphaFilter for png and gif
if (String::EndsWith(filename, ".png") || String::EndsWith(filename, ".gif"))
{
ImageData * temp = imageFixAlphaFilter(imageData);
delete imageData;
imageData = temp;
}
#endif
if ((imageData->sx % int(gridSx * contentScale)) != 0 || (imageData->sy % int(gridSy * contentScale)) != 0)
{
logError("image size (%d, %d) must be a multiple of the grid size (%d, %d) @%.2fx",
imageData->sx, imageData->sy, gridSx, gridSy, contentScale);
}
else
{
const int numTextures = gridSx * gridSy;
const int cellSx = imageData->sx / gridSx;
const int cellSy = imageData->sy / gridSy;
textures = new GxTexture[numTextures];
GxTextureProperties textureProperties;
textureProperties.dimensions.sx = cellSx;
textureProperties.dimensions.sy = cellSy;
textureProperties.format = GX_RGBA8_UNORM;
textureProperties.mipmapped = mipmapped;
// todo : try to see if there's a meta data file for this texture,
// if so, load texture settings from this file (similar to Sprite)
// _OR_ when getTexture is called on a .txt file, load the .txt
// file and reference the texture from the .txt file or by replacing the extension <-- this doesn't seem like a good idea. we want people to be able to override texture settings (for instance through refine) without the code needing to change
// idea : for refine : make sure most resources have reflection data. load/save of meta data files would be much easier this way. also, enables an 'advanced' section inside the resource editor, which lets one inspect and modify the entire reflected structure. eg, the sprite editor would have a nice UI for changing the scale & flipped flags, and an advanced section for setting grid divisions, animation definitions
// -> use meta data to see if mipmaps should be enabled, and for filter settings
for (int i = 0; i < numTextures; ++i)
{
const int cellX = i % gridSx;
const int cellY = i / gridSx;
const int sourceX = cellX * cellSx;
const int sourceY = cellY * cellSy;
const int sourceOffset = sourceX + sourceY * imageData->sx;
const void * source = ((int*)imageData->imageData) + sourceOffset;
textures[i].allocate(textureProperties);
textures[i].upload(source, 0, imageData->sx, true);
}
this->sx = imageData->sx / contentScale;
this->sy = imageData->sy / contentScale;
this->gridSx = gridSx;
this->gridSy = gridSy;
this->mipmapped = mipmapped;
this->contentScale = contentScale;
logInfo("loaded %s (%dx%d) @%.2fx", filename, gridSx, gridSy, contentScale);
}
delete imageData;
imageData = nullptr;
}
}
void TextureCacheElem::reload()
{
const std::string oldName = name;
const int oldGridSx = gridSx;
const int oldGridSy = gridSy;
const bool oldMipmapped = mipmapped;
const float oldContentScale = contentScale;
free();
load(oldName.c_str(), oldGridSx, oldGridSy, oldMipmapped, oldContentScale);
}
void TextureCache::clear()
{
for (Map::iterator i = m_map.begin(); i != m_map.end(); ++i)
{
i->second.free();
}
m_map.clear();
}
void TextureCache::reload()
{
for (Map::iterator i = m_map.begin(); i != m_map.end(); ++i)
{
i->second.reload();
}
}
void TextureCache::handleFileChange(const std::string & filename, const std::string & extension)
{
for (auto & i : m_map)
{
auto & elem = i.second;
if (elem.name == filename)
elem.reload();
}
}
TextureCacheElem & TextureCache::findOrCreate(const char * name, int gridSx, int gridSy, bool mipmapped, float contentScale)
{
if (contentScale == 0.f)
{
contentScale = getContentScale();
}
// ignore content scale for file formats that don't support it
if (Path::IsExtension(name, "svg", true) == false)
{
contentScale = 1.f;
}
Key key;
key.name = name;
key.gridSx = gridSx;
key.gridSy = gridSy;
key.mipmapped = mipmapped;
key.contentScale = contentScale;
Map::iterator i = m_map.find(key);
if (i != m_map.end())
{
return i->second;
}
else
{
const char * resolved_filename = framework.resolveResourcePath(name);
TextureCacheElem elem;
elem.load(resolved_filename, gridSx, gridSy, mipmapped, contentScale);
i = m_map.insert(Map::value_type(key, elem)).first;
return i->second;
}
}
// -----
Texture3dCacheElem::Texture3dCacheElem()
{
texture = nullptr;
}
void Texture3dCacheElem::free()
{
if (texture != nullptr)
{
texture->free();
delete texture;
texture = nullptr;
}
}
void Texture3dCacheElem::load(const char * filename)
{
ScopedLoadTimer loadTimer(filename);
free();
name = filename;
texture = new GxTexture3d();
ImageData * imageData = loadImage(filename);
if (!imageData)
{
logError("failed to load %s", filename);
}
else
{
#if 1 // imageFixAlphaFilter for png and gif
if (String::EndsWith(filename, ".png") || String::EndsWith(filename, ".gif"))
{
ImageData * temp = imageFixAlphaFilter(imageData);
delete imageData;
imageData = temp;
}
#endif
GxTexture3dProperties textureProperties;
if (imageData->sx > 0 && imageData->sy > 0)
{
textureProperties.dimensions.sx = imageData->sx / imageData->sy;
textureProperties.dimensions.sy = imageData->sy;
textureProperties.dimensions.sz = imageData->sx / imageData->sy;
}
textureProperties.format = GX_RGBA8_UNORM;
textureProperties.mipmapped = false;
// todo : try to see if there's a meta data file for this texture,
// if so, load texture settings from this file (similar to Sprite)
// _OR_ when getTexture3d is called on a .txt file, load the .txt
// file and reference the texture from the .txt file or by replacing the extension
// -> use meta data to see if mipmaps should be enabled
texture->allocate(textureProperties);
texture->upload(imageData->imageData, 4, 0);
logInfo("loaded %s", filename);
}
delete imageData;
}
void Texture3dCacheElem::reload()
{
const std::string oldName = name;
free();
load(oldName.c_str());
}
void Texture3dCache::clear()
{
for (Map::iterator i = m_map.begin(); i != m_map.end(); ++i)
{
i->second.free();
}
m_map.clear();
}
void Texture3dCache::reload()
{
for (Map::iterator i = m_map.begin(); i != m_map.end(); ++i)
{
i->second.reload();
}
}
void Texture3dCache::handleFileChange(const std::string & filename, const std::string & extension)
{
auto i = m_map.find(filename);
if (i != m_map.end())
{
auto & elem = i->second;
elem.reload();
}
}
Texture3dCacheElem & Texture3dCache::findOrCreate(const char * name)
{
Key key;
key = name;
Map::iterator i = m_map.find(key);
if (i != m_map.end())
{
return i->second;
}
else
{
const char * resolved_filename = framework.resolveResourcePath(name);
Texture3dCacheElem elem;
elem.load(resolved_filename);
i = m_map.insert(Map::value_type(key, elem)).first;
return i->second;
}
}
// -----
AnimCacheElem::AnimCacheElem()
{
free();
}
void AnimCacheElem::free()
{
m_hasSheet = false;
m_gridSize[0] = m_gridSize[1] = 1;
m_pivot[0] = m_pivot[1] = 0;
m_scale = 1.f;
m_animMap.clear();
}
template <typename Policy>
void splitString(const std::string & str, std::vector<std::string> & result, Policy policy, const bool keepEmptyElements)
{
if (str.empty())
return;
size_t start = -1;
bool foundStart = false;
for (size_t i = 0; i <= str.size(); ++i)
{
const char c = i < str.size() ? str[i] : policy.getBreakChar();
if (foundStart == false)
{
// found start
if (!policy.isBreak(c))
{
start = i;
foundStart = true;
}
else if (keepEmptyElements)
{
result.push_back(std::string());
}
}
else if (policy.isBreak(c))
{
// found end
result.push_back(str.substr(start, i - start));
start = -1;
foundStart = false;
}
}
}
class WhiteSpacePolicy
{
public:
bool isBreak(char c)
{
return c == '\t' || c == ' ' || c == '\r' || c == '\n';
}
char getBreakChar()
{
return ' ';
}
};
void splitString(const std::string & str, std::vector<std::string> & result, bool keepEmptyElements)
{
WhiteSpacePolicy policy;
splitString<WhiteSpacePolicy>(str, result, policy, keepEmptyElements);
}
void splitString(const std::string & str, std::vector<std::string> & result)
{
WhiteSpacePolicy policy;
splitString<WhiteSpacePolicy>(str, result, policy, false);
}
class CharPolicy
{
char C;
public:
CharPolicy(char c)
{
C = c;
}
bool isBreak(char c)
{
return c == C;
}
char getBreakChar()
{
return C;
}
};
void splitString(const std::string & str, std::vector<std::string> & result, char c)
{
CharPolicy policy(c);
splitString<CharPolicy>(str, result, policy, true);
}
void AnimCacheElem::load(const char * filename)
{
ScopedLoadTimer loadTimer(filename);
free();
FileReader r;
if (!r.open(filename, true))
{
//logError("%s: failed to open file!", filename);
}
else
{
Anim * currentAnim = 0;
std::string line;
while (r.read(line))
{
// format: <name> <key>:<value> <key:value> <key..
std::vector<std::string> parts;
splitString(line, parts);
if (parts.size() == 0 || parts[0][0] == '#')
{
// empty line or comment
continue;
}
if (parts.size() == 1)
{
logError("%s: missing parameters: %s (%s)", filename, line.c_str(), parts[0].c_str());
continue;
}
const std::string section = parts[0];
Dictionary args;
for (size_t i = 1; i < parts.size(); ++i)
{
const size_t separator = parts[i].find(':');
if (separator == std::string::npos)
{
logError("%s: incorrect key:value syntax: %s (%s)", filename, line.c_str(), parts[i].c_str());
continue;
}
const std::string key = parts[i].substr(0, separator);
const std::string value = parts[i].substr(separator + 1, parts[i].size() - separator - 1);
if (key.size() == 0 || value.size() == 0)
{
logError("%s: incorrect key:value syntax: %s (%s)", filename, line.c_str(), parts[i].c_str());
continue;
}
if (args.contains(key.c_str()))
{
logError("%s: duplicate key: %s (%s)", filename, line.c_str(), key.c_str());
continue;
}
args.setString(key.c_str(), value.c_str());
}
// sheet pivot_x:0 pivot_y:0 cells_x:4 cells_y:8
// animation name:walk grid_x:0 grid_y:0 frames:12 rate:4 loop:0 pivot_x:2 pivot_y:2
// trigger frame:3 action:sound sound:test.wav
if (section == "sheet")
{
const int gridSx = args.getInt("grid_sx", 1);
const int gridSy = args.getInt("grid_sy", 1);
if (gridSx <= 0 || gridSy <= 0)
{
logError("%s: grid size must be > 0: %s", filename, line.c_str());
continue;
}
m_hasSheet = true;
m_gridSize[0] = gridSx;
m_gridSize[1] = gridSy;
m_pivot[0] = args.getInt("pivot_x", 0);
m_pivot[1] = args.getInt("pivot_y", 0);
m_scale = args.getFloat("scale", 1.f);
}
else if (section == "animation")
{
currentAnim = 0;
Anim anim;
anim.name = args.getString("name", "");
if (anim.name.empty())
{
logError("%s: name not set: %s", filename, line.c_str());
continue;
}
const int gridX = args.getInt("grid_x", 0);
const int gridY = args.getInt("grid_y", 0);
if (gridX < 0 || gridY < 0)
{
logError("%s: grid_x and grid_y must be >= 0: %s", filename, line.c_str());
continue;
}
anim.firstCell = gridX + gridY * m_gridSize[0];
anim.numFrames = args.getInt("frames", 1);
const int lastCell = anim.firstCell + anim.numFrames;
if (lastCell > m_gridSize[0] * m_gridSize[1])
{
logError("%s: animation lies (partially or completely) outside the grid: %s", filename, line.c_str());
continue;
}
anim.frameRate = (float)args.getInt("rate", 1);
if (anim.frameRate <= 0)
{
logError("%s: frame rate must be >= 1: %s", filename, line.c_str());
continue;
}
anim.pivot[0] = args.getInt("pivot_x", m_pivot[0]);
anim.pivot[1] = args.getInt("pivot_y", m_pivot[1]);
anim.loop = args.getInt("loop", 1) != 0;
anim.loopStart = args.getInt("loop_start", 0);
if (anim.loopStart >= anim.numFrames)
{
logError("%s: loop start must be < 'frames': %s", filename, line.c_str());
continue;
}
anim.frameTriggers.resize(anim.numFrames);
currentAnim = &m_animMap.insert(AnimMap::value_type(anim.name, anim)).first->second;
}
else if (section == "trigger")
{
if (currentAnim == 0)
{
logError("%s: must first define an animation before adding triggers to it! %s", filename, line.c_str());
continue;
}
const int frame = args.getInt("frame", 0);
if (frame < 0 || frame >= currentAnim->numFrames)
{
logWarning("%s: frame is not a key frame within the animation: %s", filename, line.c_str());
continue;
}
const std::string event = args.getString("on", "enter");
const std::string action = args.getString("action", "");
AnimTrigger::Event eventEnum;
if (event == "enter")
eventEnum = AnimTrigger::OnEnter;
else if (event == "leave")
eventEnum = AnimTrigger::OnLeave;
else
{
logError("%s: invalid value for 'on': %s", filename, line.c_str());
continue;
}
//logInfo("added frame trigger. frame=%d, on=%s, action=%s", frame, event.c_str(), action.c_str());
AnimTrigger trigger;
trigger.event = eventEnum;
trigger.action = action;
trigger.args = args;
currentAnim->frameTriggers[frame].push_back(trigger);
}
else
{
logError("%s: unknown section: %s (%s)", filename, line.c_str(), section.c_str());
}
}
}
}
int AnimCacheElem::getVersion() const
{
return globals.resourceVersion;
}
void AnimCache::clear()
{
for (Map::iterator i = m_map.begin(); i != m_map.end(); ++i)
{
i->second.free();
}
m_map.clear();
}
void AnimCache::reload()
{
for (Map::iterator i = m_map.begin(); i != m_map.end(); ++i)
{
i->second.load(i->first.c_str());
}
}
void AnimCache::handleFileChange(const std::string & filename, const std::string & extension)
{
auto i = m_map.find(filename);
if (i != m_map.end())
{
auto & elem = i->second;
elem.load(i->first.c_str());
}
}
AnimCacheElem & AnimCache::findOrCreate(const char * name)
{
Key key = name;