Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,8 @@ add_library(DriftEngine STATIC
Source/Engine/Clock.h
Source/Engine/EngineCommandQueue.cpp
Source/Engine/EngineCommandQueue.h
Source/Engine/ProximityRhythmMapping.cpp
Source/Engine/ProximityRhythmMapping.h
Source/Engine/SpatialWorld.cpp
Source/Engine/SpatialWorld.h
Source/Engine/SpeedActivityMapping.cpp
Expand Down
4 changes: 3 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ New contacts are resolved in the table's stable pair order. If simultaneous cont

Phrase speed also selects authored material. Native velocity magnitude is normalized against the maximum throw speed and smoothed with a deterministic 250 ms filter. Each phrase begins normal (`A`), slows into sparse (`C`), or accelerates into active (`B`). Hysteresis keeps the bands stable: normal enters sparse at `0.015` and sparse returns at `0.040`; normal enters active at `0.450` and active returns at `0.300`. Band changes take effect at the next eligible bar. Speed observation pauses during Freeze Motion and direct dragging, while audio playback continues. A collision targeting the same phrase and bar replaces a pending speed change.

Proximity currently has two deliberately temporary audition modes. Both derive a loose, linked, or tight coupling level from the smoothed surface gap between every phrase pair, with stable changes taking effect at the next eligible unscheduled bar. **Rhythm profiles** snap nearby phrases toward half-beat or beat grids without changing their notes, durations, or dynamics. **Shared accents** leave timing and density untouched and emphasize notes that already begin together. The selector changes modes on the next bar so the alternatives can be compared during uninterrupted playback; neither is yet designated as the production mapping.

## Architecture

Drift is designed as a native **JUCE** desktop application with an embedded **React** interface. **PixiJS** is the initial renderer for the spatial world.
Expand Down Expand Up @@ -100,7 +102,7 @@ Drift is in the design and initial implementation phase. The first development b
5. [Prove transport stability under simulated UI stress](https://github.com/datashaman/drift/issues/5)
6. [Validate ten-minute playback through a real MIDI device](https://github.com/datashaman/drift/issues/6)

The native shell now connects React Play, Stop, Freeze Motion, BPM, MIDI-output, and direct phrase-drag controls to a native-owned monotonic transport and a four-role composition: drums, bass, chords, and melody. Stop freezes both playback and movement; Freeze Motion pauses only autonomous movement so phrases can be caught and repositioned while MIDI continues uninterrupted. Untouched phrases retain their velocity for resume, while a phrase manipulated during the freeze is released stationary. Drift schedules every phrase from the same transport to its assigned MIDI channel and advances the phrase bodies in a bounded normalized world at a fixed 120 Hz. Validated pointer intent crosses a bounded, coalescing command queue; PixiJS follows the pointer optimistically and reconciles to latest-state native snapshots at 30 Hz. A bounded recent pointer sample window gives each release a native-owned throw velocity, while stationary releases settle and edge or corner throws reflect inside the field. Every phrase now has three compatible authored variants. Both unique phrase collisions and stable speed-band crossings queue deterministic changes at the next eligible unscheduled bar, with collisions taking priority at a shared boundary. Physics and input pressure remain independent of musical time, and the interface exposes motion state, raw and smoothed phrase speed, stable and pending activity bands, current/pending variants, pair mappings, transition counts, timing, catch-up, queue, coalescing, rejection, and snapshot diagnostics.
The native shell now connects React Play, Stop, Freeze Motion, BPM, MIDI-output, proximity-audition, and direct phrase-drag controls to a native-owned monotonic transport and a four-role composition: drums, bass, chords, and melody. Stop freezes both playback and movement; Freeze Motion pauses only autonomous movement so phrases can be caught and repositioned while MIDI continues uninterrupted. Untouched phrases retain their velocity for resume, while a phrase manipulated during the freeze is released stationary. Drift schedules every phrase from the same transport to its assigned MIDI channel and advances the phrase bodies in a bounded normalized world at a fixed 120 Hz. Validated pointer intent crosses a bounded, coalescing command queue; PixiJS follows the pointer optimistically and reconciles to latest-state native snapshots at 30 Hz. A bounded recent pointer sample window gives each release a native-owned throw velocity, while stationary releases settle and edge or corner throws reflect inside the field. Every phrase now has three compatible authored variants. Unique collisions, stable speed-band crossings, and stable pair-coupling changes queue deterministic changes at the next eligible unscheduled bar. Proximity transforms the resolved collision/speed material rather than selecting another variant. Physics and input pressure remain independent of musical time, and the interface exposes motion state, phrase speeds, activity bands, variants, exact pair proximity and coupling state, audition mode, transition counts, timing, catch-up, queue, coalescing, rejection, and snapshot diagnostics.

The native/UI bridge uses a validated protocol-versioned envelope. Invalid commands produce structured rejection events without mutating engine state, and every React load performs a fresh handshake that restores the current authoritative transport state without restarting playback.

Expand Down
72 changes: 72 additions & 0 deletions Source/App/MainComponent.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,11 @@ void MainComponent::handleCommand (juce::var command)
engineCommand.type = drift::engine::EngineCommandType::worldSetMotionPaused;
engineCommand.motionPaused = validated.motionPaused;
break;
case drift::ui::BridgeCommandType::proximitySetAuditionMode:
engineCommand.type = drift::engine::EngineCommandType::proximitySetAuditionMode;
engineCommand.proximityMode
= *drift::engine::proximityAuditionModeForName (validated.proximityMode);
break;
case drift::ui::BridgeCommandType::transportSetTempo:
engineCommand.type = drift::engine::EngineCommandType::transportSetTempo;
break;
Expand Down Expand Up @@ -239,6 +244,20 @@ void MainComponent::publishState()
state.transport.diagnostics.speedIntentSuppressedCount));
diagnostics->setProperty ("speedTransitionAppliedCount", static_cast<juce::int64> (
state.transport.diagnostics.speedTransitionAppliedCount));
diagnostics->setProperty ("proximityLevelChangeCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityLevelChangeCount));
diagnostics->setProperty ("proximityIntentQueuedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityIntentQueuedCount));
diagnostics->setProperty ("proximityIntentCoalescedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityIntentCoalescedCount));
diagnostics->setProperty ("proximityIntentSuppressedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityIntentSuppressedCount));
diagnostics->setProperty ("proximityTransitionAppliedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityTransitionAppliedCount));
diagnostics->setProperty ("proximityModeQueuedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityModeQueuedCount));
diagnostics->setProperty ("proximityModeAppliedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityModeAppliedCount));
diagnostics->setProperty (
"commandQueueDepth", static_cast<juce::int64> (state.commandQueue.queueDepth));
diagnostics->setProperty (
Expand Down Expand Up @@ -284,6 +303,21 @@ void MainComponent::publishWorldSnapshot (const drift::engine::ControllerSnapsho
payload->setProperty ("sequence", static_cast<juce::int64> (++worldSnapshotSequence));
payload->setProperty ("engineTimeMs", state.transport.engineTimeSeconds * 1000.0);
payload->setProperty ("motionPaused", state.transport.motionPaused);
payload->setProperty (
"proximityMode",
juce::String { drift::engine::proximityAuditionModeName (
state.transport.proximityMode) });
payload->setProperty (
"pendingProximityMode",
state.transport.pendingProximityMode
? juce::var { juce::String { drift::engine::proximityAuditionModeName (
*state.transport.pendingProximityMode) } }
: juce::var {});
payload->setProperty (
"pendingProximityModeApplyBeat",
state.transport.pendingProximityModeApplyBeat
? juce::var { *state.transport.pendingProximityModeApplyBeat }
: juce::var {});

auto* transport = new juce::DynamicObject();
transport->setProperty ("playing", state.transport.playing);
Expand Down Expand Up @@ -359,6 +393,30 @@ void MainComponent::publishWorldSnapshot (const drift::engine::ControllerSnapsho
}
payload->setProperty ("collisions", juce::var { collisions });

juce::Array<juce::var> proximityPairs;
for (const auto& pair : state.transport.proximityPairs)
{
auto* pairObject = new juce::DynamicObject();
pairObject->setProperty ("firstPhraseId", juce::String { pair.firstPhraseId });
pairObject->setProperty ("secondPhraseId", juce::String { pair.secondPhraseId });
pairObject->setProperty ("rawProximity", pair.rawProximity);
pairObject->setProperty ("smoothedProximity", pair.smoothedProximity);
pairObject->setProperty (
"couplingLevel",
juce::String { drift::engine::couplingLevelName (pair.couplingLevel) });
pairObject->setProperty (
"pendingCouplingLevel",
pair.pendingCouplingLevel
? juce::var { juce::String { drift::engine::couplingLevelName (
*pair.pendingCouplingLevel) } }
: juce::var {});
pairObject->setProperty (
"pendingApplyBeat",
pair.pendingApplyBeat ? juce::var { *pair.pendingApplyBeat } : juce::var {});
proximityPairs.add (juce::var { pairObject });
}
payload->setProperty ("proximityPairs", juce::var { proximityPairs });

auto* diagnostics = new juce::DynamicObject();
diagnostics->setProperty (
"physicsStepCount",
Expand Down Expand Up @@ -387,6 +445,20 @@ void MainComponent::publishWorldSnapshot (const drift::engine::ControllerSnapsho
state.transport.diagnostics.speedIntentSuppressedCount));
diagnostics->setProperty ("speedTransitionAppliedCount", static_cast<juce::int64> (
state.transport.diagnostics.speedTransitionAppliedCount));
diagnostics->setProperty ("proximityLevelChangeCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityLevelChangeCount));
diagnostics->setProperty ("proximityIntentQueuedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityIntentQueuedCount));
diagnostics->setProperty ("proximityIntentCoalescedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityIntentCoalescedCount));
diagnostics->setProperty ("proximityIntentSuppressedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityIntentSuppressedCount));
diagnostics->setProperty ("proximityTransitionAppliedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityTransitionAppliedCount));
diagnostics->setProperty ("proximityModeQueuedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityModeQueuedCount));
diagnostics->setProperty ("proximityModeAppliedCount", static_cast<juce::int64> (
state.transport.diagnostics.proximityModeAppliedCount));
diagnostics->setProperty (
"droppedSnapshotCount", static_cast<juce::int64> (droppedWorldSnapshotCount));
diagnostics->setProperty (
Expand Down
3 changes: 3 additions & 0 deletions Source/Engine/EngineCommandQueue.h
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#pragma once

#include "Music/Phrase.h"
#include "Engine/ProximityRhythmMapping.h"

#include <atomic>
#include <cstddef>
Expand All @@ -18,6 +19,7 @@ enum class EngineCommandType
transportPlay,
transportStop,
worldSetMotionPaused,
proximitySetAuditionMode,
transportSetTempo,
midiSelectOutput,
phraseDragStart,
Expand All @@ -35,6 +37,7 @@ struct EngineCommand
std::string outputId;
double bpm = 120.0;
bool motionPaused = false;
ProximityAuditionMode proximityMode = ProximityAuditionMode::rhythmProfiles;
music::NormalizedPosition position;
music::NormalizedVelocity velocity;
};
Expand Down
9 changes: 9 additions & 0 deletions Source/Engine/EngineController.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,12 @@ void EngineController::setMotionPaused (bool paused)
engine.setMotionPaused (paused);
}

void EngineController::setProximityAuditionMode (ProximityAuditionMode mode)
{
const std::scoped_lock lock { mutex };
engine.setProximityAuditionMode (mode);
}

bool EngineController::setBpm (double bpm)
{
const std::scoped_lock lock { mutex };
Expand Down Expand Up @@ -117,6 +123,9 @@ void EngineController::applyCommand (const EngineCommand& command)
case EngineCommandType::worldSetMotionPaused:
engine.setMotionPaused (command.motionPaused);
break;
case EngineCommandType::proximitySetAuditionMode:
engine.setProximityAuditionMode (command.proximityMode);
break;
case EngineCommandType::transportSetTempo:
engine.setBpm (command.bpm);
break;
Expand Down
1 change: 1 addition & 0 deletions Source/Engine/EngineController.h
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ class EngineController final : private juce::HighResolutionTimer
void play();
void stop();
void setMotionPaused (bool paused);
void setProximityAuditionMode (ProximityAuditionMode mode);
bool setBpm (double bpm);
bool selectMidiOutput (const std::string& outputId);
CommandEnqueueResult enqueueCommand (EngineCommand command);
Expand Down
160 changes: 160 additions & 0 deletions Source/Engine/ProximityRhythmMapping.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,160 @@
#include "Engine/ProximityRhythmMapping.h"

#include <algorithm>
#include <cmath>

namespace drift::engine
{
const char* couplingLevelName (CouplingLevel level) noexcept
{
switch (level)
{
case CouplingLevel::loose: return "loose";
case CouplingLevel::linked: return "linked";
case CouplingLevel::tight: return "tight";
}
return "loose";
}

const char* proximityAuditionModeName (ProximityAuditionMode mode) noexcept
{
switch (mode)
{
case ProximityAuditionMode::rhythmProfiles: return "rhythmProfiles";
case ProximityAuditionMode::sharedAccents: return "sharedAccents";
}
return "rhythmProfiles";
}

std::optional<ProximityAuditionMode> proximityAuditionModeForName (
const std::string& name) noexcept
{
if (name == "rhythmProfiles") return ProximityAuditionMode::rhythmProfiles;
if (name == "sharedAccents") return ProximityAuditionMode::sharedAccents;
return std::nullopt;
}

int couplingLevelRank (CouplingLevel level) noexcept
{
return static_cast<int> (level);
}

CouplingLevel couplingLevelAfterObservation (CouplingLevel current,
double proximity) noexcept
{
proximity = std::clamp (proximity, 0.0, 1.0);
switch (current)
{
case CouplingLevel::loose:
return proximity >= ProximityTracker::looseToLinkedThreshold
? CouplingLevel::linked : current;
case CouplingLevel::linked:
if (proximity <= ProximityTracker::linkedToLooseThreshold)
return CouplingLevel::loose;
if (proximity >= ProximityTracker::linkedToTightThreshold)
return CouplingLevel::tight;
return current;
case CouplingLevel::tight:
return proximity <= ProximityTracker::tightToLinkedThreshold
? CouplingLevel::linked : current;
}
return CouplingLevel::loose;
}

double normalizedPairProximity (const PhraseBody& first,
const PhraseBody& second) noexcept
{
const auto centreDistance = std::hypot (
first.position.x - second.position.x,
first.position.y - second.position.y);
const auto surfaceGap = std::max (0.0, centreDistance - first.radius - second.radius);
return 1.0 - std::clamp (
surfaceGap / ProximityTracker::influenceSurfaceGap, 0.0, 1.0);
}

std::optional<CouplingLevel> ProximityTracker::observe (
double normalizedProximity,
std::size_t fixedStepCount)
{
raw = std::clamp (normalizedProximity, 0.0, 1.0);
if (! initialized)
{
smoothed = raw;
initialized = true;
}

if (fixedStepCount == 0)
return std::nullopt;

const auto alpha = 1.0 - std::exp (
-SpatialWorld::fixedStepSeconds / smoothingTimeConstantSeconds);
for (std::size_t step = 0; step < fixedStepCount; ++step)
smoothed += alpha * (raw - smoothed);

const auto next = couplingLevelAfterObservation (level, smoothed);
if (next == level)
return std::nullopt;
level = next;
return level;
}

double ProximityTracker::rawProximity() const noexcept { return raw; }
double ProximityTracker::smoothedProximity() const noexcept { return smoothed; }
CouplingLevel ProximityTracker::observedLevel() const noexcept { return level; }

std::vector<music::NoteEvent> applyRhythmProfile (
const std::vector<music::NoteEvent>& events,
CouplingLevel level,
double phraseLengthBeats)
{
if (level == CouplingLevel::loose)
return events;

const auto grid = level == CouplingLevel::linked ? 0.5 : 1.0;
std::vector<music::NoteEvent> transformed;
transformed.reserve (events.size());
for (auto event : events)
{
event.beat = std::round (event.beat / grid) * grid;
if (event.beat >= phraseLengthBeats)
event.beat -= phraseLengthBeats;

const auto duplicate = std::find_if (
transformed.begin(), transformed.end(), [&event] (const auto& candidate) {
return candidate.note == event.note
&& std::abs (candidate.beat - event.beat) < 1.0e-9;
});
if (duplicate == transformed.end())
transformed.push_back (event);
else
{
duplicate->velocity = std::max (duplicate->velocity, event.velocity);
duplicate->durationBeats = std::max (
duplicate->durationBeats, event.durationBeats);
}
}

std::sort (transformed.begin(), transformed.end(), [] (const auto& first,
const auto& second) {
if (first.beat < second.beat) return true;
if (second.beat < first.beat) return false;
return first.note < second.note;
});
return transformed;
}

int sharedAccentBoost (double onsetBeat,
const std::vector<music::NoteEvent>& partnerEvents,
CouplingLevel level) noexcept
{
if (level == CouplingLevel::loose)
return 0;
const auto shared = std::any_of (
partnerEvents.begin(), partnerEvents.end(), [onsetBeat] (const auto& event) {
return std::abs (event.beat - onsetBeat) < 1.0e-9;
});
if (! shared)
return 0;
return level == CouplingLevel::tight ? 24 : 12;
}
} // namespace drift::engine
Loading