summaryrefslogtreecommitdiffhomepage
path: root/StarsEx/DataLoader.cpp
blob: 487dead34578039f3f01d38ced299e62c49f8677 (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
/*  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 "DataLoader.h"
#include "DataSource.h"
#include "Archive.h"
#include "Color.h"
#include "D3DXImage.h"
#include "Bitmap.h"
#include "Bmp.h"
#include "Pcx.h"
#include "Sound.h"
#include "Wave.h"

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

DataLoader*   DataLoader::loader = 0;

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

DataLoader::DataLoader() :
    datapath(""),
    enable_media(true),
    work_directory_source(new FileSystemDataSource())
{
}

DataLoader::~DataLoader()
{
    archives.destroy();
    sources.destroy();
    delete work_directory_source;
}

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

void
DataLoader::Initialize()
{
    if (!loader) {
        loader = new DataLoader;
    }
}

void
DataLoader::Close()
{
    Bitmap::ClearCache();
    delete loader;
    loader = nullptr;
}

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

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

const char*
DataLoader::LastError() const
{
    return last_error;
}

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

void
DataLoader::UseFileSystem(bool use)
{
    if (work_directory_source) {
        if (!use) {
            delete work_directory_source;  // This is wasteful
            work_directory_source = nullptr;
        }
    }
    else if (use) {
        work_directory_source = new FileSystemDataSource();
    }
}

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

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

int
DataLoader::MountDatafile(const char* name, Group group, int pos)
{
    FILE* f = fopen(name, "rb");
    if (!f) {
        last_error = Text::format("Could not open datafile '%s'", name);
        return FAILED;
    }
    fclose(f);
    auto archive = new DataArchive(name);
    if (!archive || archive->NumFiles() < 1) {
        last_error = Text::format("Invalid datafile '%s'", name);
        if (archive) delete archive;
        return FAILED;
    }
    DataSource* source = new ArchiveDataSource(archive, group);
    if (pos < 0)
        sources.append(source);
    else
        sources.insert(source, pos);
    return source->Id();
}

int
DataLoader::UnmountSource(int src)
{
    ListIter<DataSource> iter = sources;
    while (++iter) {
        if (iter.value()->Id() == src) {
            delete iter.removeItem();
            return src;
        }
    }
    last_error = Text::format("Source with id is not mounted: %d", src);
    return FAILED;
}

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

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

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

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

        DataArchive* a = new DataArchive(name);

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

            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 {
            last_error = Text::format("Invalid datafile '%s'", name);
            status = FAILED;
            delete a;
        }

        loader   = this;
    }
    else {
        last_error = Text::format("Could not open datafile '%s'", name);
        status = FAILED;
    }

    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 0;
        }
    }

    return FAILED;
}

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

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 (work_directory_source) {
        bool found = work_directory_source->Find(datapath, name);
        if (found)
            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 (work_directory_source) {
        work_directory_source->ListFiles(base_path, filter, list, recurse);
    }
}

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

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 (work_directory_source) {
        int len = work_directory_source->Load(datapath, name, buf, null_terminate);
        if (len > 0)
            return len;
        if (buf)
            delete buf;
    }

    // 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 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 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 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 (work_directory_source) {
        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 (work_directory_source) {
        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 (work_directory_source) {
        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;
}