Debian Codegraph @

src/audio/castlesoundengine_repoengine.inc

raw
1 {%MainUnit castlesoundengine.pas}
2 {
3 Copyright 2010-2024 Michalis Kamburelis.
4
5 This file is part of "Castle Game Engine".
6
7 "Castle Game Engine" is free software; see the file COPYING.txt,
8 included in this distribution, for details about the copyright.
9
10 "Castle Game Engine" is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
13
14 ----------------------------------------------------------------------------
15 }
16
17 {$ifdef read_interface}
18
19 //type // allow type declaration to continue
20
21 { Unique sound type identifier for sounds used within TRepoSoundEngine. }
22 TSoundType = TCastleSound deprecated 'use TCastleSound';
23
24 { Sound engine that keeps a repository of sounds, defined in a nice XML file.
25 Loading this XML file by setting @link(RepositoryUrl) property
26 creates a number of TCastleSound instances, that you can find using
27 @link(SoundFromName) method. You can use these TCastleSound instances
28 e.g. with @link(TSoundEngine.Play) method.
29
30 This class extends TSoundEngine. So using the sounds defined in the XML file
31 is completely optional. You can also create instances of TCastleSound
32 and use them through any other means -- by code, by setting them up in editor,
33 see https://castle-engine.io/manual_sound.php . }
34 TRepoSoundEngine = class(TSoundEngine)
35 private
36 {$ifndef PASDOC} // PasDoc cannot parse the private section of this correctly yet
37 type
38 TSoundInfoBuffer = class;
39 TSoundInfoList = class;
40 TSoundGroup = class;
41
42 { Sound that can be played -- actual sound with buffer, or an alias to it. }
43 TSoundInfo = class
44 strict private
45 { Although we only support one instance of TSoundEngine,
46 in @link(SoundEngine), but it seems more future-proof
47 to store in TSoundInfo own reference to TSoundEngine.
48 Automatically assigned in ReadElement. }
49 FOwningSoundEngine: TSoundEngine;
50 strict protected
51 property OwningSoundEngine: TSoundEngine read FOwningSoundEngine;
52 public
53 { Unique sound name (including parent group names). Empty for the special sound stNone = nil. }
54 Name: String;
55
56 { Like Name, but without parent group names.
57 Unique within the ParentGroup (not necessarily unique among all sounds). }
58 ShortName: String;
59
60 { A group (one among FSoundGroups, or @nil if not in any group). }
61 ParentGroup: TSoundGroup;
62
63 { Read a sound from XML element <sound> or <alias>. }
64 procedure ReadElement(const Element: TDOMElement;
65 const AParentGroup: TSoundGroup;
66 const BaseUrl: String; const ASoundEngine: TRepoSoundEngine); virtual;
67
68 { Do some finalization once all sounds are known, and their names are known. }
69 procedure ResolveNames(const AllSounds: TSoundInfoList); virtual;
70
71 { Get the final TSoundInfoBuffer, resolving aliases. }
72 function FinalSound(const RecursionDepth: Cardinal): TSoundInfoBuffer; virtual; abstract;
73 end;
74
75 { List of TSoundInfo. }
76 TSoundInfoList = class({$ifdef FPC}specialize{$endif} TObjectList<TSoundInfo>)
77 public
78 { Index of sound with given TSoundInfo.Name, or -1 if not found. }
79 function IndexOfName(const SoundName: String): Integer;
80 end;
81
82 { Sound that can be played, as an alias to a number of other TSoundInfo instances
83 (an alias may lead to another alias, that's OK, as long as eventually it
84 resolves into actual sound name). }
85 TSoundInfoAlias = class(TSoundInfo)
86 strict private
87 Target: TCastleStringList;
88 public
89 constructor Create;
90 destructor Destroy; override;
91 procedure ReadElement(const Element: TDOMElement;
92 const AParentGroup: TSoundGroup;
93 const BaseUrl: String; const ASoundEngine: TRepoSoundEngine); override;
94 procedure ResolveNames(const AllSounds: TSoundInfoList); override;
95 function FinalSound(const RecursionDepth: Cardinal): TSoundInfoBuffer; override;
96 end;
97
98 { Sound that can be played, with a buffer. }
99 TSoundInfoBuffer = class(TSoundInfo)
100 public
101 Sound: TCastleSound;
102 procedure ReadElement(const Element: TDOMElement;
103 const AParentGroup: TSoundGroup;
104 const BaseUrl: String; const ASoundEngine: TRepoSoundEngine); override;
105 function FinalSound(const RecursionDepth: Cardinal): TSoundInfoBuffer; override;
106 destructor Destroy; override;
107 end;
108
109 TSoundGroup = class(TSoundInfoList)
110 public
111 { Group name (including parent group names). }
112 Name: string;
113 { Group URL.
114 Absolute (including parent group URL parts).
115 Always ends with slash. }
116 Url: String;
117 { A parent group (one among FSoundGroups, or @nil if not in any group). }
118 ParentGroup: TSoundGroup;
119 end;
120
121 TSoundGroupList = class({$ifdef FPC}specialize{$endif} TObjectList<TSoundGroup>)
122 public
123 { Index of group with given TSoundGroup.Name, or -1 if not found. }
124 function IndexOfName(const GroupName: String): Integer;
125 end;
126
127 TLoopingChannelList = {$ifdef FPC}specialize{$endif} TObjectList<TLoopingChannel>;
128
129 var
130 FSoundImportanceNames: TStringList;
131 { A list of sounds used by your program.
132 Each sound has a unique name, used to identify sound in
133 the XML file and for SoundFromName function.
134
135 At the beginning, this list always contains exactly one sound, empty.
136 This is a special TSoundInfoBuffer that has Sound=nil and Name=''.
137 It means "no sound" in many cases. }
138 FSounds: TSoundInfoList;
139 FSoundGroups: TSoundGroupList;
140 FRepositoryUrl: String;
141 FLoopingChannels: TLoopingChannelList;
142 {$endif PASDOC}
143
144 procedure SetRepositoryUrl(const Value: String);
145 { Reinitialize looping channels sounds.
146 Should be called as soon as Sounds changes and we may have OpenAL context. }
147 procedure RestartLoopingChannels;
148 function GetLoopingChannel(const Index: Cardinal): TLoopingChannel;
149 procedure ContextOpenCore; override;
150
151 { Sound importance names and values.
152 *Maintained only to provide backward compatibility when reading sound XML files*.
153
154 Each item is a name (as a string) and a value (that is stored in Objects
155 property of the item as a pointer; add new importances by
156 AddSoundImportanceName for comfort).
157
158 These can be used within sounds.xml file.
159 Before using ContextOpen, you can fill this list with values.
160
161 Initially, it contains a couple of useful values (ordered here
162 from most to least important):
163
164 @unorderedList(
165 @item 'max' - MaxSoundImportance
166 @item 'level_event' - LevelEventSoundImportance
167 @item 'player' - PlayerSoundImportance
168 @item 'default_creature' - DefaultCreatureSoundImportance
169 @item 'minor_non_spatial' - MinorNonSpatialSoundImportance
170 @item 'default' - DefaultSoundImportance
171 ) }
172 property SoundImportanceNames: TStringList read FSoundImportanceNames;
173 procedure AddSoundImportanceName(const Name: string; Importance: Integer);
174 public
175 constructor Create;
176 destructor Destroy; override;
177
178 { The XML file that contains description of your sounds.
179 This should be an URL (in simple cases, just a filename)
180 pointing to an XML file describing your sounds.
181 See https://castle-engine.io/creating_data_sound.php#section_sample .
182
183 When you set RepositoryUrl property, we read sound information from
184 given XML file. You usually set RepositoryUrl at the very beginning
185 of the application.
186 Right after setting RepositoryUrl you usually call SoundFromName
187 a couple of times to convert some names into TCastleSound values,
188 to later use these TCastleSound values with @link(Play) or
189 @link(TCastleSoundSource.Sound).
190
191 When the sound context is initialized (or when you set this property,
192 if the sound context is initialized already)
193 then sound buffers will actually be loaded.
194
195 If this is empty (the default), then no sounds are loaded,
196 and TRepoSoundEngine doesn't really give you much above standard
197 TSoundEngine.
198
199 If you want to actually use TRepoSoundEngine features you have to set this
200 property. For example like this:
201
202 @longCode(#
203 SoundEngine.RepositoryUrl := 'castle-data:/sounds.xml';
204 MySound1 := SoundEngine.SoundFromName('my_sound_1');
205 MySound2 := SoundEngine.SoundFromName('my_sound_2');
206 // ... and later in your game you can do stuff like this:
207 SoundEngine.Play(MySound1);
208 #)
209
210 See https://castle-engine.io/data
211 for information about the castle-data:/ protocol. In short, on desktop,
212 this just indicates the "data" subdirectory of your project.
213 }
214 property RepositoryUrl: String read FRepositoryUrl write SetRepositoryUrl;
215 {$ifdef FPC}deprecated 'instead of XML file, create design with .castle-component that contains a number of TCastleSound components';{$endif}
216
217 { Reload the RepositoryUrl and all referenced buffers.
218 Useful as a tool for game designers, to reload the sounds XML file
219 without restarting the game and sound engine. }
220 procedure ReloadSounds; deprecated 'deprecated just like RepositoryUrl';
221
222 { Return sound with given name.
223 Available names are given in SoundNames, defined in XML file pointed
224 by RepositoryUrl.
225 Always for SoundName = '' it will return nil.
226
227 @param(Required
228
229 If Required = @true, it will make a warning when the sound name
230 is not found. This may mean that sound is missing in your sounds.xml
231 file (so you should correct your sounds.xml),
232 or that you didn't load the sounds.xml file yet
233 (so you should correct your code to set @link(TRepoSoundEngine.RepositoryUrl)
234 early enough), or that you specified invalid sound name.
235 When Required = @false, missing sound is silently ignored,
236 which is sensible if it was optional.
237
238 Regardless of the Required value, we return nil for missing sound.
239 So the Required parameter only determines whether we make a warning,
240 or not.)
241 }
242 function SoundFromName(const SoundName: string; const Required: boolean = true): TCastleSound;
243 deprecated 'deprecated just like RepositoryUrl';
244
245 { Comfortable way to play and control looping non-spatial sounds, like music tracks, ambience.
246
247 The TLoopingChannel instance automatically remembers the sound it plays.
248 You start playing just by setting @link(TLoopingChannel.Sound)
249 to some sound. For example:
250
251 @longCode(# LoopingChannel[0].Sound := MyMusicTrack; #)
252
253 You stop by setting @link(TLoopingChannel.Sound) to something else,
254 which can be @nil to just stop playing any looping
255 sound on this channel. For example:
256
257 @longCode(# LoopingChannel[0].Sound := nil; #)
258
259 Each channel has it's own @link(TLoopingChannel.Volume)
260 that can be changed at any point.
261
262 All the looping channels play simultaneously.
263
264 Note: Alternative way to play looping non-spatial sounds
265 is to use @link(Play) with @link(TCastlePlayingSound) (setting
266 @link(TCastlePlayingSound.Loop) to @true). }
267 property LoopingChannel [const Index: Cardinal]: TLoopingChannel
268 read GetLoopingChannel;
269
270 { Opens sound context and loads sound files,
271 but only if RepositoryUrl was set and contains some sounds.
272
273 The idea is that you can call this during "loading" stage for any game that
274 *possibly but not necessarily* uses sound. If a game doesn't use sound,
275 this does nothing (doesn't waste time to even initialize sound context,
276 which on some systems may cause some warnings).
277 If a game uses sound (through RepositoryUrl), this will initialize
278 sound backend and load these sound files, to play them without any delay
279 in game.
280
281 Note that, if this does nothing, but you later set @link(RepositoryUrl)
282 or use @link(Play), then sound context will
283 be created on-demand anyway. So calling this is always optional. }
284 procedure PrepareResources; deprecated 'deprecated just like RepositoryUrl';
285 end;
286
287 {$endif read_interface}
288
289 {$ifdef read_implementation}
290
291 { TSoundInfoList ------------------------------------------------------------- }
292
293 function TRepoSoundEngine.TSoundInfoList.IndexOfName(const SoundName: String): Integer;
294 begin
295 for Result := 0 to Count - 1 do
296 if Items[Result].Name = SoundName then
297 Exit;
298 Result := -1;
299 end;
300
301 { TSoundGroupList ------------------------------------------------------------- }
302
303 function TRepoSoundEngine.TSoundGroupList.IndexOfName(
304 const GroupName: String): Integer;
305 begin
306 for Result := 0 to Count - 1 do
307 if Items[Result].Name = GroupName then
308 Exit;
309 Result := -1;
310 end;
311
312 { TRepoSoundEngine.TSoundInfo ------------------------------------------------ }
313
314 procedure TRepoSoundEngine.TSoundInfo.ReadElement(const Element: TDOMElement;
315 const AParentGroup: TSoundGroup;
316 const BaseUrl: String; const ASoundEngine: TRepoSoundEngine);
317 begin
318 FOwningSoundEngine := ASoundEngine;
319 ShortName := Element.AttributeString('name');
320 Name := ShortName;
321
322 ParentGroup := AParentGroup;
323 if ParentGroup <> nil then
324 Name := ParentGroup.Name + '/' + Name;
325 end;
326
327 procedure TRepoSoundEngine.TSoundInfo.ResolveNames(const AllSounds: TSoundInfoList);
328 begin
329 end;
330
331 { TRepoSoundEngine.TSoundInfoAlias ------------------------------------------- }
332
333 constructor TRepoSoundEngine.TSoundInfoAlias.Create;
334 begin
335 inherited;
336 Target := TCastleStringList.Create;
337 end;
338
339 destructor TRepoSoundEngine.TSoundInfoAlias.Destroy;
340 begin
341 FreeAndNil(Target);
342 inherited;
343 end;
344
345 procedure TRepoSoundEngine.TSoundInfoAlias.ReadElement(const Element: TDOMElement;
346 const AParentGroup: TSoundGroup;
347 const BaseUrl: String; const ASoundEngine: TRepoSoundEngine);
348 var
349 I: TXMLElementIterator;
350 TargetName: String;
351 begin
352 inherited;
353
354 I := Element.ChildrenIterator('target');
355 try
356 while I.GetNext do
357 begin
358 TargetName := I.Current.AttributeString('name');
359 if ParentGroup <> nil then
360 TargetName := ParentGroup.Name + '/' + TargetName;
361 Target.Add(TargetName);
362 end;
363 finally FreeAndNil(I) end;
364
365 if Target.Count = 0 then
366 raise EInvalidSoundRepositoryXml.CreateFmt('Alias "%s" does not define any targets',
367 [Name]);
368
369 if Target.Count > 1 then
370 WritelnWarning('Choosing sound at random is no longer supported, alias "%s" is no longer a random sound', [
371 Name
372 ]);
373 end;
374
375 procedure TRepoSoundEngine.TSoundInfoAlias.ResolveNames(const AllSounds: TSoundInfoList);
376 var
377 I, TargetIndex: Integer;
378 begin
379 inherited;
380
381 for I := 0 to Target.Count - 1 do
382 begin
383 TargetIndex := AllSounds.IndexOfName(Target[I]);
384 if TargetIndex = -1 then
385 raise EInvalidSoundRepositoryXml.CreateFmt('Alias "%s" target "%s" not found',
386 [Name, Target[I]]);
387 Target.Objects[I] := AllSounds[TargetIndex];
388 end;
389 end;
390
391 function TRepoSoundEngine.TSoundInfoAlias.FinalSound(const RecursionDepth: Cardinal): TSoundInfoBuffer;
392 const
393 MaxRecursionDepth = 100;
394 var
395 RandomTarget: TSoundInfo;
396 begin
397 RandomTarget := Target.Objects[Random(Target.Count)] as TSoundInfo;
398 { Instead of returning RandomTarget, we return RandomTarget.FinalSound.
399 This way an <alias> may point to another <alias>.
400 To avoid infinite loop, we use MaxRecursionDepth. }
401 if RecursionDepth > MaxRecursionDepth then
402 raise EInvalidSoundRepositoryXml.CreateFmt('Possible infinite loop when trying to resolve sound alias, detected at alias "%s". Recursion depth %s reached.',
403 [Name, RecursionDepth]);
404 Result := RandomTarget.FinalSound(RecursionDepth + 1);
405 end;
406
407 { TRepoSoundEngine.TSoundInfoBuffer ------------------------------------------ }
408
409 procedure TRepoSoundEngine.TSoundInfoBuffer.ReadElement(const Element: TDOMElement;
410 const AParentGroup: TSoundGroup;
411 const BaseUrl: String; const ASoundEngine: TRepoSoundEngine);
412 var
413 Url, ImportanceStr, UrlPrefix: String;
414 SoundImportanceIndex: Integer;
415 begin
416 inherited;
417
418 FreeAndNil(Sound);
419 Sound := TCastleSound.Create(nil);
420
421 { retrieve URL using AttributeString
422 (that internally uses Element.Attributes.GetNamedItem),
423 because we have to distinguish between the case when url/file_name
424 attribute is not present (in this case URL is left as it was)
425 and when it's present and set to empty string
426 (in this case URL must also be set to empty string).
427 Standard Element.GetAttribute wouldn't allow me this. }
428 Url := '';
429 if (Element.AttributeString('url', Url) or
430 Element.AttributeString('file_name', Url)) and
431 (Url <> '') then
432 begin
433 Url := CombineURI(BaseUrl, Url);
434 end else
435 begin
436 UrlPrefix := CombineURI(BaseUrl, ShortName);
437 if URIFileExists(UrlPrefix + '.ogg') then
438 Url := UrlPrefix + '.ogg'
439 else
440 if URIFileExists(UrlPrefix + '.wav') then
441 Url := UrlPrefix + '.wav'
442 else
443 WritelnWarning('No matching sound file found for sound "%s"', [Name]);
444 end;
445
446 if Element.HasAttribute('gain') then
447 begin
448 Sound.Volume := Element.AttributeSingleDef('gain', 1);
449 WritelnWarning('Sound "%s": "gain" has been deprecated in sounds XML, use "volume" now', [Name]);
450 end else
451 Sound.Volume := Element.AttributeSingleDef('volume', 1);
452
453 {$warnings off} // using unportable symbols knowingly
454 Sound.MinGain := Element.AttributeSingleDef('min_gain', 0);
455 Sound.MaxGain := Element.AttributeSingleDef('max_gain', 1);
456
457 { MaxGain is max 1. Although some sound backends (like some OpenAL backends)
458 implementations allow > 1,
459 Windows implementation of OpenAL (from Creative) doesn't.
460 For consistent results, we don't allow it anywhere. }
461 if Sound.MaxGain > 1 then
462 begin
463 WritelnWarning('Sound "%s": "max_gain" max value is 1.0', [Name]);
464 Sound.MaxGain := 1;
465 end;
466 {$warnings on}
467
468 if Element.AttributeString('default_importance', ImportanceStr) then
469 begin
470 WritelnWarning('Sound "%s": Use "priority" (float, in 0..1 range) instead of "importance" in sounds XML file', [
471 Name
472 ]);
473
474 SoundImportanceIndex := ASoundEngine.SoundImportanceNames.IndexOf(ImportanceStr);
475 if SoundImportanceIndex = -1 then
476 Sound.Priority := ImportanceToPriority(StrToInt(ImportanceStr))
477 else
478 Sound.Priority := ImportanceToPriority(
479 PtrUInt(ASoundEngine.SoundImportanceNames.Objects[SoundImportanceIndex]));
480 end else
481 Sound.Priority := Element.AttributeSingleDef('priority', 0.5);
482
483 Sound.Stream := Element.AttributeBooleanDef('stream', false);
484
485 { set URL at the end, to avoid reloading when Sound.Stream changes }
486 Sound.Url := Url;
487 end;
488
489 function TRepoSoundEngine.TSoundInfoBuffer.FinalSound(const RecursionDepth: Cardinal): TSoundInfoBuffer;
490 begin
491 Result := Self;
492 end;
493
494 destructor TRepoSoundEngine.TSoundInfoBuffer.Destroy;
495 begin
496 FreeAndNil(Sound);
497 inherited;
498 end;
499
500 { TRepoSoundEngine ----------------------------------------------------------- }
501
502 constructor TRepoSoundEngine.Create;
503 begin
504 // We need to set global FSoundEngine early, to make UseOpenALSoundBackend work
505 FSoundEngine := Self;
506
507 inherited;
508
509 { Sound importance names and sound names are case-sensitive because
510 XML traditionally is also case-sensitive.
511 Maybe in the future we'll relax this,
512 there's no definite reason actually to not let them ignore case. }
513 FSoundImportanceNames := TStringList.Create;
514 FSoundImportanceNames.CaseSensitive := true;
515
516 AddSoundImportanceName('max', MaxSoundImportance);
517 AddSoundImportanceName('level_event', LevelEventSoundImportance);
518 AddSoundImportanceName('player', PlayerSoundImportance);
519 AddSoundImportanceName('default_creature', DefaultCreatureSoundImportance);
520 AddSoundImportanceName('minor_non_spatial', MinorNonSpatialSoundImportance);
521 AddSoundImportanceName('default', DefaultSoundImportance);
522
523 FSoundGroups := TSoundGroupList.Create;
524
525 FSounds := TSoundInfoList.Create;
526 { add stNone = nil sound }
527 FSounds.Add(TSoundInfoBuffer.Create);
528
529 FLoopingChannels := TLoopingChannelList.Create(true);
530 end;
531
532 destructor TRepoSoundEngine.Destroy;
533 begin
534 FreeAndNil(FSoundImportanceNames);
535 FreeAndNil(FSounds);
536 FreeAndNil(FSoundGroups);
537 FreeAndNil(FLoopingChannels);
538 inherited;
539 end;
540
541 procedure TRepoSoundEngine.ContextOpenCore;
542 begin
543 inherited;
544 RestartLoopingChannels;
545 end;
546
547 procedure TRepoSoundEngine.RestartLoopingChannels;
548 var
549 L: TLoopingChannel;
550 begin
551 { allocate sound for all TLoopingChannel }
552 if IsContextOpenSuccess then
553 for L in FLoopingChannels do
554 if (L <> nil) and (L.FAllocatedSource = nil) then
555 L.AllocateSource;
556 end;
557
558 procedure TRepoSoundEngine.SetRepositoryUrl(const Value: String);
559
560 { Check that SoundInfo.Name is unique. }
561 procedure CheckUniqueSoundInfo(var SoundInfo: TSoundInfo);
562 begin
563 if FSounds.IndexOfName(SoundInfo.Name) <> -1 then
564 raise EInvalidSoundRepositoryXml.CreateFmt('Sound name "%s" is not unique',
565 [SoundInfo.Name]);
566 end;
567
568 { Check that Group.Name is unique. }
569 procedure CheckUniqueGroup(var Group: TSoundGroup);
570 begin
571 if FSoundGroups.IndexOfName(Group.Name) <> -1 then
572 raise EInvalidSoundRepositoryXml.CreateFmt('Group name "%s" is not unique',
573 [Group.Name]);
574 end;
575
576 procedure ReadGroup(const Group: TSoundGroup;
577 const Element: TDOMElement;
578 const ParentGroup: TSoundGroup;
579 const BaseUrl: String); forward;
580
581 { Read <group> child XML element, like <sound> or <alias> or another <group>. }
582 procedure ReadGroupChild(const Element: TDOMElement;
583 const ParentGroup: TSoundGroup;
584 const BaseUrl: String);
585 var
586 SoundInfo: TSoundInfo;
587 Group: TSoundGroup;
588 begin
589 if Element.TagName = 'sound' then
590 begin
591 SoundInfo := TSoundInfoBuffer.Create;
592 try
593 SoundInfo.ReadElement(Element, ParentGroup, BaseUrl, Self);
594 CheckUniqueSoundInfo(SoundInfo);
595 except
596 { In case SoundInfo.ReadElement fails (e.g. because LoadBuffer failed),
597 or in case CheckUniqueSoundInfo fails (name not unique), avoid memory leaks. }
598 FreeAndNil(SoundInfo);
599 raise;
600 end;
601 FSounds.Add(SoundInfo);
602 end else
603 if Element.TagName = 'alias' then
604 begin
605 SoundInfo := TSoundInfoAlias.Create;
606 try
607 SoundInfo.ReadElement(Element, ParentGroup, BaseUrl, Self);
608 CheckUniqueSoundInfo(SoundInfo);
609 except
610 FreeAndNil(SoundInfo);
611 raise;
612 end;
613 FSounds.Add(SoundInfo);
614 end else
615 if Element.TagName = 'group' then
616 begin
617 Group := TSoundGroup.Create;
618 try
619 ReadGroup(Group, Element, ParentGroup, BaseUrl);
620 CheckUniqueGroup(Group);
621 except
622 FreeAndNil(Group);
623 raise;
624 end;
625 { Adding Group to FSoundGroups makes TSoundGroup freed later. }
626 FSoundGroups.Add(Group);
627 end else
628 raise EInvalidSoundRepositoryXml.CreateFmt('Invalid XML element "%s" in sounds XML file',
629 [Element.TagName]);
630 end;
631
632 { Read a group of sounds from XML element <group>. }
633 procedure ReadGroup(const Group: TSoundGroup;
634 const Element: TDOMElement;
635 const ParentGroup: TSoundGroup;
636 const BaseUrl: String);
637 var
638 I: TXMLElementIterator;
639 Subdirectory: String;
640 begin
641 Group.ParentGroup := ParentGroup;
642
643 { calculate Group.Name }
644 Group.Name := Element.AttributeString('name');
645 if ParentGroup <> nil then
646 Group.Name := ParentGroup.Name + '/' + Group.Name;
647
648 Group.Url := BaseUrl;
649 Subdirectory := Element.AttributeStringDef('subdirectory', '');
650 if Subdirectory <> '' then
651 Group.Url := Group.Url + Subdirectory + '/';
652
653 I := Element.ChildrenIterator;
654 try
655 while I.GetNext do
656 ReadGroupChild(I.Current, Group, Group.Url);
657 finally FreeAndNil(I) end;
658 end;
659
660 procedure ResolveNames;
661 var
662 S: TSoundInfo;
663 begin
664 for S in FSounds do
665 S.ResolveNames(FSounds);
666 end;
667
668 var
669 SoundConfig: TXMLDocument;
670 Stream: TStream;
671 I: TXMLElementIterator;
672 BaseUrl: String;
673 TimeStart: TCastleProfilerTime;
674 begin
675 if FRepositoryUrl = Value then Exit;
676 FRepositoryUrl := Value;
677
678 FSoundGroups.Clear;
679 FSounds.Clear;
680 { add stNone = nil sound }
681 FSounds.Add(TSoundInfoBuffer.Create);
682
683 { if no sounds XML file, then that's it --- no more sounds }
684 if FRepositoryUrl = '' then Exit;
685
686 TimeStart := Profiler.Start('Loading All Sounds From ' + FRepositoryUrl + ' (TRepoSoundEngine)');
687 try
688 { This must be an absolute path, since FSounds[].Url should be
689 absolute (to not depend on the current dir when loading sound files. }
690 BaseUrl := AbsoluteURI(FRepositoryUrl);
691
692 Stream := Download(BaseUrl);
693 try
694 ReadXMLFile(SoundConfig, Stream, BaseUrl);
695 finally FreeAndNil(Stream) end;
696
697 // cut off last part from BaseUrl, for ReadSound / ReadGroup calls
698 BaseUrl := ExtractURIPath(BaseUrl);
699
700 try
701 Check(SoundConfig.DocumentElement.TagName = 'sounds',
702 'Root node of sounds/index.xml must be <sounds>');
703
704 { TODO: This could display a progress bar using Progress.Init / Fini
705 if IsContextOpenSuccess, since it loads sounds in this case (calls LoadBuffer),
706 so can take a while. }
707
708 I := SoundConfig.DocumentElement.ChildrenIterator;
709 try
710 while I.GetNext do
711 ReadGroupChild(I.Current, nil, BaseUrl);
712 finally FreeAndNil(I) end;
713 finally
714 FreeAndNil(SoundConfig);
715 end;
716
717 ResolveNames;
718
719 { read common sound names }
720 {$warnings off} // initialize deprecated symbols knowingly
721 stPlayerInteractFailed := SoundFromName('player_interact_failed', false);
722 stPlayerSuddenPain := SoundFromName('player_sudden_pain', false);
723 stPlayerPickItem := SoundFromName('player_pick_item', false);
724 stPlayerDropItem := SoundFromName('player_drop_item', false);
725 stPlayerDies := SoundFromName('player_dies', false);
726 stPlayerSwimmingChange := SoundFromName('player_swimming_change', false);
727 stPlayerSwimming := SoundFromName('player_swimming', false);
728 stPlayerDrowning := SoundFromName('player_drowning', false);
729 stPlayerFootstepsDefault := SoundFromName('player_footsteps_default', false);
730 stPlayerToxicPain := SoundFromName('player_toxic_pain', false);
731
732 stMenuCurrentItemChanged := SoundFromName('menu_current_item_changed', false);
733 stMenuClick := SoundFromName('menu_click' , false);
734 {$warnings on}
735
736 { in case you set RepositoryUrl when sound context is already
737 initialized, start playing music immediately if necessary }
738 RestartLoopingChannels;
739
740 finally Profiler.Stop(TimeStart) end;
741 end;
742
743 procedure TRepoSoundEngine.ReloadSounds;
744 var
745 OldRepositoryUrl: String;
746 begin
747 {$warnings off} // using deprecated in deprecated
748 if RepositoryUrl <> '' then
749 begin
750 OldRepositoryUrl := RepositoryUrl;
751 RepositoryUrl := '';
752 RepositoryUrl := OldRepositoryUrl;
753 end;
754 {$warnings on}
755 end;
756
757 function TRepoSoundEngine.SoundFromName(const SoundName: string;
758 const Required: boolean): TCastleSound;
759 var
760 SoundIndex: Integer;
761 begin
762 SoundIndex := FSounds.IndexOfName(SoundName);
763 if SoundIndex <> -1 then
764 begin
765 Result := FSounds[SoundIndex].FinalSound(0).Sound;
766 end else
767 begin
768 Result := nil;
769 if Required then
770 WritelnWarning('Sound', Format('Unknown sound name "%s"', [SoundName]));
771 end;
772 end;
773
774 procedure TRepoSoundEngine.AddSoundImportanceName(const Name: string;
775 Importance: Integer);
776 begin
777 FSoundImportanceNames.AddObject(Name, TObject(Pointer(PtrUInt(Importance))));
778 end;
779
780 procedure TRepoSoundEngine.PrepareResources;
781 begin
782 if not IsContextOpen and (FSounds.Count > 1) then
783 ContextOpen;
784 end;
785
786 function TRepoSoundEngine.GetLoopingChannel(const Index: Cardinal): TLoopingChannel;
787 begin
788 { On demand, resize FLoopingChannels list and create new TLoopingChannel.
789 Note that FLoopingChannels may have nils along the way. }
790 if Index >= FLoopingChannels.Count then
791 FLoopingChannels.Count := Index + 1;
792 Assert(Index < FLoopingChannels.Count);
793
794 if FLoopingChannels[Index] = nil then
795 FLoopingChannels[Index] := TLoopingChannel.Create(Self);
796
797 Result := FLoopingChannels[Index];
798 end;
799
800 {$endif read_implementation}