feat(html): the page plays sounds on button frames with Web Audio, as Test Movie does (M5)

This commit is contained in:
Tanish Manku committed 2026-11-11 14:04:59 -07:00
1 parent 7877a09c04
commit e60f65e800
3 files changed
+108 -9

No files matched your search

-4
View File
@@ -95,7 +95,6 @@ const FILTERS: &str = "filters (not exported; drawn without them)";
const BLENDS: &str = "Subtract and Invert blending (drawn normally)";
const BITMAP_TINT: &str = "tints on bitmap fills (drawn untinted)";
const PLUGIN_SCRIPTS: &str = "plug-in frame scripts (not exported; they need the plug-in host)";
const BUTTON_SOUNDS: &str = "sounds on button frames (not played yet)";
const KEPT_SCRIPTS: &str = "kept frame scripts outside the ActionScript subset (not run; kept in the document only)";
const NINE_SLICE: &str = "9-slice scaling (scaled as a whole)";
const OUTSIDE_CALLS: &str = "script calls that reach outside the movie (ignored)";
@@ -706,9 +705,6 @@ pub fn movie(doc: &Document, opts: &HtmlOptions) -> Movie {
frames += sym.timeline.frame_count() as usize;
let decls = (sym.kind == SymbolKind::MovieClip).then(|| anicraft_doc::player::decls(doc, TimelineRef::Symbol(*id)));
timelines.push(b.timeline(&sym.timeline, false, decls.as_ref()));
if b.sound && sym.kind == SymbolKind::Button && sym.timeline.layers.iter().any(|l| l.has_sounds()) {
b.notes.entry(BUTTON_SOUNDS).or_default().insert(sym.id.0);
}
let kind = match sym.kind {
SymbolKind::Graphic => "graphic",
SymbolKind::MovieClip => "movieclip",
+52 -5
View File
@@ -163,10 +163,26 @@ var AniCraft = (function () {
const c = st.clips.get(key);
return Math.min(c ? c.frame : 0, Math.max(len, 1) - 1);
}
// Where the pointer leaves a button (player.rs `ButtonState`): Up (0), Over (1), Down (2), or
// pressed on it and dragged off (3, shown Up).
function buttonState(hover, pressed, down, path) {
const held = down && samePath(pressed, path);
return samePath(hover, path) ? (held ? 2 : 1) : held ? 3 : 0;
}
// The frame whose sound plays as a button goes from state `a` to `b` (player.rs
// `button_sound_frame`, ADR 0057): Over's going over it, Up's leaving, Down's pressing, Hit's
// letting go over it; -1 for none.
function buttonSoundFrame(a, b) {
if (a === 0 && b === 1) return 1;
if (a === 1 && b === 0) return 0;
if (a === 1 && b === 2) return 2;
if (a === 2 && b === 1) return 3;
return -1;
}
// Up (0), Over (1) under the pointer, Down (2) while pressed on it.
function buttonFrame(st, path, len) {
const over = samePath(st.hover, path);
const f = over ? (st.down && samePath(st.pressed, path) ? 2 : 1) : 0;
const s = buttonState(st.hover, st.pressed, st.down, path);
const f = s === 1 || s === 2 ? s : 0;
return Math.min(f, Math.max(len, 1) - 1);
}
@@ -1063,10 +1079,34 @@ var AniCraft = (function () {
};
// The sounds of timeline `tl`'s keyframes starting at `frame`, as
// [sound, sync, repeat, loop, span, gain, envelope], the gain times `gain`.
Run.prototype.soundsAt = function (tl, frame, gain) {
// On a button's frame (`button`) a stream plays as an event: the frame has no span to stream
// over (ADR 0057).
Run.prototype.soundsAt = function (tl, frame, gain, button) {
for (const s of (tl.snd && tl.snd[frame]) || []) {
if (this.sounds.length >= MAX_SOUNDS_PER_STEP) return;
this.sounds.push([s[0], s[1], s[2], s[3], s[4], (s[5] === undefined ? 1 : s[5]) * gain, s[6] || null]);
const sync = button && s[1] === "stream" ? "event" : s[1];
this.sounds.push([s[0], sync, s[2], s[3], s[4], (s[5] === undefined ? 1 : s[5]) * gain, s[6] || null]);
}
};
// Where the pointer is, for buttonSounds.
Run.prototype.pointerNow = function () {
return { hover: this.st.hover, pressed: this.st.pressed, down: this.st.down };
};
// Starts the sounds of the buttons whose state changed since `before` (pointerNow then).
Run.prototype.buttonSounds = function (before) {
const st = this.st;
const same = (a, b) => (a === null ? b === null : samePath(a, b));
if (same(before.hover, st.hover) && same(before.pressed, st.pressed) && before.down === st.down) return;
this.refresh();
const paths = [];
for (const p of [before.hover, before.pressed, st.hover, st.pressed]) if (p !== null && !paths.some((q) => samePath(q, p))) paths.push(p);
for (const path of paths) {
const f = buttonSoundFrame(buttonState(before.hover, before.pressed, before.down, path), buttonState(st.hover, st.pressed, st.down, path));
if (f < 0) continue;
const i = this.indexOf(path);
if (i < 0 || this.nodes[i].kind !== BUTTON) continue;
const s = this.M.symbols[this.nodes[i].sym];
if (s) this.soundsAt(this.M.timelines[s.tl], f, this.nodes[i].gain, true);
}
};
Run.prototype.out = function (line) {
@@ -1577,19 +1617,24 @@ var AniCraft = (function () {
case "move":
this.pointer(e);
break;
case "down":
case "down": {
this.pointer(e);
const before = this.pointerNow();
st.down = true;
st.pressed = st.hover;
this.dirty = true;
this.buttonSounds(before);
if (st.hover !== null) this.fire(st.hover, "press");
break;
}
case "up": {
this.pointer(e);
const before = this.pointerNow();
st.down = false;
const pressed = st.pressed;
st.pressed = null;
this.dirty = true;
this.buttonSounds(before);
if (st.hover !== null) {
const h = st.hover;
this.fire(h, "release");
@@ -1617,9 +1662,11 @@ var AniCraft = (function () {
const now = p ? hitIn(this.M, st, this.nodes, this.host, p.x, p.y) : null;
const same = now === null ? st.hover === null : samePath(now, st.hover);
if (!same) {
const before = this.pointerNow();
const old = st.hover;
st.hover = now;
this.dirty = true;
this.buttonSounds(before);
if (old !== null) this.fire(old, "out");
if (now !== null) this.fire(now, "over");
}
+56
View File
@@ -630,6 +630,62 @@ fn sounds_carry_their_envelopes_and_volumes_and_start_in_graphics_and_clips_as_i
}
}
#[test]
fn button_sounds_start_in_the_page_as_in_the_player() {
use anicraft_doc::{FrameSound, Sound, SoundId, SoundSync};
// A button at (100, 100), 10 × 10 art, a 100 × 100 Hit frame; a sound on each of its frames
// (Over's a stream) on a layer at half volume; the button's own layer at half volume too.
let mut d = Document::default();
for (i, name) in ["up", "over", "down", "hit"].iter().enumerate() {
let wav = anicraft_doc::audio::wav::encode(8000, 1, &[0.25; 800], anicraft_doc::audio::wav::Bits::Int16);
d.sounds.push(Arc::new(Sound::from_data(SoundId(60 + i as u64), *name, wav).unwrap()));
}
let with = |k: Arc<Keyframe>, i: u64, sync| {
let mut k = (*k).clone();
k.sound = Some(FrameSound { sync, ..FrameSound::new(SoundId(60 + i)) });
Arc::new(k)
};
let mut sounds = (*layer(34, vec![with(kf(0, 1, vec![], vec![], ""), 0, SoundSync::Event), with(kf(1, 1, vec![], vec![], ""), 1, SoundSync::Stream), with(kf(2, 1, vec![], vec![], ""), 2, SoundSync::Event), with(kf(3, 1, vec![], vec![], ""), 3, SoundSync::Event)])).clone();
sounds.volume = 0.5;
let art = || vec![rect(32, 0.0, 0.0, 10.0, 10.0, 0x336699)];
let states = layer(31, vec![kf(0, 1, art(), vec![], ""), kf(1, 1, art(), vec![], ""), kf(2, 1, art(), vec![], ""), kf(3, 1, vec![rect(33, 0.0, 0.0, 100.0, 100.0, 0)], vec![], "")]);
d.library.push(symbol(300, SymbolKind::Button, vec![Arc::new(sounds), states]));
let mut holder = (*layer(2, vec![kf(0, 4, vec![inst(3, 300, "go", Affine::translate(100.0, 100.0), vec![])], vec![], "")])).clone();
holder.volume = 0.5;
d.timeline_mut(0).layers = vec![Arc::new(holder)];
let m = movie(&d, &HtmlOptions::default());
let names: Vec<String> = m.json["sounds"].as_array().unwrap().iter().map(|s| s["name"].as_str().unwrap().to_string()).collect();
assert_eq!(names.len(), 4, "every button sound is embedded");
assert!(m.report.keys().all(|n| !n.contains("button")), "nothing reported: {:?}", m.report);
let mut js = Js::new(&m);
let mut r = start(&d, &mut NoScripts);
js.eval("P.start()");
let at = |x, y| Vec2::new(x, y);
// Over, about, Down, Hit (released), Up (left), Over and Down at once, dragged off and back.
let batches: Vec<Vec<Event>> = vec![
vec![Event::Move(at(150.0, 150.0))],
vec![Event::Move(at(160.0, 150.0))],
vec![Event::Down(at(160.0, 150.0))],
vec![Event::Up(at(160.0, 150.0))],
vec![Event::Leave],
vec![Event::Down(at(150.0, 150.0))],
vec![Event::Move(at(400.0, 300.0)), Event::Move(at(150.0, 150.0)), Event::Up(at(150.0, 150.0))],
];
let mut heard = Vec::new();
for (i, events) in batches.iter().enumerate() {
// Between frames and with a frame, alike.
let (rs, page) = if i % 2 == 0 { (anicraft_doc::player::input(&d, &r.state, events, &mut NoScripts), js.eval(&format!("P.input({}).sounds", js_events(events)))) } else { (step(&d, &r.state, events, &mut NoScripts), js.eval(&format!("P.step({}).sounds", js_events(events)))) };
let theirs: Vec<Value> = rs.sounds.iter().map(|s| json!([d.sound(s.sound.sound).unwrap().name, s.sound.sync.key(), f64::from(s.gain)])).collect();
let ours: Vec<Value> = page.as_array().unwrap().iter().map(|s| json!([names[s[0].as_u64().unwrap() as usize], s[1], s[5].as_f64()])).collect();
assert_eq!(ours, theirs, "batch {i}");
heard.extend(theirs);
r = rs;
}
let order: Vec<&str> = heard.iter().map(|h| h[0].as_str().unwrap()).collect();
assert_eq!(order, ["over", "down", "hit", "up", "over", "down", "hit"]);
assert!(heard.iter().all(|h| h[1] == "event" && h[2] == 0.25), "{heard:?}");
}
#[test]
fn hostile_documents_export_without_panicking() {
let mut doc = Document::default();