VR-Forces Developer's Guide
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
List of all members | Public Member Functions | Protected Member Functions | Protected Attributes | Static Protected Attributes | Private Member Functions | Private Attributes
makVrv::DtProceduralSound Class Reference

Composes multiple DtProceduralSoundLayer pools into one streaming ambient sound.

A DtProceduralSound owns any number of named DtProceduralSoundLayer objects and drives a single streaming OpenAL voice via a software PCM mixer. Every frame, tick() produces 100 ms PCM chunks (configurable) by mixing all enabled layers into a shared float scratch buffer, clamping to [-1.0f, 1.0f], and pushing the resulting DtAudioBuffer into the underlying DtStreamSource.

Using a single OpenAL voice - regardless of how many concurrent events the layers produce - avoids exhausting the OpenAL voice budget and removes any per-event overhead from the audio manager.

Typical usage (implemented inside a DtProceduralSoundCreator subclass):

auto* sc = new DtProceduralSound(de, id);
auto& birds = sc->addLayer("birds");
birds.addClip(de.dePathConfiguration().resolvePath("$(SHARED_DATA_DIR)/Audio/bird1.wav"), 2.0f);
birds.addClip(de.dePathConfiguration().resolvePath("$(SHARED_DATA_DIR)/Audio/bird2.wav"), 1.5f);
birds.setDensity(1.5f);
birds.setGainRange(0.05f, 1.0f);
birds.setPitchRange(0.93f, 1.07f);
See Also
DtProceduralSoundLayer, DtProceduralSoundCreator

Public Member Functions

 DtProceduralSound (DtDe &de, DtUniqueID id)
 
virtual ~DtProceduralSound ()
 
 DtProceduralSound (const DtProceduralSound &)=delete
 
DtProceduralSound & operator= (const DtProceduralSound &)=delete
 
virtual DtProceduralSoundLayer & addLayer (const std::string &name)
 
virtual DtProceduralSoundLayer * getLayer (const std::string &name)
 
virtual const std::map
< std::string,
DtProceduralSoundLayer > & 
layers () const
 
virtual void setBehaviorOnAllLayers (DtProceduralSoundBehavior *behavior)
 
virtual void setProximityFactorOnAllLayers (float factor)
 
virtual int queuedChunks () const
 
virtual bool play ()
 
virtual void pause ()
 
virtual void stop ()
 
virtual bool isPlaying () const
 
virtual void setDecibel (float relativeDb)
 
virtual void setMinAudibleDistance (float minDistM)
 
virtual void setMaxAudibleDistance (float maxDistM)
 
virtual void setIs3d (bool is3d)
 
virtual bool is3d () const
 
virtual void setPosition (const DtVector &position)
 
virtual void setVelocity (const DtVector &velocity)
 
virtual void tick (double dt, float densityScale)
 
virtual void setSampleRate (unsigned int rate)
 
virtual unsigned int sampleRate () const
 
virtual void setChunkDuration (float seconds)
 
virtual float chunkDuration () const
 
virtual void setSoftStartDuration (float seconds)
 
virtual float softStartDuration () const
 

Protected Member Functions

virtual void initializeSound ()
 
virtual void produceChunk (int numSamples, float densityScale)
 
virtual makAudio::DtStreamSource * resolveStream () const
 

Protected Attributes

DtDe & myDe
 
DtUniqueID myId
 
std::map< std::string,
DtProceduralSoundLayer > 
myLayers
 
std::unique_ptr
< makAudio::DtSound > 
mySound
 
unsigned int myOutputSampleRate = 44100
 
float myChunkDuration = 0.1f
 
bool myIsPlaying = false
 
float myPendingDecibel = 0.0f
 
float myMinAudibleDistanceM = DtAudioLevel::kUseDefaultDistance
 
float myMaxAudibleDistanceM = DtAudioLevel::kUseDefaultDistance
 
bool myIs3d = false
 
DtVector myPosition
 
DtVector myVelocity
 
std::vector< float > myScratch
 

Static Protected Attributes

static constexpr int kMaxQueuedChunks = 4
 

Private Member Functions

void armSoftStart ()
 

Private Attributes

float mySoftStartDurationSec = 1.0f
 
int mySoftStartSamplesRemaining = 0
 
int mySoftStartTotalSamples = 0
 
float mySoftStartCurrentGain = 1.0f
 
float mySoftStartGainStep = 1.0f
 

Constructor & Destructor Documentation

makVrv::DtProceduralSound::DtProceduralSound ( DtDe &  de,
DtUniqueID  id 
)

Construct a procedural sound attached to the given DE. The id is used to avoid DtSoundComponent ID collisions; use a locally-generated atomic counter (see DtProceduralSoundscapeManager pattern).

virtual makVrv::DtProceduralSound::~DtProceduralSound ( )
virtual

Destructor. Stops the stream and releases all layer resources.

makVrv::DtProceduralSound::DtProceduralSound ( const DtProceduralSound &  )
delete

Member Function Documentation

DtProceduralSound& makVrv::DtProceduralSound::operator= ( const DtProceduralSound &  )
delete
virtual DtProceduralSoundLayer& makVrv::DtProceduralSound::addLayer ( const std::string &  name)
virtual

Add a named layer. Returns a reference valid for the lifetime of this sound (or until the sound is destroyed).

virtual DtProceduralSoundLayer* makVrv::DtProceduralSound::getLayer ( const std::string &  name)
virtual

Look up a layer by name. Returns nullptr if not found.

virtual const std::map<std::string, DtProceduralSoundLayer>& makVrv::DtProceduralSound::layers ( ) const
virtual

Read-only access to all layers, keyed by name.

virtual void makVrv::DtProceduralSound::setBehaviorOnAllLayers ( DtProceduralSoundBehavior *  behavior)
virtual

Set the same behavior on all layers (non-owning pointer).

virtual void makVrv::DtProceduralSound::setProximityFactorOnAllLayers ( float  factor)
virtual

Push proximity factor into all layers for audio-thread context.

virtual int makVrv::DtProceduralSound::queuedChunks ( ) const
virtual

Number of PCM chunks currently queued on the DtStreamSource. Valid range 0-4 (kMaxQueuedChunks). Useful for diagnosing stream backpressure: 0 = underrun risk; 4 = audio manager is behind.

virtual bool makVrv::DtProceduralSound::play ( )
virtual

Start streaming. Creates the underlying DtSound on first call once the audio playback device is ready.

Returns
true if the sound is now playing, false if the device is not yet available (caller should retry next frame).
virtual void makVrv::DtProceduralSound::pause ( )
virtual

Pause the stream.

virtual void makVrv::DtProceduralSound::stop ( )
virtual

Stop the stream and discard any queued chunks.

Warning
Always call stop() before discarding this object or before the next play(). The mandatory cleanup sequence after stop() is:
  1. stream->reset() - flushes the DtStreamSource software queue.
  2. For each layer: layer.resetPlayback() - clears in-flight events. Failure to do this causes stall-on-next-play (pre-fill backpressure fires immediately because bufferCount() still reports 4 after stop()).
Note
Idempotent: calling stop() when the sound is already stopped is a no-op. DtProceduralSoundscapeManager relies on this to safely call player->stop() every frame while a channel is out of range.
virtual bool makVrv::DtProceduralSound::isPlaying ( ) const
virtual
Returns
true if play() has succeeded and the stream is active.
virtual void makVrv::DtProceduralSound::setDecibel ( float  relativeDb)
virtual

Apply a dB volume level to the underlying sound.

For non-3D sources: converts relativeDb to a linear gain (0 dB = unit gain, negative values attenuate). Call this before tick() each frame.

For 3D sources: updates the max-audible-distance via the same DtSound::setDecibels() path used by regular file-based sounds. Source gain stays at 1.0 so falloff matches file-based 3D sounds at the same dB.

Parameters
relativeDbVolume level in decibels (0 dB = unity gain for non-3D; controls falloff range for 3D).
virtual void makVrv::DtProceduralSound::setMinAudibleDistance ( float  minDistM)
virtual

Set the inner-radius (reference-distance) override for 3D attenuation, in metres.

Applied to the underlying voice via DtAudioLevel::applyAttenuation on the next play() (and immediately if the sound is already playing). Pass DtAudioLevel::kUseDefaultDistance (the default) to leave the physical-model reference distance in place.

Parameters
minDistMReference distance in metres, or kUseDefaultDistance.
virtual void makVrv::DtProceduralSound::setMaxAudibleDistance ( float  maxDistM)
virtual

Set the outer-radius (max-falloff-distance) override for 3D attenuation, in metres.

Applied to the underlying voice via DtAudioLevel::applyAttenuation on the next play() (and immediately if the sound is already playing). Pass DtAudioLevel::kUseDefaultDistance (the default) to leave the physical-model max-falloff distance in place.

Parameters
maxDistMMax-falloff distance in metres, or kUseDefaultDistance.
virtual void makVrv::DtProceduralSound::setIs3d ( bool  is3d)
virtual

Enable or disable 3D spatial attenuation for this sound.

When true, OpenAL applies distance-based gain falloff automatically using the source position set via setPosition(). The gain set by setDecibel() updates the max-audible distance (3D) or source gain (non-3D); OpenAL then applies the distance model for 3D sources. Defaults to false (ambient / non-positional).

virtual bool makVrv::DtProceduralSound::is3d ( ) const
virtual
Returns
true if 3D positional attenuation is enabled.
virtual void makVrv::DtProceduralSound::setPosition ( const DtVector &  position)
virtual

Set the world-space position of the sound source.

Only meaningful when is3d() is true. Forwarded to the underlying DtSound immediately if the sound has been created; otherwise applied on the next play().

virtual void makVrv::DtProceduralSound::setVelocity ( const DtVector &  velocity)
virtual

Set the world-space velocity of the sound source (for Doppler).

Only meaningful when is3d() is true.

virtual void makVrv::DtProceduralSound::tick ( double  dt,
float  densityScale 
)
virtual

Produce and push PCM chunks for the current frame.

Parameters
dtElapsed simulation time in seconds. Accepted for API parity with other per-frame tick interfaces but intentionally ignored: each call produces exactly one chunk of fixed duration (myChunkDuration), so per-frame dt is not meaningful for PCM scheduling. Subclasses that override tick() may consult dt for their own purposes.
densityScaleRuntime density multiplier forwarded to each layer.
virtual void makVrv::DtProceduralSound::setSampleRate ( unsigned int  rate)
virtual

Output sample rate in Hz. Must match the clips in all layers. Default: 44100.

virtual unsigned int makVrv::DtProceduralSound::sampleRate ( ) const
virtual
virtual void makVrv::DtProceduralSound::setChunkDuration ( float  seconds)
virtual

Duration of each PCM chunk pushed to the stream, in seconds. Shorter = lower latency, higher CPU. Default: 0.1 s (100 ms).

virtual float makVrv::DtProceduralSound::chunkDuration ( ) const
virtual
virtual void makVrv::DtProceduralSound::setSoftStartDuration ( float  seconds)
virtual

Duration of the dB-linear fade-in applied when the streaming OpenAL voice transitions from stopped to playing, in seconds.

Suppresses the "rush of sound" that would otherwise be heard at cold start, when the kMaxQueuedChunks pre-fill (~400 ms of densely-mixed audio) hits the source at full volume the instant play() succeeds. The ramp rises logarithmically in amplitude from a -60 dB floor to 0 dB over the configured duration – equal dB increments per sample. This is the perceptual standard for fade-ins because human hearing is logarithmic; a linear-amplitude ramp climbs from -inf dB to -8 dB in roughly the first 10 percent of the ramp, which is audibly abrupt. The envelope is re-armed automatically on every successful play() call and on stall recovery inside tick(). It applies uniformly to all layers; after the ramp completes the envelope is bypassed entirely until the next arm.

Input is clamped to [0.0f, 5.0f]; 0.0f disables the envelope (samples pass through at unity from sample 0). Changing this value while a ramp is in progress does not interrupt the ramp; the new value takes effect on the next play() or stall-recovery event. Default: 1.0 s.

virtual float makVrv::DtProceduralSound::softStartDuration ( ) const
virtual
virtual void makVrv::DtProceduralSound::initializeSound ( )
protectedvirtual

Create and configure the underlying makAudio::DtSound for streaming.

Note
Called lazily by play() once the audio playback device is available. Safe to call multiple times - no-op if the sound is already initialized.
virtual void makVrv::DtProceduralSound::produceChunk ( int  numSamples,
float  densityScale 
)
protectedvirtual

Mix all layers into one 100 ms PCM chunk and push it to the DtStreamSource.

Note
Pre-fill requirement: call this kMaxQueuedChunks (= 4) times before the first play() to ensure the OpenAL buffer queue is populated before the source starts.
Backpressure guard: if the software queue already holds kMaxQueuedChunks chunks, this function returns immediately without producing a new chunk. This is intentional - do not remove the guard.
virtual makAudio::DtStreamSource* makVrv::DtProceduralSound::resolveStream ( ) const
protectedvirtual

Resolve the DtStreamSource from the underlying DtSound.

Returns nullptr when the sound has not been initialized, when the underlying DtSource has not yet been assigned (play() not yet called), or when the source is not a stream. Used internally by queuedChunks(), stop(), and produceChunk().

void makVrv::DtProceduralSound::armSoftStart ( )
private

Recompute mySoftStartTotalSamples from the current duration and sample rate, and reset mySoftStartSamplesRemaining to that count. Called from play() and from the stall-recovery path inside tick().

Member Data Documentation

DtDe& makVrv::DtProceduralSound::myDe
protected
DtUniqueID makVrv::DtProceduralSound::myId
protected
std::map<std::string, DtProceduralSoundLayer> makVrv::DtProceduralSound::myLayers
protected
std::unique_ptr<makAudio::DtSound> makVrv::DtProceduralSound::mySound
protected

Underlying streaming sound. Null until play() succeeds.

unsigned int makVrv::DtProceduralSound::myOutputSampleRate = 44100
protected
float makVrv::DtProceduralSound::myChunkDuration = 0.1f
protected
bool makVrv::DtProceduralSound::myIsPlaying = false
protected
float makVrv::DtProceduralSound::myPendingDecibel = 0.0f
protected

Volume stored before the sound is initialized, applied on first play().

float makVrv::DtProceduralSound::myMinAudibleDistanceM = DtAudioLevel::kUseDefaultDistance
protected

Inner-radius (reference-distance) override for 3D attenuation, in metres. kUseDefaultDistance leaves the physical-model default in place; any positive value pins the reference distance on the voice via DtAudioLevel::applyAttenuation.

float makVrv::DtProceduralSound::myMaxAudibleDistanceM = DtAudioLevel::kUseDefaultDistance
protected

Outer-radius (max-falloff-distance) override for 3D attenuation, in metres. kUseDefaultDistance leaves the physical-model default in place; any positive value pins the max-falloff distance on the voice via DtAudioLevel::applyAttenuation.

bool makVrv::DtProceduralSound::myIs3d = false
protected

Whether to use 3D positional attenuation (default: false).

DtVector makVrv::DtProceduralSound::myPosition
protected

World-space source position, applied when myIs3d is true.

DtVector makVrv::DtProceduralSound::myVelocity
protected

World-space source velocity for Doppler, applied when myIs3d is true.

std::vector<float> makVrv::DtProceduralSound::myScratch
protected

Reused scratch buffer (float32) - avoids per-chunk heap allocation.

constexpr int makVrv::DtProceduralSound::kMaxQueuedChunks = 4
staticprotected
float makVrv::DtProceduralSound::mySoftStartDurationSec = 1.0f
private

Configured soft-start fade-in duration, in seconds. Default: 1.0 s.

int makVrv::DtProceduralSound::mySoftStartSamplesRemaining = 0
private

Samples still to attenuate in the current ramp; 0 means the envelope is bypassed.

int makVrv::DtProceduralSound::mySoftStartTotalSamples = 0
private

round(mySoftStartDurationSec * myOutputSampleRate); total length of the ramp.

float makVrv::DtProceduralSound::mySoftStartCurrentGain = 1.0f
private

Current ramp gain (linear amplitude); updated multiplicatively each sample during the soft-start ramp. Held at the -60 dB floor (~0.001f) until the envelope is armed, then drifts toward 1.0f.

float makVrv::DtProceduralSound::mySoftStartGainStep = 1.0f
private

Per-sample multiplicative step: 10^(3 / mySoftStartTotalSamples). Applied to mySoftStartCurrentGain each sample to produce a dB-linear ramp from -60 dB to 0 dB over mySoftStartTotalSamples samples.


The documentation for this class was generated from the following file:

Document ID: Generated on Thu Oct 15 21:27:02 EDT 2026 from SVN revision 296421
Copyright © 2005-2026 MAK Technologies. All Rights Reserved (www.mak.com)