summaryrefslogtreecommitdiffhomepage
path: root/Stars45/DataLoader.cpp
blob: 9c5860842e45f66bad84e303afd09c20d768fa0e (plain)
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
/*  Starshatter: The Open Source Project
    Copyright (c) 2021-2022, Starshatter: The Open Source Project Contributors
    Copyright (c) 2011-2012, Starshatter OpenSource Distribution Contributors
    Copyright (c) 1997-2006, Destroyer Studios LLC.

    AUTHOR:       John DiCamillo

*/

#include "MemDebug.h"
#include "DataLoader.h"
#include "Archive.h"
#include "Color.h"
#include "D3DXImage.h"
#include "Bitmap.h"
#include "Bmp.h"
#include "Pcx.h"
#include "Sound.h"
#include "Video.h"
#include "Wave.h"

// +------------------------------------------------------------------+

static DataLoader*   def_loader = 0;
DataLoader*   DataLoader::loader = 0;

static List<DataArchive>   archives;

// +--------------------------------------------------------------------+

DataLoader::DataLoader()
    : datapath(""), video(0), use_file_system(true), enable_media(true)
{ }

// +--------------------------------------------------------------------+

void
DataLoader::UseVideo(Video* v)
{
    video = v;
}

// +--------------------------------------------------------------------+

void
DataLoader::Initialize()
{
    def_loader = new(__FILE__,__LINE__) DataLoader;
    loader = def_loader;

    archives.destroy();
}

void
DataLoader::Close()
{
    archives.destroy();
    Bitmap::ClearCache();

    delete def_loader;
    def_loader = 0;
    loader = 0;
}

void
DataLoader::Reset()
{
    Close();
}

// +--------------------------------------------------------------------+

void
DataLoader::UseFileSystem(bool use)
{
    use_file_system = use;
}

void
DataLoader::EnableMedia(bool enable)
{
    enable_media = enable;
}

// +--------------------------------------------------------------------+

int
DataLoader::EnableDatafile(const char* name)
{
    int status = DATAFILE_NOTEXIST;

    FILE* f;
    fopen_s(&f, name, "rb");

    if (f) {
        ::fclose(f);

        DataArchive* a = new(__FILE__,__LINE__) DataArchive(name);

        if (a && a->NumFiles() >= 1) {
            status = DATAFILE_OK;

            bool found = false;
            ListIter<DataArchive> iter = archives;
            while (++iter && !found) {
                DataArchive* archive = iter.value();
                if (!strcmp(archive->Name(), name)) {
                    found = true;
                }
            }

            if (!found)
            archives.append(a);
        }
        else {
            Print("   WARNING: invalid data file '%s'\n", name);
            status = DATAFILE_INVALID;

            delete a;
        }

        loader   = this;
    }
    else {
        Print("   WARNING: could not open datafile '%s'\n", name);
        status = DATAFILE_NOTEXIST;
    }

    return status;
}

int
DataLoader::DisableDatafile(const char* name)
{
    ListIter<DataArchive> iter = archives;
    while (++iter) {
        DataArchive* a = iter.value();
        if (!strcmp(a->Name(), name)) {
            delete iter.removeItem();
            return DATAFILE_OK;
        }
    }

    return DATAFILE_NOTEXIST;
}

// +--------------------------------------------------------------------+

void
DataLoader::SetDataPath(const char* path)
{
    if (path)
    datapath = path;
    else
    datapath = "";
}

// +--------------------------------------------------------------------+

bool
DataLoader::FindFile(const char* name)
{
    // assemble file name:
    char filename[1024];
    strcpy_s(filename, datapath);
    strcat_s(filename, name);

    // first check current directory:
    if (use_file_system) {
        FILE* f;
        ::fopen_s(&f, filename, "rb");

        if (f) {
            ::fclose(f);
            return true;
        }
    }

    // then check datafiles, from last to first:
    int narchives = archives.size();
    for (int i = 0; i < narchives; i++) {
        DataArchive* a = archives[narchives-1-i];
        if (a->FindEntry(filename) > -1) {
            return true;
        }
    }

    return false;
}

// +--------------------------------------------------------------------+

int
DataLoader::ListFiles(const char* filter, List<Text>& list, bool recurse)
{
    list.destroy();

    ListFileSystem(filter, list, datapath, recurse);

    // then check datafile(s):
    int narchives = archives.size();
    for (int i = 0; i < narchives; i++) {
        DataArchive* a = archives[narchives-1-i];
        ListArchiveFiles(a->Name(), filter, list);
    }

    return list.size();
}

int
DataLoader::ListArchiveFiles(const char* archive_name, const char* filter, List<Text> &list)
{
    int            pathlen  = datapath.length();
    DataArchive*   a        = 0;

    if (archive_name) {
        int narchives = archives.size();
        for (int i = 0; i < narchives && !a; i++) {
            a = archives[narchives-1-i];

            if (_stricmp(a->Name(), archive_name))
            a = 0;
        }
    }

    if (!a) {
        ListFileSystem(filter, list, datapath, true);
        return list.size();
    }

    if (!strcmp(filter, "*.*")) {
        int count = a->NumFiles();
        for (int n = 0; n < count; n++) {
            DataEntry* entry = a->GetFile(n);
            Text entry_name = entry->name;
            entry_name.setSensitive(false);

            if (entry_name.contains(datapath)) {
                Text fname = entry_name(pathlen, 1000);

                if (!list.contains(&fname))
                list.append(new Text(fname));
            }
        }
    }
    else {
        char data_filter[256];
        ZeroMemory(data_filter, 256);

        const char* pf  = filter;
        char*       pdf = data_filter;

        while (*pf) {
            if (*pf != '*')
            *pdf++ = *pf;
            pf++;
        }

        int count = a->NumFiles();
        for (int n = 0; n < count; n++) {
            DataEntry* entry = a->GetFile(n);
            Text entry_name = entry->name;
            entry_name.setSensitive(false);

            if (entry_name.contains(datapath) && entry_name.contains(data_filter)) {
                Text fname = entry_name(pathlen, 1000);

                if (!list.contains(&fname))
                list.append(new Text(fname));
            }
        }
    }

    return list.size();
}

// +--------------------------------------------------------------------+

void
DataLoader::ListFileSystem(const char* filter, List<Text>& list, Text base_path, bool recurse)
{
    if (use_file_system) {
        char data_filter[256];
        ZeroMemory(data_filter, 256);

        const char* pf  = filter;
        char*       pdf = data_filter;

        while (*pf) {
            if (*pf != '*')
            *pdf++ = *pf;
            pf++;
        }

        int pathlen = base_path.length();

        // assemble win32 find filter:
        char win32_filter[1024];
        strcpy_s(win32_filter, datapath);

        if (recurse)
        strcat_s(win32_filter, "*.*");
        else
        strcat_s(win32_filter, filter);

        // first check current directory:
        WIN32_FIND_DATA data;
        HANDLE hFind = FindFirstFile(win32_filter, &data);

        if (hFind != INVALID_HANDLE_VALUE) {
            do {
                if ((data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0) {
                    if (recurse && data.cFileName[0] != '.') {
                        Text old_datapath = datapath;

                        Text newpath = datapath;
                        newpath += data.cFileName;
                        newpath += "/";
                        datapath = newpath;

                        ListFileSystem(filter, list, base_path, recurse);

                        datapath = old_datapath;
                    }
                }
                else {
                    if (!strcmp(filter, "*.*") || strstr(data.cFileName, data_filter)) {
                        Text full_name = datapath;
                        full_name += data.cFileName;

                        list.append(new Text(full_name(pathlen, 1000)));
                    }
                }
            }
            while (FindNextFile(hFind, &data));
        }
    }
}

// +--------------------------------------------------------------------+

int
DataLoader::LoadBuffer(const char* name, BYTE*& buf, bool null_terminate, bool optional)
{
    buf = 0;

    // assemble file name:
    char filename[1024];
    strcpy_s(filename, datapath);
    strcat_s(filename, name);

    if (use_file_system) {
        // first check current directory:
        FILE* f;
        ::fopen_s(&f, filename, "rb");

        if (f) {
            ::fseek(f, 0, SEEK_END);
            int len = ftell(f);
            ::fseek(f, 0, SEEK_SET);

            if (null_terminate) {
                buf = new(__FILE__,__LINE__) BYTE[len+1];
                if (buf)
                buf[len] = 0;
            }

            else {
                buf = new(__FILE__,__LINE__) BYTE[len];
            }

            if (buf)
            ::fread(buf, len, 1, f);

            ::fclose(f);

            return len;
        }
    }

    // then check datafile(s):
    int narchives = archives.size();

    // vox files are usually in their own archive,
    // so check there first
    if (narchives > 1 && strstr(filename, "Vox")) {
        for (int i = 0; i < narchives; i++) {
            DataArchive* a = archives[narchives-1-i];
            if (strstr(a->Name(), "vox")) {
                int index = a->FindEntry(filename);
                if (index > -1)
                return a->ExpandEntry(index, buf, null_terminate);
            }
        }
    }

    for (int i = 0; i < narchives; i++) {
        DataArchive* a = archives[narchives-1-i];
        int index = a->FindEntry(filename);
        if (index > -1)
        return a->ExpandEntry(index, buf, null_terminate);
    }

    if (!optional)
    Print("WARNING - DataLoader could not load buffer '%s'\n", filename);
    return 0;
}

// +--------------------------------------------------------------------+

int
DataLoader::LoadPartialFile(const char* name, BYTE*& buf, int max_load, bool optional)
{
    buf = 0;

    // assemble file name:
    char filename[1024];
    strcpy_s(filename, datapath);
    strcat_s(filename, name);

    // first check current directory:
    FILE* f;
    ::fopen_s(&f, filename, "rb");

    if (f) {
        ::fseek(f, 0, SEEK_END);
        int len = ftell(f);
        ::fseek(f, 0, SEEK_SET);

        if (len > max_load) {
            len = max_load;
        }

        buf = new(__FILE__,__LINE__) BYTE[len];

        if (buf)
        ::fread(buf, len, 1, f);

        ::fclose(f);

        return len;
    }

    if (!optional)
    Print("WARNING - DataLoader could not load partial file '%s'\n", filename);
    return 0;
}

int
DataLoader::fread(void* buffer, size_t size, size_t count, BYTE*& stream)
{
    CopyMemory(buffer, stream, size*count);
    stream += size*count;

    return size*count;
}

// +--------------------------------------------------------------------+

void
DataLoader::ReleaseBuffer(BYTE*& buf)
{
    delete [] buf;
    buf = 0;
}

// +--------------------------------------------------------------------+

int
DataLoader::CacheBitmap(const char* name, Bitmap*& bitmap, int type, bool optional)
{
    int      result = 0;

    // search cache:
    bitmap = Bitmap::CheckCache(name);
    if (bitmap) return 1;

    // not in cache yet:
    bitmap = new(__FILE__,__LINE__) Bitmap;

    if (bitmap)
    result = LoadBitmap(name, *bitmap, type, optional);

    if (result && bitmap)
    Bitmap::AddToCache(bitmap);

    return result;
}

// +--------------------------------------------------------------------+

int
DataLoader::LoadBitmap(const char* name, Bitmap& bitmap, int type, bool optional)
{
    if (!enable_media)
    return 0;

    int result = LoadIndexed(name, bitmap, type);

    // check for a matching high color bitmap:
    if (result == 1) {
        int hi_result = LoadHiColor(name, bitmap, type);

        if (hi_result == 2)
        result = 3;
    }

    bitmap.SetFilename(name);

    if (!result && !optional)
    Print("WARNING - DataLoader could not load bitmap '%s%s'\n", datapath.data(), name);

    return result;
}

// +--------------------------------------------------------------------+

int
DataLoader::LoadTexture(const char* name, Bitmap*& bitmap, int type, bool preload_cache, bool optional)
{
    if (!enable_media)
    return 0;

    int      result = 0;

    // assemble file name:
    char filename[256];
    strcpy_s(filename, datapath);
    strcat_s(filename, name);

    // search cache:
    bitmap = Bitmap::CheckCache(filename);
    if (bitmap) return 1;

    // not in cache yet:
    bitmap = new(__FILE__,__LINE__) Bitmap;

    if (bitmap) {
        result = LoadHiColor(name, *bitmap, type);

        if (!result) {
            result = LoadIndexed(name, *bitmap, type);
        }

        bitmap->SetFilename(filename);

        if (result) {
            bitmap->MakeTexture();
            Bitmap::AddToCache(bitmap);
        }
        else {
            delete bitmap;
            bitmap = 0;

            if (!optional)
            Print("WARNING - DataLoader could not load texture '%s%s'\n", datapath.data(), name);
        }
    }
    else if (!optional) {
        Print("WARNING - DataLoader could not allocate texture '%s%s'\n", datapath.data(), name);
    }

    return result;
}

// +--------------------------------------------------------------------+

int
DataLoader::LoadIndexed(const char* name, Bitmap& bitmap, int type)
{
    if (!enable_media)
    return 0;

    int         result = 0;
    PcxImage    pcx;
    D3DXImage   d3dx;
    bool        pcx_file = strstr(name, ".pcx") || strstr(name, ".PCX");

    // assemble file name:
    char filename[256];
    strcpy_s(filename, datapath);
    strcat_s(filename, name);

    // first try to load from current directory:
    bool loaded = false;

    if (use_file_system) {
        if (pcx_file)
        loaded = pcx.Load(filename) == PCX_OK;

        else
        loaded = d3dx.Load(filename);
    }

    if (!loaded) {
        // then check datafile:
        int   len     = 0;
        BYTE* tmp_buf = 0;

        int narchives = archives.size();
        for (int i = 0; i < narchives; i++) {
            DataArchive* a = archives[narchives-1-i];
            int index = a->FindEntry(filename);
            if (index > -1) {
                len = a->ExpandEntry(index, tmp_buf);

                if (pcx_file)
                pcx.LoadBuffer(tmp_buf, len);

                else
                d3dx.LoadBuffer(tmp_buf, len);

                ReleaseBuffer(tmp_buf);
                break;
            }
        }
    }

    // now copy the image into the bitmap:
    if (pcx_file) {
        if (pcx.bitmap) {
            bitmap.CopyImage(pcx.width, pcx.height, pcx.bitmap, type);
            result = 1;
        }

        else if (pcx.himap) {
            bitmap.CopyHighColorImage(pcx.width, pcx.height, pcx.himap, type);
            result = 2;
        }

        if (result == 2)
        LoadAlpha(name, bitmap, type);
    }

    else {
        if (d3dx.image) {
            bitmap.CopyHighColorImage(d3dx.width, d3dx.height, d3dx.image, type);
            result = 2;
        }

        if (result == 2) {
            LoadAlpha(name, bitmap, type);
        }
    }

    return result;
}

int
DataLoader::LoadHiColor(const char* name, Bitmap& bitmap, int type)
{
    if (!enable_media)
    return 0;

    int         result = 0;
    PcxImage    pcx;
    D3DXImage   d3dx;
    bool        pcx_file = strstr(name, ".pcx") || strstr(name, ".PCX");
    bool        bmp_file = strstr(name, ".bmp") || strstr(name, ".BMP");
    bool        png_file = strstr(name, ".png") || strstr(name, ".PNG");

    // check for a matching high color bitmap:
    char filename[256];
    char name2[256];
    strcpy_s(name2, name);

    char* dot = strrchr(name2, '.');
    if (dot && pcx_file)
    strcpy(dot, "+.pcx");
    else if (dot && bmp_file)
    strcpy(dot, "+.bmp");
    else if (dot && png_file)
    strcpy(dot, "+.png");
    else
    return result;

    strcpy_s(filename, datapath);
    strcat_s(filename, name2);

    // first try to load from current directory:
    bool loaded = false;

    if (use_file_system) {
        if (pcx_file)
        loaded = pcx.Load(filename) == PCX_OK;

        else
        loaded = d3dx.Load(filename);
    }

    if (!loaded) {
        // then check datafile:
        int   len     = 0;
        BYTE* tmp_buf = 0;

        int narchives = archives.size();
        for (int i = 0; i < narchives; i++) {
            DataArchive* a = archives[narchives-1-i];
            int index = a->FindEntry(filename);
            if (index > -1) {
                len = a->ExpandEntry(index, tmp_buf);

                if (pcx_file)
                pcx.LoadBuffer(tmp_buf, len);
                else
                d3dx.LoadBuffer(tmp_buf, len);

                ReleaseBuffer(tmp_buf);
                break;
            }
        }
    }

    // now copy the image into the bitmap:
    if (pcx_file && pcx.himap) {
        bitmap.CopyHighColorImage(pcx.width, pcx.height, pcx.himap, type);
        result = 2;
    }

    else if (d3dx.image) {
        bitmap.CopyHighColorImage(d3dx.width, d3dx.height, d3dx.image, type);
        result = 2;
    }

    if (result == 2)
    LoadAlpha(name, bitmap, type);

    return result;
}

int
DataLoader::LoadAlpha(const char* name, Bitmap& bitmap, int type)
{
    if (!enable_media)
    return 0;

    PcxImage    pcx;
    D3DXImage   d3dx;
    bool        pcx_file = strstr(name, ".pcx") || strstr(name, ".PCX");
    bool        bmp_file = strstr(name, ".bmp") || strstr(name, ".BMP");
    bool        png_file = strstr(name, ".png") || strstr(name, ".PNG");
    bool        tga_file = strstr(name, ".tga") || strstr(name, ".TGA");

    // check for an associated alpha-only (grayscale) bitmap:
    char filename[256];
    char name2[256];
    strcpy_s(name2, name);
    char* dot = strrchr(name2, '.');
    if (dot && pcx_file)
    strcpy(dot, "@.pcx");
    else if (dot && bmp_file)
    strcpy(dot, "@.bmp");
    else if (dot && png_file)
    strcpy(dot, "@.png");
    else if (dot && tga_file)
    strcpy(dot, "@.tga");
    else
    return 0;

    strcpy_s(filename, datapath);
    strcat_s(filename, name2);

    // first try to load from current directory:
    bool loaded = false;

    if (use_file_system) {
        if (pcx_file)
        loaded = pcx.Load(filename) == PCX_OK;

        else
        loaded = d3dx.Load(filename);
    }

    if (!loaded) {
        // then check datafile:
        int   len     = 0;
        BYTE* tmp_buf = 0;

        int narchives = archives.size();
        for (int i = 0; i < narchives; i++) {
            DataArchive* a = archives[narchives-1-i];
            int index = a->FindEntry(filename);
            if (index > -1) {
                len = a->ExpandEntry(index, tmp_buf);

                if (pcx_file)
                pcx.LoadBuffer(tmp_buf, len);
                else
                d3dx.LoadBuffer(tmp_buf, len);

                ReleaseBuffer(tmp_buf);
                break;
            }
        }
    }

    // now copy the alpha values into the bitmap:
    if (pcx_file && pcx.bitmap) {
        bitmap.CopyAlphaImage(pcx.width, pcx.height, pcx.bitmap);
    }
    else if (pcx_file && pcx.himap) {
        bitmap.CopyAlphaRedChannel(pcx.width, pcx.height, pcx.himap);
    }
    else if (d3dx.image) {
        bitmap.CopyAlphaRedChannel(d3dx.width, d3dx.height, d3dx.image);
    }

    return 0;
}

// +--------------------------------------------------------------------+

int
DataLoader::LoadSound(const char* name, Sound*& snd, DWORD flags, bool optional)
{
    if (!enable_media)
    return 0;

    if (strstr(name, ".ogg"))
    return LoadStream(name, snd, optional);

    int result = 0;

    WAVE_HEADER    head;
    WAVE_FMT       fmt;
    WAVE_FACT      fact;
    WAVE_DATA      data;
    WAVEFORMATEX   wfex;
    LPBYTE         wave;

    LPBYTE         buf;
    LPBYTE         p;
    int            len;

    ZeroMemory(&head, sizeof(head));
    ZeroMemory(&fmt,  sizeof(fmt));
    ZeroMemory(&fact, sizeof(fact));
    ZeroMemory(&data, sizeof(data));

    len = LoadBuffer(name, buf, false, optional);

    if (len > sizeof(head)) {
        CopyMemory(&head, buf, sizeof(head));

        if (head.RIFF == MAKEFOURCC('R', 'I', 'F', 'F') &&
                head.WAVE == MAKEFOURCC('W', 'A', 'V', 'E')) {

            p = buf + sizeof(WAVE_HEADER);

            do {
                DWORD chunk_id = *((LPDWORD) p);

                switch (chunk_id) {
                case MAKEFOURCC('f', 'm', 't', ' '):
                    CopyMemory(&fmt, p, sizeof(fmt));
                    p += fmt.chunk_size + 8;
                    break;

                case MAKEFOURCC('f', 'a', 'c', 't'):
                    CopyMemory(&fact, p, sizeof(fact));
                    p += fact.chunk_size + 8;
                    break;

                case MAKEFOURCC('s', 'm', 'p', 'l'):
                    CopyMemory(&fact, p, sizeof(fact));
                    p += fact.chunk_size + 8;
                    break;

                case MAKEFOURCC('d', 'a', 't', 'a'):
                    CopyMemory(&data, p, sizeof(data));
                    p += 8;
                    break;

                default:
                    ReleaseBuffer(buf);
                    return result;
                }
            }
            while (data.chunk_size == 0);

            wfex.wFormatTag      = fmt.wFormatTag;
            wfex.nChannels       = fmt.nChannels;
            wfex.nSamplesPerSec  = fmt.nSamplesPerSec;
            wfex.nAvgBytesPerSec = fmt.nAvgBytesPerSec;
            wfex.nBlockAlign     = fmt.nBlockAlign;
            wfex.wBitsPerSample  = fmt.wBitsPerSample;
            wfex.cbSize          = 0;
            wave                 = p;

            snd = Sound::Create(flags, &wfex, data.chunk_size, wave);

            if (snd)
            result = data.chunk_size;
        }
    }

    ReleaseBuffer(buf);
    return result;
}

int
DataLoader::LoadStream(const char* name, Sound*& snd, bool optional)
{
    if (!enable_media)
    return 0;

    if (!name)
    return 0;

    int namelen = strlen(name);

    if (namelen < 5)
    return 0;

    if ((name[namelen-3] == 'o' || name[namelen-3] == 'O') &&
            (name[namelen-2] == 'g' || name[namelen-2] == 'G') &&
            (name[namelen-1] == 'g' || name[namelen-1] == 'G')) {

        return LoadOggStream(name, snd);
    }

    int result = 0;

    WAVE_HEADER    head;
    WAVE_FMT       fmt;
    WAVE_FACT      fact;
    WAVE_DATA      data;
    WAVEFORMATEX   wfex;

    LPBYTE         buf;
    LPBYTE         p;
    int            len;

    ZeroMemory(&head, sizeof(head));
    ZeroMemory(&fmt,  sizeof(fmt));
    ZeroMemory(&fact, sizeof(fact));
    ZeroMemory(&data, sizeof(data));

    len = LoadPartialFile(name, buf, 4096, optional);

    if (len > sizeof(head)) {
        CopyMemory(&head, buf, sizeof(head));

        if (head.RIFF == MAKEFOURCC('R', 'I', 'F', 'F') &&
                head.WAVE == MAKEFOURCC('W', 'A', 'V', 'E')) {

            p = buf + sizeof(WAVE_HEADER);

            do {
                DWORD chunk_id = *((LPDWORD) p);

                switch (chunk_id) {
                case MAKEFOURCC('f', 'm', 't', ' '):
                    CopyMemory(&fmt, p, sizeof(fmt));
                    p += fmt.chunk_size + 8;
                    break;

                case MAKEFOURCC('f', 'a', 'c', 't'):
                    CopyMemory(&fact, p, sizeof(fact));
                    p += fact.chunk_size + 8;
                    break;

                case MAKEFOURCC('s', 'm', 'p', 'l'):
                    CopyMemory(&fact, p, sizeof(fact));
                    p += fact.chunk_size + 8;
                    break;

                case MAKEFOURCC('d', 'a', 't', 'a'):
                    CopyMemory(&data, p, sizeof(data));
                    p += 8;
                    break;

                default:
                    ReleaseBuffer(buf);
                    return result;
                }
            }
            while (data.chunk_size == 0);

            wfex.wFormatTag      = fmt.wFormatTag;
            wfex.nChannels       = fmt.nChannels;
            wfex.nSamplesPerSec  = fmt.nSamplesPerSec;
            wfex.nAvgBytesPerSec = fmt.nAvgBytesPerSec;
            wfex.nBlockAlign     = fmt.nBlockAlign;
            wfex.wBitsPerSample  = fmt.wBitsPerSample;
            wfex.cbSize          = 0;

            snd = Sound::Create(Sound::STREAMED, &wfex);

            if (snd) {
                // assemble file name:
                char filename[1024];
                strcpy_s(filename, datapath);
                strcat_s(filename, name);

                snd->StreamFile(filename, p - buf);

                result = data.chunk_size;
            }
        }
    }

    ReleaseBuffer(buf);
    return result;
}

int
DataLoader::LoadOggStream(const char* name, Sound*& snd)
{
    if (!enable_media)
    return 0;

    snd = Sound::CreateOggStream(name);

    return snd != 0;
}