| 1 |
{%MainUnit x3dnodes.pas} |
| 2 |
{ |
| 3 |
Copyright 2002-2023 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 |
{ Base for all sound nodes. } |
| 19 |
TAbstractSoundNode = class(TAbstractChildNode) |
| 20 |
{$I auto_generated_node_helpers/x3dnodes_x3dsoundnode.inc} |
| 21 |
end; |
| 22 |
|
| 23 |
{ Base class for most (but not all) nodes that can emit audio data. |
| 24 |
We may introduce TSoundSourceFunctionality is needed to express exactly X3DSoundSourceObject. } |
| 25 |
TAbstractSoundSourceNode = class(TAbstractTimeDependentNode) |
| 26 |
{$I auto_generated_node_helpers/x3dnodes_x3dsoundsourcenode.inc} |
| 27 |
end; |
| 28 |
|
| 29 |
{ Buffer for sound data, which can be played by the @link(TSoundNode). } |
| 30 |
TAudioClipNode = class(TAbstractSoundSourceNode) |
| 31 |
strict private |
| 32 |
FBufferLoaded: Boolean; |
| 33 |
InsideLoadBuffer: Cardinal; |
| 34 |
PlayingSound: TCastlePlayingSoundSource; |
| 35 |
WarningDoneParentFieldsCount: Boolean; |
| 36 |
procedure SetBufferLoaded(const Value: boolean); |
| 37 |
procedure UpdatePlayingEvent(const Event: TX3DEvent; const Value: TX3DField; |
| 38 |
const Time: TX3DTime); |
| 39 |
procedure SoundOpenClose(Sender: TObject); |
| 40 |
|
| 41 |
{ Did we attempt loading Buffer. You still have to check Buffer <> 0 to know |
| 42 |
if it's successfully loaded. } |
| 43 |
property BufferLoaded: boolean read FBufferLoaded write SetBufferLoaded; |
| 44 |
{ Final length (in seconds) of this sound, adjusted by pitch. |
| 45 |
See @link(TTimeDependentFunctionality.CycleInterval), |
| 46 |
this must return the relevant value. } |
| 47 |
function GetCycleInterval: TFloatTime; |
| 48 |
{ Pitch, corrected to always be > 0. } |
| 49 |
function SafePitch: Single; |
| 50 |
private |
| 51 |
procedure UpdatePlaying; |
| 52 |
protected |
| 53 |
procedure ParseAfter(Reader: TX3DReaderNames); override; |
| 54 |
procedure BeforeTraverse(StateStack: TX3DGraphTraverseStateStack); override; |
| 55 |
public |
| 56 |
constructor Create(const AX3DName: string = ''; const ABaseUrl: String = ''); override; |
| 57 |
destructor Destroy; override; |
| 58 |
|
| 59 |
{$I auto_generated_node_helpers/x3dnodes_audioclip.inc} |
| 60 |
end; |
| 61 |
|
| 62 |
{ 3D sound emitter. } |
| 63 |
TSoundNode = class(TAbstractSoundNode) |
| 64 |
private |
| 65 |
FTransform: TMatrix4; |
| 66 |
FTransformScale: Single; |
| 67 |
SoundSource: TCastleSoundSource; |
| 68 |
SoundSourceTransform: TCastleTransform; |
| 69 |
procedure UpdateSoundSource; |
| 70 |
procedure EventLocationReceive( |
| 71 |
const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime); |
| 72 |
procedure EventEnabledReceive( |
| 73 |
const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime); |
| 74 |
{ Location expressed in Scene coordinate-space, that is: transformed |
| 75 |
by X3D transformations in this X3D scene graph. |
| 76 |
|
| 77 |
TODO: This may need to be renamed to WorldLocation and transformed by scene transformation. |
| 78 |
Test how it behaves in TCastleScene that has some transformation. } |
| 79 |
function SceneLocation: TVector3; |
| 80 |
protected |
| 81 |
procedure BeforeTraverse(StateStack: TX3DGraphTraverseStateStack); override; |
| 82 |
function DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; override; |
| 83 |
public |
| 84 |
constructor Create(const AX3DName: string = ''; const ABaseUrl: String = ''); override; |
| 85 |
destructor Destroy; override; |
| 86 |
|
| 87 |
{$I auto_generated_node_helpers/x3dnodes_sound.inc} |
| 88 |
end; |
| 89 |
|
| 90 |
{$endif read_interface} |
| 91 |
|
| 92 |
{$ifdef read_implementation} |
| 93 |
|
| 94 |
{ TAudioClipNode ------------------------------------------------------------- } |
| 95 |
|
| 96 |
constructor TAudioClipNode.Create(const AX3DName: string; const ABaseUrl: String); |
| 97 |
begin |
| 98 |
inherited; |
| 99 |
|
| 100 |
FTimeFunctionality.OnCycleInterval := {$ifdef FPC}@{$endif} GetCycleInterval; |
| 101 |
|
| 102 |
PlayingSound := TCastlePlayingSoundSource.Create(nil); |
| 103 |
PlayingSound.Sound := TCastleSound.Create(PlayingSound); |
| 104 |
|
| 105 |
EventIsActive.AddNotification({$ifdef FPC}@{$endif} UpdatePlayingEvent); |
| 106 |
EventIsPaused.AddNotification({$ifdef FPC}@{$endif} UpdatePlayingEvent); |
| 107 |
FdEnabled.AddNotification({$ifdef FPC}@{$endif} UpdatePlayingEvent); |
| 108 |
FdGain.AddNotification({$ifdef FPC}@{$endif} UpdatePlayingEvent); |
| 109 |
|
| 110 |
SoundEngine.OnOpenClose.Add({$ifdef FPC}@{$endif} SoundOpenClose); |
| 111 |
|
| 112 |
AddFunctionality(TUrlFunctionality.Create(Self)); |
| 113 |
end; |
| 114 |
|
| 115 |
destructor TAudioClipNode.Destroy; |
| 116 |
begin |
| 117 |
FreeAndNil(PlayingSound); |
| 118 |
SoundEngine.OnOpenClose.Remove({$ifdef FPC}@{$endif} SoundOpenClose); |
| 119 |
inherited; |
| 120 |
end; |
| 121 |
|
| 122 |
procedure TAudioClipNode.ParseAfter(Reader: TX3DReaderNames); |
| 123 |
begin |
| 124 |
inherited; |
| 125 |
|
| 126 |
{ We want to load buffer early, not on-demand (inside UpdatePlaying): |
| 127 |
- This avoids sudden delay when 1st playing sound, |
| 128 |
- It's necessary to make PlayingSound.Sound.Duration good, |
| 129 |
making CycleInterval good, |
| 130 |
which is necessary for time-dependent mechanism (in |
| 131 |
TTimeDependentFunctionality) to always work Ok (see e.g. at thunder.x3dv, |
| 132 |
when AudioClip.startTime is set by script to future time. |
| 133 |
|
| 134 |
But don't do it if URL field is empty. |
| 135 |
This is important in case "url" field value |
| 136 |
has an IS clause, and it will be really known only after expanding |
| 137 |
the PROTO, see thunder.x3dv. } |
| 138 |
if FdUrl.Count <> 0 then |
| 139 |
BufferLoaded := true; |
| 140 |
end; |
| 141 |
|
| 142 |
procedure TAudioClipNode.BeforeTraverse(StateStack: TX3DGraphTraverseStateStack); |
| 143 |
begin |
| 144 |
inherited; |
| 145 |
{ Reasons for doing this: see ParseAfter } |
| 146 |
if FdUrl.Count <> 0 then |
| 147 |
BufferLoaded := true; |
| 148 |
end; |
| 149 |
|
| 150 |
function TAudioClipNode.SafePitch: Single; |
| 151 |
begin |
| 152 |
Result := Pitch; |
| 153 |
if Result <= 0 then |
| 154 |
Result := 1; { assign default pitch in case of trouble } |
| 155 |
end; |
| 156 |
|
| 157 |
function TAudioClipNode.GetCycleInterval: TFloatTime; |
| 158 |
begin |
| 159 |
{ Secure from invalid PlayingSound.Sound.Duration |
| 160 |
(when sound file is not loaded, or duration is just unknown). } |
| 161 |
if PlayingSound.Sound.Duration > 0 then |
| 162 |
Result := PlayingSound.Sound.Duration / SafePitch |
| 163 |
else |
| 164 |
Result := 0; |
| 165 |
end; |
| 166 |
|
| 167 |
procedure TAudioClipNode.UpdatePlayingEvent(const Event: TX3DEvent; const Value: TX3DField; |
| 168 |
const Time: TX3DTime); |
| 169 |
begin |
| 170 |
UpdatePlaying; |
| 171 |
end; |
| 172 |
|
| 173 |
procedure TAudioClipNode.UpdatePlaying; |
| 174 |
|
| 175 |
procedure UpdatePlayingSoundProperties(const SoundNode: TSoundNode); |
| 176 |
begin |
| 177 |
PlayingSound.Loop := Loop; |
| 178 |
PlayingSound.Sound.Priority := SoundNode.Priority; |
| 179 |
PlayingSound.Sound.Volume := SoundNode.Intensity * Gain; |
| 180 |
PlayingSound.Sound.Pitch := SafePitch; |
| 181 |
{ We pass min/maxFront as ReferenceDistance/MaxDistance |
| 182 |
as their meaning matches for SoundEngine.DistanceModel = dmLinear. } |
| 183 |
PlayingSound.Sound.ReferenceDistance := SoundNode.FTransformScale * SoundNode.MinFront; |
| 184 |
PlayingSound.Sound.MaxDistance := SoundNode.FTransformScale * SoundNode.MaxFront; |
| 185 |
end; |
| 186 |
|
| 187 |
function GetSoundNode: TSoundNode; |
| 188 |
begin |
| 189 |
if ParentFieldsCount <> 0 then |
| 190 |
begin |
| 191 |
if ParentFieldsCount > 1 then |
| 192 |
begin |
| 193 |
WarningOnce(WarningDoneParentFieldsCount, |
| 194 |
'Multiple parents of AudioClip node, only the first one will be used'); |
| 195 |
end; |
| 196 |
|
| 197 |
if ParentFields[0].ParentNode is TSoundNode then |
| 198 |
Result := TSoundNode(ParentFields[0].ParentNode) |
| 199 |
else |
| 200 |
Result := nil; |
| 201 |
end else |
| 202 |
Result := nil; |
| 203 |
end; |
| 204 |
|
| 205 |
var |
| 206 |
SoundNode: TSoundNode; |
| 207 |
begin |
| 208 |
SoundNode := GetSoundNode; |
| 209 |
if FTimeFunctionality.IsActive and |
| 210 |
(not FTimeFunctionality.IsPaused) and |
| 211 |
Enabled and |
| 212 |
(SoundNode <> nil) and |
| 213 |
SoundNode.Enabled then |
| 214 |
begin |
| 215 |
if not PlayingSound.Playing then |
| 216 |
begin |
| 217 |
{ if not playing, try to start playing } |
| 218 |
BufferLoaded := true; |
| 219 |
UpdatePlayingSoundProperties(SoundNode); |
| 220 |
// TODO: we could set here Parameters.Offset to not always start playing from start |
| 221 |
SoundNode.SoundSource.Play(PlayingSound); |
| 222 |
end else |
| 223 |
begin |
| 224 |
UpdatePlayingSoundProperties(SoundNode); |
| 225 |
end; |
| 226 |
end else |
| 227 |
begin |
| 228 |
{ if playing, try to stop playing } |
| 229 |
PlayingSound.Stop; |
| 230 |
end; |
| 231 |
end; |
| 232 |
|
| 233 |
procedure TAudioClipNode.SetBufferLoaded(const Value: boolean); |
| 234 |
var |
| 235 |
I: Integer; |
| 236 |
FullUrl: String; |
| 237 |
begin |
| 238 |
if FBufferLoaded <> Value then |
| 239 |
begin |
| 240 |
FBufferLoaded := Value; |
| 241 |
|
| 242 |
if Value then |
| 243 |
begin |
| 244 |
for I := 0 to FdUrl.Items.Count - 1 do |
| 245 |
begin |
| 246 |
FullUrl := PathFromBaseUrl(FdUrl.Items[I]); |
| 247 |
try |
| 248 |
{ LoadBuffer inside may cause OpenAL open, and we don't want to |
| 249 |
do SoundOpenClose then. |
| 250 |
|
| 251 |
Doing OnOpenClose.Remove/Add now would be bad, as this code |
| 252 |
may be called when inside iterating over OnOpenClose: |
| 253 |
(- SetEnable calls ALContextOpen |
| 254 |
- that calls OnOpenClose.ExecuteAll |
| 255 |
- that calls Self.SoundOpenClose |
| 256 |
- that calls UpdatePlaying |
| 257 |
- that loads the buffer |
| 258 |
). Shuffling now OnOpenClose items (Add always adds at the end) |
| 259 |
would mean that the same callback is again processed, |
| 260 |
so Self.SoundOpenClose is called with IsContextOpenSuccess = true and Buffer <> 0, |
| 261 |
so ALContextOpen releases a buffer for a playing sound source |
| 262 |
so OpenAL raises error. |
| 263 |
|
| 264 |
Testcase: |
| 265 |
- start castle-model-viewer with sound = on |
| 266 |
- click CW on all 4 speakers in sound_final.x3dv |
| 267 |
- turn sound off |
| 268 |
- turn sound back on |
| 269 |
- click on lower-bottom speakers } |
| 270 |
Inc(InsideLoadBuffer); |
| 271 |
try |
| 272 |
PlayingSound.Sound.URL := FullUrl; |
| 273 |
finally Dec(InsideLoadBuffer) end; |
| 274 |
|
| 275 |
EventDuration_Changed.Send(PlayingSound.Sound.Duration); |
| 276 |
Break; |
| 277 |
except |
| 278 |
on E: Exception do |
| 279 |
{ Remember that WritelnWarning *may* raise an exception. } |
| 280 |
WritelnWarning('Audio', Format(SLoadError, |
| 281 |
[E.ClassName, 'sound file', UriDisplay(FullUrl), E.Message])); |
| 282 |
end; |
| 283 |
end; |
| 284 |
end else |
| 285 |
begin |
| 286 |
Assert(not PlayingSound.Playing, 'You can unload a buffer only when Sound is not playing'); |
| 287 |
PlayingSound.Sound.URL := ''; |
| 288 |
end; |
| 289 |
end; |
| 290 |
end; |
| 291 |
|
| 292 |
procedure TAudioClipNode.SoundOpenClose(Sender: TObject); |
| 293 |
begin |
| 294 |
if InsideLoadBuffer <> 0 then Exit; |
| 295 |
|
| 296 |
if (Sender as TSoundEngine).IsContextOpenSuccess then |
| 297 |
begin |
| 298 |
{ Maybe we should start playing? } |
| 299 |
BufferLoaded := false; //< force reloading buffer next time |
| 300 |
UpdatePlaying; |
| 301 |
end; |
| 302 |
end; |
| 303 |
|
| 304 |
{ TSoundNode ----------------------------------------------------------------- } |
| 305 |
|
| 306 |
constructor TSoundNode.Create(const AX3DName: string; const ABaseUrl: String); |
| 307 |
begin |
| 308 |
inherited; |
| 309 |
FdLocation.AddNotification({$ifdef FPC}@{$endif} EventLocationReceive); |
| 310 |
FdEnabled.AddNotification({$ifdef FPC}@{$endif} EventEnabledReceive); |
| 311 |
|
| 312 |
FTransform := TMatrix4.Identity; |
| 313 |
FTransformScale := 1; |
| 314 |
|
| 315 |
SoundSource := TCastleSoundSource.Create(nil); |
| 316 |
SoundSource.SetTransient; |
| 317 |
|
| 318 |
SoundSourceTransform := TCastleTransform.Create(nil); |
| 319 |
SoundSourceTransform.SetTransient; |
| 320 |
SoundSourceTransform.AddBehavior(SoundSource); |
| 321 |
end; |
| 322 |
|
| 323 |
destructor TSoundNode.Destroy; |
| 324 |
begin |
| 325 |
FreeAndNil(SoundSource); |
| 326 |
FreeAndNil(SoundSourceTransform); |
| 327 |
inherited; |
| 328 |
end; |
| 329 |
|
| 330 |
function TSoundNode.SceneLocation: TVector3; |
| 331 |
begin |
| 332 |
Result := FTransform.MultPoint(Location); |
| 333 |
end; |
| 334 |
|
| 335 |
function TSoundNode.DirectEnumerateActive(Func: TEnumerateChildrenFunction): Pointer; |
| 336 |
begin |
| 337 |
Result := inherited; |
| 338 |
if Result <> nil then Exit; |
| 339 |
|
| 340 |
{ Necessary in order to call TAudioClipNode.BeforeTraverse, |
| 341 |
testcase: thunder.x3dv. } |
| 342 |
Result := FdSource.Enumerate(Func); |
| 343 |
if Result <> nil then Exit; |
| 344 |
end; |
| 345 |
|
| 346 |
procedure TSoundNode.UpdateSoundSource; |
| 347 |
// var |
| 348 |
// AudioClip: TAudioClipNode; |
| 349 |
begin |
| 350 |
{ TODO: this should be called also when |
| 351 |
- Scene changes, |
| 352 |
- Scene.Parent changes |
| 353 |
- Spatialize value changes |
| 354 |
} |
| 355 |
|
| 356 |
if Scene <> SoundSourceTransform.Parent then |
| 357 |
begin |
| 358 |
if SoundSourceTransform.Parent <> nil then |
| 359 |
SoundSourceTransform.Parent.Remove(SoundSourceTransform); |
| 360 |
if Scene <> nil then |
| 361 |
Scene.Add(SoundSourceTransform); |
| 362 |
end; |
| 363 |
|
| 364 |
SoundSourceTransform.Translation := SceneLocation; |
| 365 |
SoundSource.Spatial := Spatialize; |
| 366 |
|
| 367 |
// if FdSource.Value is TAudioClipNode then // also checks FdSource.Value <> nil |
| 368 |
// begin |
| 369 |
// AudioClip := TAudioClipNode(FdSource.Value); |
| 370 |
// //AudioClip.PlayingSound ... |
| 371 |
// end; |
| 372 |
end; |
| 373 |
|
| 374 |
procedure TSoundNode.BeforeTraverse(StateStack: TX3DGraphTraverseStateStack); |
| 375 |
begin |
| 376 |
inherited; |
| 377 |
FTransform := StateStack.Top.Transformation.Transform; |
| 378 |
FTransformScale := StateStack.Top.Transformation.Scale; |
| 379 |
UpdateSoundSource; |
| 380 |
end; |
| 381 |
|
| 382 |
procedure TSoundNode.EventLocationReceive( |
| 383 |
const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime); |
| 384 |
begin |
| 385 |
UpdateSoundSource; |
| 386 |
end; |
| 387 |
|
| 388 |
procedure TSoundNode.EventEnabledReceive( |
| 389 |
const Event: TX3DEvent; const Value: TX3DField; const Time: TX3DTime); |
| 390 |
begin |
| 391 |
if Source is TAudioClipNode then // also checks Source <> nil |
| 392 |
TAudioClipNode(Source).UpdatePlaying; |
| 393 |
end; |
| 394 |
|
| 395 |
procedure RegisterSoundNodes; |
| 396 |
begin |
| 397 |
NodesManager.RegisterNodeClasses([ |
| 398 |
TAudioClipNode, |
| 399 |
TSoundNode |
| 400 |
]); |
| 401 |
end; |
| 402 |
|
| 403 |
{$endif read_implementation} |