iOS milestone 2 groundwork: song model in C++, whole-song references from Kotlin

IosGoldenSongs exports .szg/.sng/.szp files and full AudioEngine renders of four
songs (demo, mix, waltz, midifx); Model.hpp is the C++ twin of model/.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Reactorcoremeltdown
2026-11-15 22:50:10 +01:00
co-authored by Claude Opus 5.5
parent c6520277b7
commit b1dc5ed8db
3 changed files with 563 additions and 0 deletions
@@ -0,0 +1,248 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
package cc.tiredsysadmin.android.sizzle.audio
import cc.tiredsysadmin.android.sizzle.echofield.EchofieldDefs
import cc.tiredsysadmin.android.sizzle.frasil.FrasilClock
import cc.tiredsysadmin.android.sizzle.frasil.FrasilDefs
import cc.tiredsysadmin.android.sizzle.frasil.FrasilVoice
import cc.tiredsysadmin.android.sizzle.echofield.GrainCloud
import cc.tiredsysadmin.android.sizzle.io.PresetIo
import cc.tiredsysadmin.android.sizzle.io.ProjectIo
import cc.tiredsysadmin.android.sizzle.io.SngFormat
import cc.tiredsysadmin.android.sizzle.model.Arrangement
import cc.tiredsysadmin.android.sizzle.model.Cell
import cc.tiredsysadmin.android.sizzle.model.NesSynthPresets
import cc.tiredsysadmin.android.sizzle.model.Pattern
import cc.tiredsysadmin.android.sizzle.model.Project
import cc.tiredsysadmin.android.sizzle.model.SamplerPads
import cc.tiredsysadmin.android.sizzle.model.Scale
import cc.tiredsysadmin.android.sizzle.model.TimeSignature
import cc.tiredsysadmin.android.sizzle.model.ToolboxType
import cc.tiredsysadmin.android.sizzle.wavetable.WaveDefs
import cc.tiredsysadmin.android.sizzle.wavetable.WaveTables
import org.junit.Assume.assumeTrue
import org.junit.Test
import java.io.File
import java.nio.ByteBuffer
import java.nio.ByteOrder
/**
* Whole songs for the iOS port's model, file formats and engine (milestone 2 in
* ios/PORTING.md). Runs only when SIZZLE_GOLDEN_DIR is set. Per song, in
* SIZZLE_GOLDEN_DIR/songs/:
*
* <song>.szg ProjectIo.save (the full project format)
* <song>.sng SngFormat.export (the desktop-compatible format)
* <song>.slot<N>.szp PresetIo.export of every filled toolbox slot
* <song>.render.f32 AudioEngine.fillBlock output (48 kHz, stereo interleaved,
* 256-frame blocks) after play(), for songs with "render"
* <song>.meta sr, block, seconds, the Morph Pad clock and the voice-seed
* counters before the engine was built ("seeds <frasil> <grain>"),
* and the sample the Sampler/SF2 slots use ("sample <id> <rate>
* <loopStart> <loopEnd>", data in <song>.smp.f32)
*
* The C++ port must parse each .szg / .sng / .szp and write it back byte for
* byte, and render the same audio from the parsed .szg.
*/
class IosGoldenSongs {
@Test fun export() {
val dir = System.getenv("SIZZLE_GOLDEN_DIR")
assumeTrue("set SIZZLE_GOLDEN_DIR to export", dir != null)
val out = File(dir!!, "songs").apply { mkdirs() }
WaveTables.prewarmBlocking()
GrainSources.prewarmBlocking()
SampleStore.put(SAMPLE_ID, testSample())
// The repo's demo song (despite its name, in the full ProjectIo format) as
// it loads, then with instruments on its empty channels.
val demoText = File(repoRoot(), "samples/demo.sng").readText()
write(out, "demo_imported", ProjectIo.loadInto(Project(), demoText), seconds = 0.0)
write(out, "demo", demoWithInstruments(demoText), seconds = 12.0)
write(out, "mix", mixSong(), seconds = 12.0)
write(out, "waltz", waltzSong(), seconds = 10.0)
write(out, "midifx", midiFxSong(), seconds = 10.0)
}
private fun repoRoot(): File {
var f = File("").absoluteFile
while (!File(f, "samples/demo.sng").exists()) f = f.parentFile ?: error("repo root not found")
return f
}
private fun write(out: File, name: String, p: Project, seconds: Double) {
File(out, "$name.szg").writeText(ProjectIo.save(p))
File(out, "$name.sng").writeText(SngFormat.export(p))
p.toolbox.forEach { s -> if (!s.isEmpty) File(out, "$name.slot${s.index}.szp").writeText(PresetIo.export(s)) }
val meta = StringBuilder("song $name\nsr $SR\nblock $BLOCK\nseconds $seconds\n")
val smp = SampleStore.get(SAMPLE_ID)!!
meta.append("sample $SAMPLE_ID ${smp.sampleRate} ${smp.loopStart} ${smp.loopEnd}\n")
if (seconds > 0) {
meta.append("clock ${java.lang.Double.toString(FrasilClock.seconds)}\n")
meta.append("seeds ${counter(FrasilVoice::class.java)} ${counter(GrainCloud::class.java)}\n")
val engine = AudioEngine(SR).apply { setProject(p) }
engine.play()
val frames = (seconds * SR).toInt() / BLOCK * BLOCK
val buf = FloatArray(BLOCK * 2)
val bb = ByteBuffer.allocate(frames * 2 * 4).order(ByteOrder.LITTLE_ENDIAN)
repeat(frames / BLOCK) {
engine.fillBlock(buf, BLOCK)
buf.forEach { v -> bb.putFloat(v) }
}
File(out, "$name.render.f32").writeBytes(bb.array())
}
File(out, "$name.meta").writeText(meta.toString())
val sb = ByteBuffer.allocate(smp.data.size * 4).order(ByteOrder.LITTLE_ENDIAN)
smp.data.forEach { sb.putFloat(it) }
File(out, "$name.smp.f32").writeBytes(sb.array())
}
/** The private `seeds` counter a voice class takes its next seed from. */
private fun counter(c: Class<*>): Int {
val f = runCatching { c.getDeclaredField("seeds") }.getOrElse {
Class.forName(c.name + "\$Companion").getDeclaredField("seeds")
}
f.isAccessible = true
return f.getInt(null)
}
private fun testSample() = SampleStore.Sample(FloatArray(44_100) { i ->
val t = i / 44_100.0
(0.6 * kotlin.math.sin(2 * Math.PI * 330 * t) * kotlin.math.exp(-t * 2.5) +
0.2 * (2 * ((t * 110) % 1.0) - 1) * kotlin.math.exp(-t * 6)).toFloat()
}, 44_100, loopStart = 6_000, loopEnd = 30_000)
// ----------------------------------------------------------------- songs
/** Deterministic notes: an LCG so every run writes the same song. */
private class Gen(var s: Int) {
fun next(n: Int): Int { s = s * 1103515245 + 12345; return ((s ushr 8) and 0x7FFFFF) % n }
}
private fun fill(p: Project, pattern: Int, gen: Gen, scale: List<Int>, root: Int, density: Int, offs: Boolean) {
val pat = p.patterns[pattern]
for (t in 0 until Pattern.TRACK_COUNT) for (l in 0 until pat.length) {
val c = pat.cell(t, l)
c.channel = t + 1
when {
gen.next(100) < density -> {
c.note = root + 12 * (t % 2) + scale[gen.next(scale.size)] + 12 * gen.next(2)
c.velocity = 40 + gen.next(88)
}
offs && gen.next(100) < 10 -> c.note = Cell.OFF
}
}
}
private fun route(p: Project, ch: Int, instrument: Int, vararg fx: Int, volume: Float = 0.8f) {
val m = p.mixer.channels[ch]
m.midiChannel = ch + 1
m.instrumentSlot = instrument
fx.forEachIndexed { i, s -> m.fxSlots[i] = s }
m.volume = volume
}
private fun preset(p: Project, slot: Int, type: ToolboxType, values: Map<String, String>) {
p.toolbox[slot].fill(type)
values.forEach { (k, v) -> p.toolbox[slot].set(k, v) }
}
/** Four instruments with factory presets through eight different effects. */
private fun mixSong(): Project = Project().apply {
name = "iOS golden mix"
tempoBpm = 126f
scale = Scale.MINOR
rootNote = 9
NesSynthPresets.apply(toolbox[0].apply { fill(ToolboxType.NES_SYNTH) }, NesSynthPresets.FACTORY[1])
preset(this, 1, ToolboxType.WAVETABLE, WaveDefs.FACTORY[2].values)
preset(this, 2, ToolboxType.MORPH_PAD, FrasilDefs.FACTORY[3].values)
preset(this, 3, ToolboxType.GRAIN_CLOUD, EchofieldDefs.FACTORY[0].values)
listOf(ToolboxType.DELAY, ToolboxType.FILTER, ToolboxType.EQ10, ToolboxType.AMBIENCE,
ToolboxType.BITCRUSHER, ToolboxType.MIX_TIGHTENER, ToolboxType.TAPE_ENGINE, ToolboxType.GRANULAR)
.forEachIndexed { i, t -> toolbox[4 + i].fill(t) }
toolbox[5].set("cutoff", 0.45f); toolbox[6].set("band2", 0.5f); toolbox[8].set("bits", 6f)
route(this, 0, 0, 4, volume = 0.7f)
route(this, 1, 1, 5, 6)
route(this, 2, 2, 7, volume = 0.9f)
route(this, 3, 3, 8, 9, 10, 11)
mixer.channels[3].limiter = true
val g = Gen(0x5EED)
for (pt in 0 until 4) fill(this, pt, g, scale.intervals, 45, density = 30, offs = true)
for (bar in 0 until 8) for (lane in 0 until 4) {
val beat = bar * 4
if ((bar + lane) % 3 != 2) arrangement.set(lane, beat, (bar + lane) % 4)
}
arrangement.set(1, 6 * 4 + 2, Arrangement.NOTE_OFF)
}
/** 3/4, Sampler + SF2/XI with the test sample, tape effects, a loop region, mutes. */
private fun waltzSong(): Project = Project().apply {
name = "iOS golden waltz"
tempoBpm = 95f
timeSignature = TimeSignature.THREE_FOUR
patterns.forEach { it.resize(timeSignature.lengthOptions[0]) }
scale = Scale.MAJOR
rootNote = 2
toolbox[0].fill(ToolboxType.SAMPLER)
for (pad in 0 until SamplerPads.COUNT) toolbox[0].set(SamplerPads.key(pad), SAMPLE_ID)
toolbox[0].set(SamplerPads.sliceStartKey(3), 0.2f); toolbox[0].set(SamplerPads.volumeKey(5), 0.5f)
toolbox[1].fill(ToolboxType.SOUNDFONT)
toolbox[1].set("sfSample", SAMPLE_ID); toolbox[1].set("sfRoot", 62f); toolbox[1].set("loop", "On")
toolbox[2].fill(ToolboxType.TAPE_ENGINE)
toolbox[3].fill(ToolboxType.GRANULAR); toolbox[3].set("intensity", 0.6f)
toolbox[4].fill(ToolboxType.AMBIENCE)
route(this, 0, 0, 2)
route(this, 1, 1, 3, 4)
route(this, 2, 1, volume = 0.6f)
route(this, 3, 0)
mixer.channels[3].mute = true
val g = Gen(0x3A17)
for (pt in 0 until 4) {
fill(this, pt, g, listOf(0, 2, 4, 7, 9), 36, density = 35, offs = false)
// pads live at notes 36..51: keep track 0 (channel 1 → the Sampler) there
for (l in 0 until patterns[pt].length) patterns[pt].cell(0, l).let { if (it.isPlayable) it.note = 36 + (it.note % 16) }
}
for (bar in 0 until 6) for (lane in 0 until 3) arrangement.set(lane, bar * 3, (bar + lane) % 4)
arrangement.laneMuted[2] = true
arrangement.loopEnabled = true
arrangement.regionA.apply { enabled = true; start = 3; end = 9; repeats = 2 }
}
/** MIDI effects: an arpeggiator, a transposer and an LFO on a filter cutoff. */
private fun midiFxSong(): Project = Project().apply {
name = "iOS golden midifx"
tempoBpm = 110f
NesSynthPresets.apply(toolbox[0].apply { fill(ToolboxType.NES_SYNTH) }, NesSynthPresets.FACTORY[2])
preset(this, 1, ToolboxType.WAVETABLE, WaveDefs.FACTORY[5].values)
toolbox[2].fill(ToolboxType.ARPEGGIATOR)
toolbox[2].set("mode", "UpDown"); toolbox[2].set("octaves", 2f)
toolbox[3].fill(ToolboxType.TRANSPOSER); toolbox[3].set("semitones", 7f)
toolbox[4].fill(ToolboxType.FILTER)
toolbox[5].fill(ToolboxType.LFO)
toolbox[5].set("target", "4:cutoff"); toolbox[5].set("depth", 0.8f)
route(this, 0, 0, 2, 4)
route(this, 1, 1, 3)
val g = Gen(0x1F0)
for (pt in 0 until 2) fill(this, pt, g, Scale.MAJOR.intervals, 48, density = 20, offs = true)
for (bar in 0 until 6) { arrangement.set(0, bar * 4, bar % 2); arrangement.set(1, bar * 4, (bar + 1) % 2) }
}
/** The demo song with an instrument on each of its channels (its own mixer
* routing kept: channel n listens on MIDI channel n + 1). */
private fun demoWithInstruments(text: String): Project = ProjectIo.loadInto(Project(), text).apply {
preset(this, 1, ToolboxType.WAVETABLE, WaveDefs.FACTORY[0].values)
preset(this, 2, ToolboxType.MORPH_PAD, FrasilDefs.FACTORY[0].values)
NesSynthPresets.apply(toolbox[3].apply { fill(ToolboxType.NES_SYNTH) }, NesSynthPresets.FACTORY[3])
toolbox[4].fill(ToolboxType.AMBIENCE)
for (ch in 1 until 4) mixer.channels[ch].instrumentSlot = ch
mixer.channels[2].fxSlots[0] = 4
}
private companion object {
const val SR = 48_000
const val BLOCK = 256
const val SAMPLE_ID = "ios-golden-song-sample"
}
}
+164
View File
@@ -0,0 +1,164 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#pragma once
// The song model: the C++ twin of the Android app's model/ package (Project,
// Pattern, Cell, Arrangement, LoopRegion, Mixer, MixerChannel, ToolboxSlot,
// TimeSignature, Scale, Pitch). Plain data with the same names, fields, defaults
// and constants, so the file formats (core/src/io) and the engine
// (core/src/engine) read like their Kotlin originals.
//
// Threads: like Android's, the model is edited by the UI and read by the audio
// thread. Toolbox values are text (sizzle::Params), as ToolboxSlot's map is.
#include <array>
#include <string>
#include <vector>
#include "sizzle/Params.hpp"
namespace sizzle::model {
struct Pitch {
static constexpr int LOWEST = 0, HIGHEST = 127, MIDDLE_C = 60;
};
struct TimeSignatureInfo {
const char *name; // enum name, as files store it ("FOUR_FOUR")
const char *label; // "4/4"
int linesPerBeat;
int beatsPerBar;
int lengthOptions[3];
int linesPerBar() const { return linesPerBeat * beatsPerBar; }
};
enum class TimeSignature { THREE_FOUR, FOUR_FOUR, FIVE_FOUR };
inline constexpr int TIME_SIGNATURE_COUNT = 3;
const TimeSignatureInfo &info(TimeSignature t);
struct ScaleInfo {
const char *name; // "MINOR"
const char *label; // "Natural Minor"
int intervals[12];
int count;
};
enum class Scale { CHROMATIC, MAJOR, MINOR, HARMONIC_MINOR, DORIAN, PHRYGIAN, MIXOLYDIAN,
PENTATONIC_MAJOR, PENTATONIC_MINOR, BLUES };
inline constexpr int SCALE_COUNT = 10;
const ScaleInfo &info(Scale s);
struct Cell {
static constexpr int EMPTY = -1, OFF = -2, MAX_VELOCITY = 0x7F, MAX_CHANNEL = 16;
int note = EMPTY;
int velocity = MAX_VELOCITY;
int channel = 1;
bool isEmpty() const { return note == EMPTY; }
bool isNoteOff() const { return note == OFF; }
bool isPlayable() const { return note >= Pitch::LOWEST && note <= Pitch::HIGHEST; }
void clear() { note = EMPTY; velocity = MAX_VELOCITY; }
};
struct Pattern {
static constexpr int TRACK_COUNT = 4;
int id = 0;
std::string name = "PTN";
int length = 16;
/** tracks[track][line]; cells start with channel 0, as Kotlin's do. */
std::array<std::vector<Cell>, TRACK_COUNT> tracks;
Pattern(int id_ = 0, std::string name_ = "PTN", int length_ = 16);
Cell &cell(int track, int line) { return tracks[track][line]; }
const Cell &cell(int track, int line) const { return tracks[track][line]; }
void resize(int newLength);
};
struct LoopRegion {
bool enabled = false;
int start = 0, end = 0, repeats = 2;
bool isValid() const { return enabled && end > start; }
};
struct Arrangement {
static constexpr int LANE_COUNT = 8, MAX_BARS = 256, MAX_BEATS = MAX_BARS * 5;
static constexpr int EMPTY = -1, NOTE_OFF = -2;
/** slots[lane][beat]: a pattern id, EMPTY or NOTE_OFF. */
std::array<std::vector<int>, LANE_COUNT> slots;
std::array<bool, LANE_COUNT> laneMuted{};
int lengthBars = MAX_BARS;
bool loopEnabled = false;
LoopRegion regionA, regionB;
Arrangement();
int canvasBeats(TimeSignature sig) const;
int patternAt(int lane, int beat) const;
bool hasBlockAt(int lane, int beat) const { return patternAt(lane, beat) >= 0; }
int lastFilledBeat() const;
void set(int lane, int beat, int patternId);
};
struct MixerChannel {
static constexpr int FX_SLOTS = 4;
int index = 0;
int instrumentSlot = -1;
std::array<int, FX_SLOTS> fxSlots{-1, -1, -1, -1};
int midiChannel = 1;
float volume = 0.8f;
bool mute = false, solo = false, limiter = false;
bool audible(bool anySolo) const { return !mute && (!anySolo || solo); }
};
struct Mixer {
static constexpr int CHANNEL_COUNT = Pattern::TRACK_COUNT, FX_SLOTS = MixerChannel::FX_SLOTS;
static constexpr int NO_DEVICE = -1;
static constexpr float DEFAULT_VOLUME = 0.8f;
std::array<MixerChannel, CHANNEL_COUNT> channels;
Mixer(); // channel i: index i, midiChannel 0 (as Kotlin's Mixer builds them)
bool anySolo() const;
};
/** One toolbox slot: a device type (ToolboxType name; empty = no device), its
* display name and its settings as text. */
struct ToolboxSlot {
int index = 0;
std::string type;
std::string name;
Params values;
/** Bumped on every settings write (Kotlin's `version`), so the engine can
* skip re-reading unchanged slots. */
uint32_t version = 0;
bool isEmpty() const { return type.empty(); }
/** ToolboxSlot.fill: the type's defaults (spec order), its display name. */
void fill(const std::string &newType);
void clearSlot();
float f(const char *key, float fallback = 0.f) const { return values.f(key, fallback); }
const char *s(const char *key, const char *fallback = "") const { return values.s(key, fallback); }
void set(const char *key, float v); // stored as Kotlin's Float.toString text
void set(const char *key, const char *v);
};
struct Project {
static constexpr int TOOLBOX_SLOTS = 16;
std::string name = "untitled";
float tempoBpm = 120.f;
TimeSignature timeSignature = TimeSignature::FOUR_FOUR;
Scale scale = Scale::CHROMATIC;
int rootNote = 0;
/** LANE_COUNT patterns, ids 0..7, named BLK1..BLK8, first length option. */
std::vector<Pattern> patterns;
Arrangement arrangement;
Mixer mixer;
std::array<ToolboxSlot, TOOLBOX_SLOTS> toolbox;
int activePatternId = 0;
Project();
Pattern *pattern(int id);
const Pattern *pattern(int id) const;
Pattern &activePattern();
};
/** Kotlin's Float.toString (JDK 17's algorithm), e.g. "120.0", "0.8", "1.0E-4":
* what Android writes into settings and files. */
std::string kotlinFloatToString(float v);
} // namespace sizzle::model
+151
View File
@@ -0,0 +1,151 @@
// SPDX-FileCopyrightText: 2026 Reactorcoremeltdown
// SPDX-License-Identifier: GPL-3.0-or-later
#include "sizzle/Model.hpp"
#include <algorithm>
#include <charconv>
#include <cmath>
#include <cstring>
#include "sizzle/Specs.hpp"
namespace sizzle::model {
static const TimeSignatureInfo kSignatures[TIME_SIGNATURE_COUNT] = {
{"THREE_FOUR", "3/4", 3, 3, {12, 24, 48}},
{"FOUR_FOUR", "4/4", 4, 4, {16, 32, 64}},
{"FIVE_FOUR", "5/4", 5, 5, {20, 40, 80}},
};
const TimeSignatureInfo &info(TimeSignature t) { return kSignatures[(int)t]; }
static const ScaleInfo kScales[SCALE_COUNT] = {
{"CHROMATIC", "Chromatic", {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, 12},
{"MAJOR", "Major", {0, 2, 4, 5, 7, 9, 11}, 7},
{"MINOR", "Natural Minor", {0, 2, 3, 5, 7, 8, 10}, 7},
{"HARMONIC_MINOR", "Harmonic Minor", {0, 2, 3, 5, 7, 8, 11}, 7},
{"DORIAN", "Dorian", {0, 2, 3, 5, 7, 9, 10}, 7},
{"PHRYGIAN", "Phrygian", {0, 1, 3, 5, 7, 8, 10}, 7},
{"MIXOLYDIAN", "Mixolydian", {0, 2, 4, 5, 7, 9, 10}, 7},
{"PENTATONIC_MAJOR", "Pentatonic Major", {0, 2, 4, 7, 9}, 5},
{"PENTATONIC_MINOR", "Pentatonic Minor", {0, 3, 5, 7, 10}, 5},
{"BLUES", "Blues", {0, 3, 5, 6, 7, 10}, 6},
};
const ScaleInfo &info(Scale s) { return kScales[(int)s]; }
Pattern::Pattern(int id_, std::string name_, int length_) : id(id_), name(std::move(name_)), length(length_) {
for (auto &t : tracks) t.assign((size_t)length, Cell{Cell::EMPTY, Cell::MAX_VELOCITY, 0});
}
void Pattern::resize(int newLength) {
if (newLength == length) return;
for (auto &t : tracks) t.resize((size_t)newLength, Cell{Cell::EMPTY, Cell::MAX_VELOCITY, 0});
length = newLength;
}
Arrangement::Arrangement() { for (auto &l : slots) l.assign(MAX_BEATS, EMPTY); }
int Arrangement::canvasBeats(TimeSignature sig) const {
return std::clamp(lengthBars * info(sig).beatsPerBar, 1, MAX_BEATS);
}
int Arrangement::patternAt(int lane, int beat) const {
return beat >= 0 && beat < MAX_BEATS ? slots[lane][beat] : EMPTY;
}
int Arrangement::lastFilledBeat() const {
for (int beat = MAX_BEATS - 1; beat >= 0; --beat)
for (int lane = 0; lane < LANE_COUNT; ++lane)
if (slots[lane][beat] != EMPTY) return beat;
return -1;
}
void Arrangement::set(int lane, int beat, int patternId) {
if (lane >= 0 && lane < LANE_COUNT && beat >= 0 && beat < MAX_BEATS) slots[lane][beat] = patternId;
}
Mixer::Mixer() {
for (int i = 0; i < CHANNEL_COUNT; ++i) { channels[i].index = i; channels[i].midiChannel = 0; }
}
bool Mixer::anySolo() const {
for (auto &c : channels) if (c.solo) return true;
return false;
}
void ToolboxSlot::fill(const std::string &newType) {
type = newType;
values = Params();
const DeviceSpec *spec = findDevice(newType.c_str());
name = spec ? spec->displayName : newType;
if (!spec) return;
for (int i = 0; i < spec->paramCount; ++i) {
const ParamSpec &p = spec->params[i];
if (p.isEnum()) {
int n = p.choiceCount(), idx = std::clamp((int)p.def, 0, n - 1);
values.set(p.key, p.choices[idx]);
} else {
values.set(p.key, kotlinFloatToString(p.def).c_str());
}
}
++version;
}
void ToolboxSlot::clearSlot() { type.clear(); name.clear(); values = Params(); ++version; }
void ToolboxSlot::set(const char *key, float v) { values.set(key, kotlinFloatToString(v).c_str()); ++version; }
void ToolboxSlot::set(const char *key, const char *v) { values.set(key, v); ++version; }
Project::Project() {
for (int i = 0; i < Arrangement::LANE_COUNT; ++i)
patterns.emplace_back(i, "BLK" + std::to_string(i + 1), info(timeSignature).lengthOptions[0]);
for (int i = 0; i < TOOLBOX_SLOTS; ++i) toolbox[i].index = i;
}
Pattern *Project::pattern(int id) {
for (auto &p : patterns) if (p.id == id) return &p;
return nullptr;
}
const Pattern *Project::pattern(int id) const {
for (auto &p : patterns) if (p.id == id) return &p;
return nullptr;
}
Pattern &Project::activePattern() {
Pattern *p = pattern(activePatternId);
return p ? *p : patterns.front();
}
// Shortest round-trip digits in Java's layout: plain for 1e-3 <= |v| < 1e7
// ("120.0", "0.8"), else computerized scientific ("1.0E-4", "1.2345678E7").
// JDK 17's FloatingDecimal is not always shortest; the file-format port pins it
// down against the reference files.
std::string kotlinFloatToString(float v) {
if (std::isnan(v)) return "NaN";
if (std::isinf(v)) return v > 0 ? "Infinity" : "-Infinity";
if (v == 0.f) return std::signbit(v) ? "-0.0" : "0.0";
char buf[64];
auto r = std::to_chars(buf, buf + sizeof buf, v, std::chars_format::scientific);
std::string sci(buf, r.ptr); // d.dddde±XX
size_t e = sci.find('e');
std::string mant = sci.substr(0, e);
int exp = std::stoi(sci.substr(e + 1));
bool neg = mant[0] == '-';
if (neg) mant.erase(0, 1);
std::string digits;
for (char c : mant) if (c != '.') digits += c;
std::string out;
float a = std::fabs(v);
if (a >= 1e-3f && a < 1e7f) {
if (exp >= 0) {
std::string ip = digits.substr(0, std::min<size_t>(digits.size(), (size_t)exp + 1));
while ((int)ip.size() < exp + 1) ip += '0';
std::string fp = (size_t)exp + 1 < digits.size() ? digits.substr((size_t)exp + 1) : "0";
out = ip + "." + fp;
} else {
out = "0." + std::string((size_t)(-exp - 1), '0') + digits;
}
} else {
out = digits.substr(0, 1) + "." + (digits.size() > 1 ? digits.substr(1) : "0") + "E" + std::to_string(exp);
}
return neg ? "-" + out : out;
}
} // namespace sizzle::model