A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.
TypeScript 2d-game-engine3d3d-game-engineandroidcppecsgame-editorgame-enginegamedeviostypescriptwebassemblywebglwebgpuwechat-minigame
feat(audio): connect sound event sources and graph triggers
yhha416e86e8844
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b49dc51e9..7f1abeca6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,9 +16,11 @@ published separately; it ships inside the editor.### Added-- **Sound event playback owns pending and paused voices.** The per-App SoundEvents resource loads owned emitters, shares event concurrency and cooldown before clip IO, and routes selected clips through the existing Audio priority pool. Natural completion, Stop All, owner despawn, registry disconnect and App cleanup release receipts and cancel late starts. Requests expose selected parameters, lifecycle and rejection reasons; spatial events reuse source attenuation/panning. Pending admissions avoid rescanning the loading queue, and unchanged gains skip backend writes. Dedicated event authoring, components and visual-script nodes remain in progress.+- **Sound event sources share code and graph triggers.** SoundEventSource references the same validated event assets as SoundEvents; script graphs, FSM hooks and BT actions expose trigger/stop verbs. Same-frame triggers retain their order, cold definitions retain at most 256 intents per source, and source lifetime checks cancel stale definitions and clips after edits, removal, disable, Stop All or teardown. Scene preload, inspector pickers, UUID projection and export dependencies use the shared asset metadata. Dedicated event authoring and continuous preview remain in progress.-- **Sound event definitions share deterministic selection.** Beta `.esaudioevent` assets validate weighted clip slots, sequential and no-repeat selection, volume/rate ranges and event playback settings. The shared selector uses independent seeded streams for clip and parameter choices, combines duplicate audio identities, and reports empty or disabled pools. Definitions load through Assets without decoding every candidate; export dependency scanning retains all candidates and UUID references survive file moves. This provides the resource and selection layer for RM-066; dedicated authoring, component and visual-script integration remain in progress.+- **Sound event playback owns pending and paused voices.** The per-App SoundEvents resource loads owned emitters, shares event concurrency and cooldown before clip IO, and routes selected clips through the existing Audio priority pool. Natural completion, Stop All, owner despawn, registry disconnect and App cleanup release receipts and cancel late starts. Requests expose selected parameters, lifecycle and rejection reasons; spatial events reuse source attenuation/panning. Pending admissions avoid rescanning the loading queue, and unchanged gains skip backend writes.++- **Sound event definitions share deterministic selection.** Beta `.esaudioevent` assets validate weighted clip slots, sequential and no-repeat selection, volume/rate ranges and event playback settings. The shared selector uses independent seeded streams for clip and parameter choices, combines duplicate audio identities, and reports empty or disabled pools. Definitions load through Assets without decoding every candidate; export dependency scanning retains all candidates and UUID references survive file moves.### Fixeddiff --git a/desktop b/desktopindex 29e0b24c5..1022aabd0 160000--- a/desktop+++ b/desktop@@ -1 +1 @@-Subproject commit 29e0b24c5d851f4a50af8afa88d0c35a5a7370c0+Subproject commit 1022aabd027441cc4b0e1c2583671300e9aa84d1diff --git a/docs/astro/src/content/docs/assets/audio.mdx b/docs/astro/src/content/docs/assets/audio.mdxindex bc2fa9cf0..87facb296 100644--- a/docs/astro/src/content/docs/assets/audio.mdx+++ b/docs/astro/src/content/docs/assets/audio.mdx@@ -118,8 +118,8 @@ started, ended, stopped and rejected counts without storing trigger history.Spatial events reuse AudioSource attenuation and panning; provide an owner with aworld transform or a position to `trigger()`. Without a listener the origin is used.Mini-game hosts without stereo panning report that limitation while retaining-software distance attenuation. The dedicated event editor and component/visual-script-integration remain in RM-066.+software distance attenuation. See [Sound event source](#sound-event-source) for component+and graph triggers. Dedicated event authoring and continuous preview remain in RM-066.## `Audio` API reference@@ -381,6 +381,44 @@ const gain = calculateAttenuation(250, {const pan = calculatePanning(600, 0, 0, 0, 1000); // 0.6 — to the right```+### Sound event source++Add `SoundEventSource` to an entity and pick its `.esaudioevent` resource. Scene+preloading acquires the definition without decoding all its candidates. The+component's `seed` (default `0`) fixes its choice stream; `playOnAwake` plays once+per enabled component lifetime. Changing the event or seed creates a new stream.++```typescript+import { SoundEventSource, triggerSoundEventSource, stopSoundEventSource } from 'esengine';++app.world.insert(entity, SoundEventSource, { event: 'assets/steps.esaudioevent', seed: 42 });+const voice = await triggerSoundEventSource(app.world, entity);+if (voice) {+ await voice.ready;+ console.log(voice.status, voice.reason, voice.selection);+}+stopSoundEventSource(app.world, entity);+```++Use `soundEvent.trigger` / `soundEvent.stop` in script graphs, FSM hooks or BT+actions to reach the same source. Each trigger is independent, including multiple+triggers in one frame. Graph actions continue immediately while loading proceeds.+They do not wait for clip completion.++Cold definitions queue at most 256 intents per source, in FIFO order. Excess+intents, unavailable/disabled sources, failed definitions and cancelled intents+resolve to `null`. A returned handle reports clip loading and event/global voice+rejections separately. Event cooldown begins when the loaded definition admits+an intent, so several cold intents may share an admission time.++Stopping cancels this source's queue and voices; other emitters on the entity+remain owned by their callers. A later trigger restarts this source's seeded+stream. Disable, removal, event/seed changes, inactive hierarchy, despawn and+registry disconnect invalidate its old lifetime. These checks also run after+asynchronous loads, preventing a late clip from playing before the next frame.+Global `Audio.stopAll()` cancels pending source intents while preserving prepared+definitions. Local source stop does not replay `playOnAwake` on the next frame.+## Best practices- **Preload** clips you'll play in performance-critical moments (`preload` /diff --git a/docs/astro/src/content/docs/zh-cn/assets/audio.mdx b/docs/astro/src/content/docs/zh-cn/assets/audio.mdxindex 2101cd847..77b635ff7 100644--- a/docs/astro/src/content/docs/zh-cn/assets/audio.mdx+++ b/docs/astro/src/content/docs/zh-cn/assets/audio.mdx@@ -100,7 +100,7 @@ if (voice) {空间事件复用 AudioSource 的衰减和声像计算,owner 需有世界变换,或在 `trigger()` 传入位置。没有监听器时以原点为监听位置。小游戏宿主不支持立体声声像时会报告该限制,但仍应用软件距离衰减。-专用事件制作界面、组件和可视化脚本接入继续在 RM-066 中实施。+组件与图动作见[音效事件源](#音效事件源)。专用事件制作界面和连续试听继续在 RM-066 中实施。## `Audio` API 参考@@ -348,6 +348,37 @@ const gain = calculateAttenuation(250, {const pan = calculatePanning(600, 0, 0, 0, 1000); // 0.6 — to the right```+### 音效事件源++为实体添加 `SoundEventSource`,选择 `.esaudioevent` 资源。场景预加载只持有定义,+不会解码全部候选。`seed` 默认 `0`,固定此源的选择流;`playOnAwake` 在每个启用的+组件生命周期播放一次。修改事件或种子会建立新的选择流。++```typescript+import { SoundEventSource, triggerSoundEventSource, stopSoundEventSource } from 'esengine';++app.world.insert(entity, SoundEventSource, { event: 'assets/steps.esaudioevent', seed: 42 });+const voice = await triggerSoundEventSource(app.world, entity);+if (voice) {+ await voice.ready;+ console.log(voice.status, voice.reason, voice.selection);+}+stopSoundEventSource(app.world, entity);+```++可视化脚本、FSM 钩子和 BT 动作使用 `soundEvent.trigger` / `soundEvent.stop`,+与代码触发同一个组件。同一帧多次触发各自保留;图动作立即继续,不等待加载或播放完成。++冷定义按顺序最多保留每个源 256 次触发。超额、源不可用或禁用、定义加载失败、取消的请求+返回 `null`;返回的句柄再提供片段加载状态及事件/全局声音预算拒绝原因。冷却从定义加载+完成后的准入开始,因此多次冷触发可能共享同一个准入时刻。++停止仅取消此组件的队列和声音,不影响调用者在同一实体上创建的其他发射器。之后再触发+会从固定种子的起点开始。禁用、移除、修改事件或种子、层级失活、销毁、注册表断开都会+使旧生命周期失效;异步加载完成时再次检查,防止下一帧更新前出现迟到播放。+全局 `Audio.stopAll()` 取消待播意图并保留准备好的定义。局部停止不会在下一帧重新触发+`playOnAwake`。+## 最佳实践- 对在关键时刻要播放的片段**预加载**(`preload` / `preloadAll`),第一次播放就不会因解码而静音。diff --git a/docs/astro/src/data/apiStability.generated.json b/docs/astro/src/data/apiStability.generated.jsonindex e8ad9f64d..a9ed29009 100644--- a/docs/astro/src/data/apiStability.generated.json+++ b/docs/astro/src/data/apiStability.generated.json@@ -2,11 +2,11 @@"note": "Generated by tools/api-stability.mjs from sdk/etc/*.api.md — do not edit.","counts": {"public": 115,- "beta": 117,+ "beta": 121,"experimental": 2203,"deprecated": 3},- "total": 2435,+ "total": 2439,"subsystems": [{"id": "mobile-controls",@@ -2621,6 +2621,30 @@"minigame"]},+ {+ "name": "SoundEventSource",+ "kind": "const",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },+ {+ "name": "SoundEventSourceData",+ "kind": "interface",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },{"name": "SoundEventStats","kind": "interface",@@ -3166,6 +3190,18 @@"minigame"]},+ {+ "name": "stopSoundEventSource",+ "kind": "function",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]+ },{"name": "themeColors","kind": "function",@@ -3189,6 +3225,18 @@"wechat","minigame"]+ },+ {+ "name": "triggerSoundEventSource",+ "kind": "function",+ "deprecated": false,+ "entries": [+ "index",+ "index.node",+ "index.native",+ "wechat",+ "minigame"+ ]}]}diff --git a/docs/astro/src/data/componentDocs.ts b/docs/astro/src/data/componentDocs.tsindex 6bb91c241..7cbdf56a9 100644--- a/docs/astro/src/data/componentDocs.ts+++ b/docs/astro/src/data/componentDocs.ts@@ -178,6 +178,7 @@ export const COMPONENT_DOCS: Record<string, ComponentDoc> = {EventBinding: { category: 'gameplay', summary: 'Wires an event on this entity to named actions — gameplay authored in the inspector, with no script.', doc: 'scripting/events', anchor: 'the-data', anchorZh: '数据本身' },AudioSource: { category: 'gameplay', summary: 'Declarative playback attached to an entity, attenuated by distance when spatial.', doc: 'assets/audio', anchor: 'declarative-playback--audiosource', anchorZh: '声明式播放--audiosource' },AudioListener: { category: 'gameplay', summary: 'The ear spatial audio is mixed relative to — usually the camera or the player.', doc: 'assets/audio', anchor: 'spatial-audio', anchorZh: '空间音频' },+ SoundEventSource: { category: 'gameplay', summary: 'An entity-owned sound event with reproducible variation and shared voice limits.', doc: 'assets/audio', anchor: 'sound-event-source', anchorZh: '音效事件源' },Replicated: { category: 'gameplay', summary: 'Marks an entity the server replicates to every client.', doc: 'scripting/networking', anchor: 'state-replication--multiplayer-entities', anchorZh: '状态复制多人实体同步' },NetGhost: { category: 'gameplay', summary: 'Tag: this entity is a client-side proxy of one the server owns.', doc: 'scripting/networking', anchor: 'state-replication--multiplayer-entities', anchorZh: '状态复制多人实体同步' },};diff --git a/docs/astro/src/data/components.generated.json b/docs/astro/src/data/components.generated.jsonindex 603ca2e87..9f262dbdd 100644--- a/docs/astro/src/data/components.generated.json+++ b/docs/astro/src/data/components.generated.json@@ -4033,6 +4033,36 @@}]},+ {+ "name": "SoundEventSource",+ "source": "ts",+ "fields": [+ {+ "key": "event",+ "type": "Asset<sound-event>",+ "default": "none"+ },+ {+ "key": "seed",+ "type": "number",+ "default": "0",+ "doc": "Fixed 32-bit seed for this source selection stream."+ },+ {+ "key": "playOnAwake",+ "type": "boolean",+ "default": "false"+ },+ {+ "key": "enabled",+ "type": "boolean",+ "default": "true"+ }+ ],+ "animatable": [+ "seed"+ ]+ },{"name": "SphereCollider3D","source": "cpp",diff --git a/pipeline/src/assets/addressableManifest.ts b/pipeline/src/assets/addressableManifest.tsindex 0e38ee78d..f71befb42 100644--- a/pipeline/src/assets/addressableManifest.ts+++ b/pipeline/src/assets/addressableManifest.ts@@ -38,7 +38,7 @@ interface FlatManifest {const ADDRESSABLE_TYPE: Record<string, string> = {texture: 'texture', material: 'material', audio: 'audio', 'bitmap-font': 'bitmap-font',prefab: 'prefab', spine: 'spine',- scene: 'json', 'anim-clip': 'json', tilemap: 'json', timeline: 'json', json: 'json', shader: 'text',+ scene: 'json', 'anim-clip': 'json', tilemap: 'json', timeline: 'json', json: 'json', 'sound-event': 'json', shader: 'text',};export const addrType = (editorType: string): string => ADDRESSABLE_TYPE[editorType] ?? 'binary';diff --git a/pipeline/src/assets/assetDb.ts b/pipeline/src/assets/assetDb.tsindex c9a7e38ac..0caa7d5d6 100644--- a/pipeline/src/assets/assetDb.ts+++ b/pipeline/src/assets/assetDb.ts@@ -234,7 +234,7 @@ const JSON_REF_TYPES = new Set(['scene', 'prefab', 'material', 'tileset', 'tilemap', 'animclip', 'animation', 'statemachine', 'behaviortree','scriptgraph','environment', 'animatorcontroller', 'avatar',- 'json',+ 'json', 'sound-event',]);/**diff --git a/pipeline/tests/sound-event-deps.test.ts b/pipeline/tests/sound-event-deps.test.tsindex 2b921d08e..c7d249994 100644--- a/pipeline/tests/sound-event-deps.test.ts+++ b/pipeline/tests/sound-event-deps.test.ts@@ -1,10 +1,12 @@// SPDX-License-Identifier: Apache-2.0// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Teamimport { afterEach, expect, it } from 'vitest';-import { mkdtempSync, writeFileSync, renameSync, rmSync } from 'node:fs';+import { mkdtempSync, writeFileSync, renameSync, rmSync, readFileSync } from 'node:fs';import { tmpdir } from 'node:os';import path from 'node:path';import { scanAssetDatabase } from '../src/assets/assetDb';+import { cookAssets } from '../src/assets/cookAssets';+import { buildAddressableManifest } from '../src/assets/addressableManifest';const roots: string[] = [];afterEach(() => {@@ -14,7 +16,7 @@ afterEach(() => {}});-it('keeps every event candidate as a dependency, including disabled slots and moved UUID references', async () => {+it.each(['json', 'sound-event', 'orphan'])('keeps every candidate and moved UUID reference with %s metadata', async meta => {const root = mkdtempSync(path.join(tmpdir(), 'estella-sound-event-')); roots.push(root);const clips = ['11111111-1111-4111-8111-111111111111', '22222222-2222-4222-8222-222222222222'];const event = '33333333-3333-4333-8333-333333333333';@@ -23,12 +25,29 @@ it('keeps every event candidate as a dependency, including disabled slots and mowriteFileSync(path.join(root, `${i}.wav.meta`), JSON.stringify({ uuid: clips[i], version: '2.0', type: 'audio', importer: {} }));}writeFileSync(path.join(root, 'steps.esaudioevent'), JSON.stringify({ version: 1, clips: clips.map((uuid, i) => ({ clip: `@uuid:${uuid}`, weight: i })) }));- writeFileSync(path.join(root, 'steps.esaudioevent.meta'), JSON.stringify({ uuid: event, version: '2.0', type: 'json', importer: {} }));+ if (meta !== 'orphan') writeFileSync(path.join(root, 'steps.esaudioevent.meta'), JSON.stringify({ uuid: event, version: '2.0', type: meta, importer: {} }));const first = await scanAssetDatabase(root, { write: false });- expect(first.index.deps[event]).toEqual(clips);+ const registered = JSON.parse(readFileSync(path.join(root, 'steps.esaudioevent.meta'), 'utf8'));+ expect(registered.type).toBe(meta === 'json' ? 'json' : 'sound-event');+ expect(first.index.deps[registered.uuid]).toEqual(clips);renameSync(path.join(root, '0.wav'), path.join(root, 'renamed.wav'));renameSync(path.join(root, '0.wav.meta'), path.join(root, 'renamed.wav.meta'));+ const scene = '44444444-4444-4444-8444-444444444444';+ writeFileSync(path.join(root, 'main.esscene'), JSON.stringify({ version: '1.0', name: 'Sound source', entities: [+ { id: 1, name: 'Step', parent: null, children: [], components: [+ { type: 'SoundEventSource', data: { event: `@uuid:${registered.uuid}`, seed: 42 } },+ ] },+ ] }));+ writeFileSync(path.join(root, 'main.esscene.meta'), JSON.stringify({ uuid: scene, version: '2.0', type: 'scene', importer: {} }));const second = await scanAssetDatabase(root, { write: false });- expect(second.index.deps[event]).toEqual(clips);+ expect(second.index.deps[registered.uuid]).toEqual(clips);+ expect(second.index.deps[scene]).toEqual([registered.uuid]);expect(second.index.entries.find(entry => entry.uuid === clips[0])?.path).toBe('renamed.wav');+ const cooked = await cookAssets(root, { entryScenes: ['main.esscene'], outDir: 'build', contentAddressed: true });+ expect(cooked.failed).toEqual([]);+ expect(cooked.included.sort()).toEqual([scene, registered.uuid, ...clips].sort());+ expect(cooked.warnings.filter(warning => /does not carry/.test(warning))).toEqual([]);+ const manifest = JSON.parse(await buildAddressableManifest(cooked.outDir));+ const entries = Object.values(manifest.groups).flatMap(group => Object.entries((group as { assets: Record<string, unknown> }).assets));+ expect(entries.find(([uuid]) => uuid === registered.uuid)?.[1]).toMatchObject({ type: 'json' });});diff --git a/sdk/etc/index.api.md b/sdk/etc/index.api.mdindex 7d5195dd4..2f0872bd1 100644--- a/sdk/etc/index.api.md+++ b/sdk/etc/index.api.md@@ -1,7 +1,7 @@# API surface — esengine/index<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 105 beta · 1581 experimental · 3 deprecated+Symbols: 115 public · 109 beta · 1581 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -859,7 +859,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'sound-event' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -3387,7 +3387,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```@@ -8080,7 +8080,7 @@ stop: () => void@internal resetOwners: () => voiddispose: () => voidgetStats: () => SoundEventStats-load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+load: (ref: string, options?: { owner?: Entity; seed?: number; alive?: () => boolean; }) => Promise<SoundEventEmitter | null>stopAll: () => voidstopOwner: (owner: Entity) => voidupdate: (delta: number, listener?: Vec3, right?: Vec3) => void@@ -8115,6 +8115,19 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventSource — const @beta+```+ComponentDef<SoundEventSourceData>+```++## SoundEventSourceData — interface @beta+```+enabled: boolean+event: string+playOnAwake: boolean+seed: number+```+## SoundEventStats — interface @beta```active: number@@ -13223,6 +13236,11 @@ MotionDriver<AnimatorClipMotion>StatsPlugin```+## stopSoundEventSource — function @beta+```+(world: World, entity: Entity): void+```+## summarizeCapture — function @experimental```(capture: ProfileCapture): CaptureSummary@@ -13308,6 +13326,11 @@ TrailPlugin(source: AnimatorAvatar | null, target: AnimatorAvatar | null): number```+## triggerSoundEventSource — function @beta+```+(world: World, entity: Entity): Promise<SoundEventHandle | null>+```+## trimTextureCache — function @experimental```(): numberdiff --git a/sdk/etc/index.native.api.md b/sdk/etc/index.native.api.mdindex 8b64bb3df..6db8ed849 100644--- a/sdk/etc/index.native.api.md+++ b/sdk/etc/index.native.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.native<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 110 beta · 1600 experimental · 3 deprecated+Symbols: 115 public · 114 beta · 1600 experimental · 3 deprecated## ABI_LAYOUT_HASH — const @experimental```@@ -859,7 +859,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'sound-event' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -3395,7 +3395,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```@@ -8293,7 +8293,7 @@ stop: () => void@internal resetOwners: () => voiddispose: () => voidgetStats: () => SoundEventStats-load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+load: (ref: string, options?: { owner?: Entity; seed?: number; alive?: () => boolean; }) => Promise<SoundEventEmitter | null>stopAll: () => voidstopOwner: (owner: Entity) => voidupdate: (delta: number, listener?: Vec3, right?: Vec3) => void@@ -8328,6 +8328,19 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventSource — const @beta+```+ComponentDef<SoundEventSourceData>+```++## SoundEventSourceData — interface @beta+```+enabled: boolean+event: string+playOnAwake: boolean+seed: number+```+## SoundEventStats — interface @beta```active: number@@ -13486,6 +13499,11 @@ MotionDriver<AnimatorClipMotion>StatsPlugin```+## stopSoundEventSource — function @beta+```+(world: World, entity: Entity): void+```+## summarizeCapture — function @experimental```(capture: ProfileCapture): CaptureSummary@@ -13571,6 +13589,11 @@ TrailPlugin(source: AnimatorAvatar | null, target: AnimatorAvatar | null): number```+## triggerSoundEventSource — function @beta+```+(world: World, entity: Entity): Promise<SoundEventHandle | null>+```+## trimTextureCache — function @experimental```(): numberdiff --git a/sdk/etc/index.node.api.md b/sdk/etc/index.node.api.mdindex cedde2085..073c8c3d6 100644--- a/sdk/etc/index.node.api.md+++ b/sdk/etc/index.node.api.md@@ -1,7 +1,7 @@# API surface — esengine/index.node<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 107 beta · 1580 experimental · 3 deprecated+Symbols: 115 public · 111 beta · 1580 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -854,7 +854,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'sound-event' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -3382,7 +3382,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```@@ -8075,7 +8075,7 @@ stop: () => void@internal resetOwners: () => voiddispose: () => voidgetStats: () => SoundEventStats-load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+load: (ref: string, options?: { owner?: Entity; seed?: number; alive?: () => boolean; }) => Promise<SoundEventEmitter | null>stopAll: () => voidstopOwner: (owner: Entity) => voidupdate: (delta: number, listener?: Vec3, right?: Vec3) => void@@ -8110,6 +8110,19 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventSource — const @beta+```+ComponentDef<SoundEventSourceData>+```++## SoundEventSourceData — interface @beta+```+enabled: boolean+event: string+playOnAwake: boolean+seed: number+```+## SoundEventStats — interface @beta```active: number@@ -13228,6 +13241,11 @@ MotionDriver<AnimatorClipMotion>StatsPlugin```+## stopSoundEventSource — function @beta+```+(world: World, entity: Entity): void+```+## summarizeCapture — function @experimental```(capture: ProfileCapture): CaptureSummary@@ -13313,6 +13331,11 @@ TrailPlugin(source: AnimatorAvatar | null, target: AnimatorAvatar | null): number```+## triggerSoundEventSource — function @beta+```+(world: World, entity: Entity): Promise<SoundEventHandle | null>+```+## trimTextureCache — function @experimental```(): numberdiff --git a/sdk/etc/logic.api.md b/sdk/etc/logic.api.mdindex 8721e6d93..ad018c750 100644--- a/sdk/etc/logic.api.md+++ b/sdk/etc/logic.api.md@@ -143,7 +143,7 @@ static prototype: ScriptGraphs## ScriptNodeShape — interface @experimental```-entry: "start" | "event" | "update" | "destroy" | undefined+entry: "event" | "start" | "update" | "destroy" | undefinedexecIn: booleanexecOut: readonly string[]inputs: readonly ScriptPort[]diff --git a/sdk/etc/minigame.api.md b/sdk/etc/minigame.api.mdindex 8baf03317..7d4a0b808 100644--- a/sdk/etc/minigame.api.md+++ b/sdk/etc/minigame.api.md@@ -1,7 +1,7 @@# API surface — esengine/minigame<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 105 beta · 1602 experimental · 3 deprecated+Symbols: 115 public · 109 beta · 1602 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -854,7 +854,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'sound-event' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -3382,7 +3382,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```@@ -8368,7 +8368,7 @@ stop: () => void@internal resetOwners: () => voiddispose: () => voidgetStats: () => SoundEventStats-load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+load: (ref: string, options?: { owner?: Entity; seed?: number; alive?: () => boolean; }) => Promise<SoundEventEmitter | null>stopAll: () => voidstopOwner: (owner: Entity) => voidupdate: (delta: number, listener?: Vec3, right?: Vec3) => void@@ -8403,6 +8403,19 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventSource — const @beta+```+ComponentDef<SoundEventSourceData>+```++## SoundEventSourceData — interface @beta+```+enabled: boolean+event: string+playOnAwake: boolean+seed: number+```+## SoundEventStats — interface @beta```active: number@@ -13532,6 +13545,11 @@ MotionDriver<AnimatorClipMotion>StatsPlugin```+## stopSoundEventSource — function @beta+```+(world: World, entity: Entity): void+```+## summarizeCapture — function @experimental```(capture: ProfileCapture): CaptureSummary@@ -13617,6 +13635,11 @@ TrailPlugin(source: AnimatorAvatar | null, target: AnimatorAvatar | null): number```+## triggerSoundEventSource — function @beta+```+(world: World, entity: Entity): Promise<SoundEventHandle | null>+```+## trimTextureCache — function @experimental```(): numberdiff --git a/sdk/etc/wechat.api.md b/sdk/etc/wechat.api.mdindex 5f7008e10..d90773976 100644--- a/sdk/etc/wechat.api.md+++ b/sdk/etc/wechat.api.md@@ -1,7 +1,7 @@# API surface — esengine/wechat<!-- Generated by tools/api-surface.mjs — do not edit. Run --update to accept changes. -->-Symbols: 115 public · 105 beta · 1593 experimental · 3 deprecated+Symbols: 115 public · 109 beta · 1593 experimental · 3 deprecated## ANCHOR_AXES — const @experimental```@@ -854,7 +854,7 @@ type: AssetFieldType## AssetFieldType — type @public```-'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'+'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'sound-event' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume'```## AssetGroupDef — interface @experimental@@ -3382,7 +3382,7 @@ Step = 15```| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown'```@@ -8082,7 +8082,7 @@ stop: () => void@internal resetOwners: () => voiddispose: () => voidgetStats: () => SoundEventStats-load: (ref: string, options?: { owner?: Entity; seed?: number; }) => Promise<SoundEventEmitter | null>+load: (ref: string, options?: { owner?: Entity; seed?: number; alive?: () => boolean; }) => Promise<SoundEventEmitter | null>stopAll: () => voidstopOwner: (owner: Entity) => voidupdate: (delta: number, listener?: Vec3, right?: Vec3) => void@@ -8117,6 +8117,19 @@ static new (asset: SoundEventAsset, seed?: number): SoundEventSelectorstatic prototype: SoundEventSelector```+## SoundEventSource — const @beta+```+ComponentDef<SoundEventSourceData>+```++## SoundEventSourceData — interface @beta+```+enabled: boolean+event: string+playOnAwake: boolean+seed: number+```+## SoundEventStats — interface @beta```active: number@@ -13259,6 +13272,11 @@ MotionDriver<AnimatorClipMotion>StatsPlugin```+## stopSoundEventSource — function @beta+```+(world: World, entity: Entity): void+```+## summarizeCapture — function @experimental```(capture: ProfileCapture): CaptureSummary@@ -13344,6 +13362,11 @@ TrailPlugin(source: AnimatorAvatar | null, target: AnimatorAvatar | null): number```+## triggerSoundEventSource — function @beta+```+(world: World, entity: Entity): Promise<SoundEventHandle | null>+```+## trimTextureCache — function @experimental```(): numberdiff --git a/sdk/src/ai/builtins.ts b/sdk/src/ai/builtins.tsindex 0fc18d58b..4ef6efe1e 100644--- a/sdk/src/ai/builtins.ts+++ b/sdk/src/ai/builtins.ts@@ -10,14 +10,15 @@* of game action names; a name already present in the registry is never* overwritten, so game code wins regardless of registration order. Everything* here speaks through components — the same channel game code and the editor- * use — never through resources.+ * use. Event-source verbs dispatch intents through their component adapter.*/import { aiRegistry, type AiContext } from './fsm/AiContext';import type { AiAction, AiActionInput, AiCondition, AiParamDef, AiParamValue, AiTouches } from './fsm/registry';import { TimelinePlayer } from '../timeline/TimelinePlayerComponent';import { SpriteAnimator } from '../animation/SpriteAnimator';-import { AudioSource } from '../audio/AudioComponents';+import { AudioSource, SoundEventSource } from '../audio/AudioComponents';+import { triggerSoundEventSource, stopSoundEventSource } from '../audio/SoundEventSource';import { setEntityProperty } from '../ecs/propertyPath';import type { AnyComponentDef, ComponentData } from '../ecs/component';import type { Entity } from '../types';@@ -25,6 +26,7 @@ import type { Entity } from '../types';const TIMELINE: AiTouches = { reads: [TimelinePlayer._name], writes: [TimelinePlayer._name] };const SPRITE_ANIM: AiTouches = { reads: [SpriteAnimator._name], writes: [SpriteAnimator._name] };const AUDIO: AiTouches = { reads: [AudioSource._name], writes: [AudioSource._name] };+const SOUND_EVENT: AiTouches = { reads: [SoundEventSource._name] };/** The one parameter the play verbs take: which clip, empty for the current one. */const CLIP_PARAM: readonly AiParamDef[] = [{ name: 'clip', type: 'string', tooltip: 'Leave empty to replay the current one' }];@@ -134,6 +136,9 @@ export function ensureBuiltinAiRegistrations(): void {ctx.set(AudioSource, source);}, AUDIO);+ action('soundEvent.trigger', ctx => { void triggerSoundEventSource(ctx.world, ctx.entity); }, SOUND_EVENT);+ action('soundEvent.stop', ctx => { stopSoundEventSource(ctx.world, ctx.entity); }, SOUND_EVENT);+// Latched only when a non-looping clip ends — the same shape as// `timeline.finished`, so `onEnter: audio.play` plus an `audio.finished`// transition is a state that lasts exactly as long as its sound.diff --git a/sdk/src/asset/Assets.ts b/sdk/src/asset/Assets.tsindex 75d9e20f2..ef648284d 100644--- a/sdk/src/asset/Assets.ts+++ b/sdk/src/asset/Assets.ts@@ -1559,6 +1559,7 @@ export class Assets {// types) would strip the alias and leave play-realm lookups keyless.const animClipPaths = discovered.rawByType.get('anim-clip') ?? new Set<string>();const audioPaths = discovered.byType.get('audio') ?? new Set<string>();+ const soundEventPaths = discovered.byType.get('sound-event') ?? new Set<string>();const tilemapPaths = discovered.byType.get('tilemap') ?? new Set<string>();const tilesetPaths = discovered.byType.get('tileset') ?? new Set<string>();const timelinePaths = discovered.byType.get('timeline') ?? new Set<string>();@@ -1686,6 +1687,7 @@ export class Assets {pushAcquire(tilesetPaths, p => this.acquireTypedLease_('tileset', p), 'tileset');pushAcquire(timelinePaths, p => this.acquireTypedLease_('timeline', p), 'timeline');pushAcquire(audioPaths, p => this.acquireTypedLease_('audio', p), 'audio');+ pushAcquire(soundEventPaths, p => this.acquireTypedLease_('sound-event', p), 'sound-event');// FSM/BT loaders register the parsed definition into the shared AI store// under the asset path, so a StateMachineAgent/BehaviorTreeAgent whose// fsm/bt is that path resolves once the scene finishes preloading.diff --git a/sdk/src/assetTypes.ts b/sdk/src/assetTypes.tsindex b528920d9..67fa7c143 100644--- a/sdk/src/assetTypes.ts+++ b/sdk/src/assetTypes.ts@@ -9,7 +9,7 @@ export type AddressableAssetType =export type EditorAssetType =| 'texture' | 'material' | 'shader' | 'spine-atlas' | 'spine-skeleton'| 'dragonbones-atlas' | 'dragonbones-skeleton'- | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'video' | 'scene' | 'anim-clip'+ | 'bitmap-font' | 'font' | 'prefab' | 'json' | 'audio' | 'sound-event' | 'video' | 'scene' | 'anim-clip'| 'tilemap' | 'tileset' | 'timeline' | 'mesh'| 'unknown';@@ -77,7 +77,7 @@ const ASSET_TYPE_REGISTRY: readonly AssetTypeEntry[] = [// @uuid (transitive dep).{ extensions: ['estileset'], contentType: 'json', editorType: 'tileset', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },{ extensions: ['estimeline'], contentType: 'json', editorType: 'timeline', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },- { extensions: ['esaudioevent'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },+ { extensions: ['esaudioevent'], contentType: 'json', editorType: 'sound-event', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: true },// Locale string table (LocaleAssetLoader → Localization.addCatalog) — one locale per file.{ extensions: ['eslocale'], contentType: 'json', editorType: 'json', addressableType: 'json', wechatPackInclude: true, hasTransitiveDeps: false },// State machine (registerFsm / FsmAssetLoader) — data-driven FSM definition.diff --git a/sdk/src/audio/AudioComponents.ts b/sdk/src/audio/AudioComponents.tsindex 154839723..c116ef872 100644--- a/sdk/src/audio/AudioComponents.ts+++ b/sdk/src/audio/AudioComponents.ts@@ -58,6 +58,22 @@ export interface AudioListenerData {enabled: boolean;}+/** An entity-owned event definition; all voices share the Audio voice budget. @beta */+export interface SoundEventSourceData {+ event: string;+ seed: number;+ playOnAwake: boolean;+ enabled: boolean;+}++/** Trigger with triggerSoundEventSource or the soundEvent.trigger graph action. @beta */+export const SoundEventSource = defineComponent<SoundEventSourceData>('SoundEventSource', {+ event: '', seed: 0, playOnAwake: false, enabled: true,+}, {+ assetFields: [{ field: 'event', type: 'sound-event' }],+ fields: { seed: { tooltip: 'Fixed 32-bit seed for this source selection stream.' } },+});+export const AudioListener = defineComponent<AudioListenerData>('AudioListener', {enabled: true,});diff --git a/sdk/src/audio/AudioPlugin.ts b/sdk/src/audio/AudioPlugin.tsindex b300a95c4..7de54f1af 100644--- a/sdk/src/audio/AudioPlugin.ts+++ b/sdk/src/audio/AudioPlugin.ts@@ -16,6 +16,7 @@ import { log } from '../util/logger';import { Assets } from '../asset/AssetPlugin';import { SoundEvents, SoundEventPlayback } from './SoundEventPlayback';import { disposeAll } from '../util/disposeAll';+import { SoundEventSourceController } from './SoundEventSource';/*** Where a transform IS, which for a parented entity is not where it says it is:@@ -47,6 +48,7 @@ interface AudioPluginState {playedEntities: Set<number>;audio: AudioAPI;events: SoundEventPlayback;+ eventSources: SoundEventSourceController;offCoreDisconnect: () => void;released: boolean;offMemoryWarning: () => void;@@ -89,7 +91,10 @@ export class AudioPlugin implements Plugin {owner => app.world.valid(owner) && (app.world.getCppRegistry()?.valid(owner) ?? true),owner => app.world.has(owner, WorldTransform) ? worldPositionOf(app.world.get(owner, WorldTransform)) : null);app.insertResource(SoundEvents, events);- const offCoreDisconnect = app.world.onCoreDisconnect(() => events.resetOwners());+ const eventSources = new SoundEventSourceController(app.world, events, audio);+ const offCoreDisconnect = app.world.onCoreDisconnect(() => {+ disposeAll([() => eventSources.reset(), () => events.resetOwners()], action => action());+ });const muteOwner = {};const offAudioMute = (isPlatformInitialized()? getPlatform().onAudioMute?.(muted => setAudioHostSuspended(audio, muteOwner, muted))@@ -116,9 +121,9 @@ export class AudioPlugin implements Plugin {const offDespawn = app.world.onDespawn((entity: Entity) => {const voice = activeSourceHandles.get(entity);activeSourceHandles.delete(entity); playedEntities.delete(entity);- disposeAll([() => events.stopOwner(entity), () => voice?.handle.stop()], action => action());+ disposeAll([() => eventSources.remove(entity), () => events.stopOwner(entity), () => voice?.handle.stop()], action => action());});- const state = { activeSourceHandles, playedEntities, audio, events, offCoreDisconnect, offMemoryWarning, offAudioMute, offExecution, offDespawn, released: false };+ const state = { activeSourceHandles, playedEntities, audio, events, eventSources, offCoreDisconnect, offMemoryWarning, offAudioMute, offExecution, offDespawn, released: false };this.states_.set(app, state);this.latestState_ = state;const stopVoice = (id: number): void => {@@ -143,6 +148,7 @@ export class AudioPlugin implements Plugin {const playMode = !isEditor() || isPlayMode();if (!playMode) {+ eventSources.reset();if (wasPlayMode) {spatialListenerWarned = false;wasPlayMode = false;@@ -175,6 +181,7 @@ export class AudioPlugin implements Plugin {}}events.update(time.delta, listenerAt, listenerRight);+ eventSources.update();const sources = world.getEntitiesWithComponents([AudioSource]);liveEntities.clear();@@ -342,7 +349,7 @@ export class AudioPlugin implements Plugin {if (app) this.states_.delete(app);if (state === this.latestState_) this.latestState_ = null;disposeAll([state.offAudioMute, state.offExecution, state.offMemoryWarning, state.offDespawn, state.offCoreDisconnect,- () => state.events.dispose(), () => this.stopSources_(state), () => state.audio.dispose()], action => action());+ () => state.eventSources.dispose(), () => state.events.dispose(), () => this.stopSources_(state), () => state.audio.dispose()], action => action());}}diff --git a/sdk/src/audio/SoundEventPlayback.ts b/sdk/src/audio/SoundEventPlayback.tsindex 3b80e2986..dd3ea7111 100644--- a/sdk/src/audio/SoundEventPlayback.ts+++ b/sdk/src/audio/SoundEventPlayback.ts@@ -53,6 +53,7 @@ interface SharedEvent { key: string; references: number; nextAllowed: number; acinterface Emitter {ref: string; owner?: Entity; disposed: boolean; shared: SharedEvent; asset: SoundEventAsset;selector: SoundEventSelector; lease: AssetLease<SoundEventAsset>; resources: Resources; requests: Set<Request>;+ alive?: () => boolean;}interface Request {emitter: Emitter; generation: number; status: SoundEventStatus; reason: SoundEventRejection | null; error: string | null;@@ -94,9 +95,10 @@ export class SoundEventPlayback {});}- /** Loading a definition is preparation, not a play intent; Audio.stopAll does not unload emitters. */- async load(ref: string, options: { owner?: Entity; seed?: number } = {}): Promise<SoundEventEmitter | null> {- if (this.disposed || (options.owner !== undefined && !this.ownerAlive(options.owner))) return null;+ /** Loading a definition is preparation, not a play intent; Audio.stopAll does not unload emitters.+ * `alive` is a pure lifetime predicate checked after asynchronous loads and on updates/triggers. */+ async load(ref: string, options: { owner?: Entity; seed?: number; alive?: () => boolean } = {}): Promise<SoundEventEmitter | null> {+ if (this.disposed || options.alive?.() === false || (options.owner !== undefined && !this.ownerAlive(options.owner))) return null;const resources = this.resources();if (!resources) throw new Error(`${ref}: no Assets resource for sound events`);const pending: PendingDefinition = { owner: options.owner, cancelled: false };@@ -105,20 +107,20 @@ export class SoundEventPlayback {let lease: AssetLease<SoundEventAsset> | undefined;try {lease = await resources.acquireTyped<SoundEventAsset>('sound-event', ref);- if (this.disposed || pending.cancelled || resources !== this.resources()+ if (this.disposed || pending.cancelled || options.alive?.() === false || resources !== this.resources()|| (pending.owner !== undefined && !this.ownerAlive(pending.owner))) { lease.release(); return null; }const asset = parseSoundEvent(lease.value);const selector = new SoundEventSelector(asset, options.seed ?? (Math.random() * 4294967296) >>> 0);let shared = this.events.get(lease.key);if (!shared) { shared = { key: lease.key, references: 0, nextAllowed: 0, active: new Set(), running: new Set() }; this.events.set(lease.key, shared); }- const emitter: Emitter = { ref, owner: options.owner, disposed: false, shared, asset, selector, lease, resources, requests: new Set() };+ const emitter: Emitter = { ref, owner: options.owner, alive: options.alive, disposed: false, shared, asset, selector, lease, resources, requests: new Set() };shared.references++; this.emitters.add(emitter);if (emitter.owner !== undefined) this.addOwner(this.owners, emitter.owner, emitter);return { ref, get disposed() { return emitter.disposed; }, trigger: position => this.trigger(emitter, position),dispose: () => this.releaseEmitter(emitter) };} catch (error) {lease?.release();- if (this.disposed || pending.cancelled || resources !== this.resources()+ if (this.disposed || pending.cancelled || options.alive?.() === false || resources !== this.resources()|| (pending.owner !== undefined && !this.ownerAlive(pending.owner))) return null;throw error;} finally {@@ -135,7 +137,7 @@ export class SoundEventPlayback {if (right) this.right = { ...right };for (const emitter of [...this.emitters]) {if (emitter.resources !== this.resources()) { this.releaseEmitter(emitter); continue; }- if (emitter.owner !== undefined && !this.ownerAlive(emitter.owner)) { this.releaseEmitter(emitter); continue; }+ if (!this.alive(emitter)) { this.releaseEmitter(emitter); continue; }for (const request of [...emitter.requests]) { this.refresh(request); this.applySpatial(request); }}}@@ -241,7 +243,7 @@ export class SoundEventPlayback {};const refresh = () => this.refresh(request);if (this.disposed || emitter.disposed || emitter.resources !== this.resources()) this.reject(request, 'disposed');- else if (emitter.owner !== undefined && !this.ownerAlive(emitter.owner)) this.reject(request, 'owner-gone');+ else if (!this.alive(emitter)) this.reject(request, 'owner-gone');else if (emitter.asset.spatial && !this.position(request)) this.reject(request, 'missing-position');else {// Pending requests already own counted slots; only started voices can have retired externally.@@ -262,6 +264,10 @@ export class SoundEventPlayback {return handle;}+ private alive(emitter: Emitter): boolean {+ return emitter.alive?.() !== false && (emitter.owner === undefined || this.ownerAlive(emitter.owner));+ }+private position(request: Request): Vec3 | null {const position = request.position ?? (request.emitter.owner !== undefined ? this.ownerPosition(request.emitter.owner) : null);return position && Number.isFinite(position.x) && Number.isFinite(position.y) && Number.isFinite(position.z) ? position : null;@@ -284,7 +290,7 @@ export class SoundEventPlayback {if (!this.live(request)) { lease.release(); return; }request.lease = lease;if (this.disposed || emitter.disposed || emitter.resources !== this.resources()) { this.finish(request, 'stopped', false); return; }- if (emitter.owner !== undefined && !this.ownerAlive(emitter.owner)) { this.reject(request, 'owner-gone'); return; }+ if (!this.alive(emitter)) { this.reject(request, 'owner-gone'); return; }if (emitter.asset.spatial && !this.position(request)) { this.reject(request, 'missing-position'); return; }const buffer = this.audio.getBufferHandle(lease.value.bufferId);if (!buffer) throw new Error('selected audio buffer is unavailable');diff --git a/sdk/src/audio/SoundEventSource.ts b/sdk/src/audio/SoundEventSource.tsnew file mode 100644index 000000000..aed6ac29a--- /dev/null+++ b/sdk/src/audio/SoundEventSource.ts@@ -0,0 +1,164 @@+// SPDX-License-Identifier: Apache-2.0+// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team+import type { World } from '../ecs/world';+import type { Entity } from '../types';+import { SoundEventSource } from './AudioComponents';+import type { SoundEventEmitter, SoundEventHandle, SoundEventPlayback } from './SoundEventPlayback';+import type { AudioAPI } from './Audio';+import { isEditor, isPlayMode } from '../ecs/env';+import { disposeAll } from '../util/disposeAll';+import { log } from '../util/logger';++const controllers = new WeakMap<World, SoundEventSourceController>();+const MAX_PENDING = 256;+interface Intent { generation: number; resolve: (handle: SoundEventHandle | null) => void }+interface Source {+ entity: Entity; event: string; seed: number; incarnation: number; awake: boolean;+ emitter: SoundEventEmitter | null; loading: boolean; epoch: number; pending: Intent[];+}++/** Play one source intent, independently of other triggers in the same frame.+ * While the definition loads, at most 256 intents per source wait in FIFO order.+ * Returns null when unavailable, cancelled, overflowing, or the definition fails;+ * otherwise the handle exposes event/global admission and clip-load results.+ * @beta */+export function triggerSoundEventSource(world: World, entity: Entity): Promise<SoundEventHandle | null> {+ return controllers.get(world)?.trigger(entity) ?? Promise.resolve(null);+}++/** Cancel this component's queued intents and voices, preserving other emitters on the entity. @beta */+export function stopSoundEventSource(world: World, entity: Entity): void {+ controllers.get(world)?.stop(entity);+}++/** @internal Per-world component adapter; playback, selection and budgets remain in SoundEvents. */+export class SoundEventSourceController {+ private readonly sources = new Map<Entity, Source>();+ private readonly offStop: () => void;+ private disposed = false;++ constructor(private readonly world: World, private readonly playback: SoundEventPlayback, private readonly audio: AudioAPI) {+ controllers.get(world)?.dispose();+ world.enableIncarnationTracking(SoundEventSource);+ controllers.set(world, this);+ this.offStop = audio.onPlaybackStop(generation => {+ for (const source of this.sources.values()) this.cancelPending(source, generation);+ });+ }++ trigger(entity: Entity): Promise<SoundEventHandle | null> {+ const source = this.source(entity);+ if (!source) return Promise.resolve(null);+ source.awake = true;+ if (source.emitter && !source.emitter.disposed) return Promise.resolve(source.emitter.trigger());+ if (source.pending.length >= MAX_PENDING) return Promise.resolve(null);+ const result = new Promise<SoundEventHandle | null>(resolve => source.pending.push({ generation: this.audio.playbackGeneration, resolve }));+ this.prepare(source);+ return result;+ }++ update(): void {+ if (this.disposed) return;+ for (const source of this.sources.values()) if (!this.current(source)) this.remove(source.entity);+ for (const entity of this.world.getEntitiesWithComponents([SoundEventSource])) {+ const data = this.world.get(entity, SoundEventSource);+ if (!data.playOnAwake) continue;+ const source = this.source(entity);+ if (source && !source.awake) { source.awake = true; void this.trigger(entity); }+ }+ }++ stop(entity: Entity): void {+ const source = this.source(entity);+ if (!source) return;+ source.awake = true;+ this.cancelPending(source);+ source.epoch++; source.loading = false;+ const emitter = source.emitter; source.emitter = null;+ emitter?.dispose();+ }++ remove(entity: Entity): void {+ const source = this.sources.get(entity);+ if (!source) return;+ this.sources.delete(entity);+ this.cancelPending(source);+ source.epoch++;+ const emitter = source.emitter; source.emitter = null;+ emitter?.dispose();+ }++ reset(): void {+ if (this.sources.size) disposeAll([...this.sources.keys()], entity => this.remove(entity));+ }++ dispose(): void {+ if (this.disposed) return;+ this.disposed = true;+ if (controllers.get(this.world) === this) controllers.delete(this.world);+ this.offStop(); this.reset();+ }++ private enabled(entity: Entity): boolean {+ return !this.disposed && (!isEditor() || isPlayMode()) && this.world.isEntityActive(entity)+ && this.world.has(entity, SoundEventSource) && this.world.get(entity, SoundEventSource).enabled;+ }++ private current(source: Source): boolean {+ if (this.sources.get(source.entity) !== source || !this.enabled(source.entity)) return false;+ const data = this.world.get(source.entity, SoundEventSource);+ return data.event === source.event && data.seed === source.seed+ && this.world.getComponentIncarnation(source.entity, SoundEventSource) === source.incarnation;+ }++ private source(entity: Entity): Source | null {+ let source = this.sources.get(entity);+ if (source && !this.current(source)) { this.remove(entity); source = undefined; }+ if (!this.enabled(entity)) return null;+ const data = this.world.get(entity, SoundEventSource);+ if (!data.event) return null;+ if (!source) {+ source = { entity, event: data.event, seed: data.seed,+ incarnation: this.world.getComponentIncarnation(entity, SoundEventSource), awake: false,+ emitter: null, loading: false, epoch: 0, pending: [] };+ this.sources.set(entity, source);+ }+ return source;+ }++ private cancelPending(source: Source, beforeGeneration = Infinity): void {+ const pending = source.pending; source.pending = [];+ for (const intent of pending) {+ if (intent.generation < beforeGeneration) intent.resolve(null);+ else source.pending.push(intent);+ }+ }++ private prepare(source: Source): void {+ if (source.loading) return;+ source.loading = true;+ const epoch = source.epoch;+ const alive = () => epoch === source.epoch && this.current(source);+ void this.playback.load(source.event, { owner: source.entity, seed: source.seed, alive }).then(emitter => {+ if (!alive()) {+ emitter?.dispose();+ if (epoch === source.epoch && this.sources.get(source.entity) === source) this.remove(source.entity);+ return;+ }+ source.loading = false; source.emitter = emitter;+ const pending = source.pending; source.pending = [];+ try {+ for (const intent of pending) {+ intent.resolve(intent.generation === this.audio.playbackGeneration && alive() && emitter ? emitter.trigger() : null);+ }+ } finally {+ // A throwing host callback must not leave the remaining callers unresolved.+ for (const intent of pending) intent.resolve(null);+ }+ }).catch(error => {+ if (!alive()) return;+ source.loading = false; this.cancelPending(source);+ log.warn('audio', `SoundEventSource ${source.entity}: ${source.event}`, error);+ });+ }+}diff --git a/sdk/src/audio/index.ts b/sdk/src/audio/index.tsindex 78f3ee9a9..717b9331b 100644--- a/sdk/src/audio/index.ts+++ b/sdk/src/audio/index.ts@@ -18,7 +18,8 @@ export {} from './AudioProjectConfig';export { AudioPool, type PooledAudioNode } from './AudioPool';export { AudioPlugin, audioPlugin, type AudioPluginConfig } from './AudioPlugin';-export { AudioSource, AudioListener, type AudioSourceData, type AudioListenerData } from './AudioComponents';+export { AudioSource, AudioListener, SoundEventSource, type AudioSourceData, type AudioListenerData, type SoundEventSourceData } from './AudioComponents';+export { triggerSoundEventSource, stopSoundEventSource } from './SoundEventSource';export { AttenuationModel, calculateAttenuation, calculatePanning, spatialDistance, type SpatialAudioConfig } from './SpatialAudio';export { WebAudioBackend } from './WebAudioBackend';export { MiniGameAudioBackend } from './MiniGameAudioBackend';diff --git a/sdk/src/core-content.ts b/sdk/src/core-content.tsindex 935095c83..2a73cdf63 100644--- a/sdk/src/core-content.ts+++ b/sdk/src/core-content.ts@@ -651,6 +651,10 @@ export {AudioPlugin,audioPlugin,AudioSource,+ SoundEventSource,+ triggerSoundEventSource,+ stopSoundEventSource,+ type SoundEventSourceData,AudioListener,AudioBus,AudioMixer,diff --git a/sdk/src/scene/scene.ts b/sdk/src/scene/scene.tsindex f1acbf7c7..7727d0277 100644--- a/sdk/src/scene/scene.ts+++ b/sdk/src/scene/scene.ts@@ -152,7 +152,7 @@ export class MissingAssetsError extends Error {** @public*/-export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume';+export type AssetFieldType = 'texture' | 'material' | 'font' | 'anim-clip' | 'audio' | 'sound-event' | 'video' | 'tilemap' | 'tileset' | 'timeline' | 'statemachine' | 'behaviortree' | 'scriptgraph' | 'animatorcontroller' | 'avatar' | 'mesh' | 'environment' | 'probeVolume';// =============================================================================// Component Query Helpers (read from self-describing ComponentDef)diff --git a/sdk/tests/audio-plugin-lifecycle.test.ts b/sdk/tests/audio-plugin-lifecycle.test.tsindex d2c7b453e..35ec804d7 100644--- a/sdk/tests/audio-plugin-lifecycle.test.ts+++ b/sdk/tests/audio-plugin-lifecycle.test.ts@@ -28,12 +28,28 @@ vi.mock('../src/platform/base', async original => ({const { App } = await import('../src/app/app');const { AudioPlugin } = await import('../src/audio/AudioPlugin');const { Audio } = await import('../src/audio/Audio');-const { AudioSource } = await import('../src/audio/AudioComponents');+const { AudioSource, SoundEventSource } = await import('../src/audio/AudioComponents');+const { triggerSoundEventSource } = await import('../src/audio/SoundEventSource');const { SoundEvents } = await import('../src/audio/SoundEventPlayback');const { Assets } = await import('../src/asset/AssetPlugin');const { parseSoundEvent } = await import('../src/audio/SoundEvent');const apps: ReturnType<typeof App.new>[] = [];function build(plugin: InstanceType<typeof AudioPlugin>) { const app=App.new(); apps.push(app); app.addPlugin(plugin); return app; }++it('drives awake event sources and cancels queued definitions on disconnect and cleanup', async () => {+ const app = build(new AudioPlugin()), owner = app.world.spawn(), release = vi.fn();+ const lease = { key: 'steps', generation: 1, value: parseSoundEvent({ version: 1, clips: [] }), release, retain: () => null };+ let resolve!: (value: typeof lease) => void;+ const acquire = vi.fn().mockResolvedValueOnce(lease).mockImplementationOnce(() => new Promise(done => { resolve = done; }));+ app.insertResource(Assets, { acquireTyped: acquire } as unknown as import('../src/asset/Assets').Assets);+ app.world.insert(owner, SoundEventSource, { event: 'steps.esaudioevent', playOnAwake: true });+ await app.tick(1 / 60); await app.tick(1 / 60);+ expect(acquire).toHaveBeenCalledOnce(); expect(app.getResource(SoundEvents).getStats().rejected).toBe(1);+ app.world.disconnectCpp(); expect(release).toHaveBeenCalledOnce();+ const pending = triggerSoundEventSource(app.world, owner); app.quit();+ expect(await pending).toBeNull(); resolve(lease); await new Promise(done => setTimeout(done, 0));+ expect(release).toHaveBeenCalledTimes(2); expect(await triggerSoundEventSource(app.world, owner)).toBeNull();+});afterEach(() => { for(const app of apps.splice(0)) app.quit(); backends.length=0; listeners.clear(); muteListeners.clear(); hostMuted=false; });it('host mute overrides game resume and preserves explicit suspension after host unmute', () => {hostMuted = true;diff --git a/sdk/tests/sound-event-loader.test.ts b/sdk/tests/sound-event-loader.test.tsindex b91424313..c069e7591 100644--- a/sdk/tests/sound-event-loader.test.ts+++ b/sdk/tests/sound-event-loader.test.ts@@ -7,12 +7,28 @@ import type { LoadContext } from '../src/asset/AssetLoader';import { Assets } from '../src/asset/Assets';import { getAssetTypeEntry, getCustomExtensions } from '../src/assetTypes';import { SoundEventSelector, type SoundEventAsset } from '../src/audio/SoundEvent';+import { SoundEventSource } from '../src/audio/AudioComponents';+import type { SceneData } from '../src/scene/scene';const document = { version: 1, mode: 'sequence', clips: [{ clip: 'a.wav' }, { clip: 'b.wav' }] };const makeContext = (text: string) => ({ catalog: { getBuildPath: () => 'cooked/hash.esaudioevent' },loadText: vi.fn(async () => text), acquireAsset: vi.fn(), getAudio: vi.fn() }) as unknown as LoadContext;describe('sound event asset loading', () => {+ it('preloads a component definition through scene scope without decoding its candidates', async () => {+ expect(SoundEventSource.assetFields).toEqual([{ field: 'event', type: 'sound-event' }]);+ const fetchText = vi.fn(async () => JSON.stringify(document)), fetchBinary = vi.fn();+ const assets = Assets.create({ module: null, backend: { fetchText, fetchBinary,+ resolveUrl: (path: string) => path } as unknown as import('../src/asset/Backend').Backend });+ const scene: SceneData = { version: '1.0', name: 'sound events', entities: [{ id: 1, name: 'Step', parent: null, children: [],+ components: [{ type: 'SoundEventSource', data: { event: 'steps.esaudioevent' } }] }] };+ const result = await assets.preloadSceneAssets(scene, undefined, { skipSpine: true });+ expect(result.missing).toEqual([]); expect(fetchText).toHaveBeenCalledOnce();+ expect(result.acquisitions?.map(receipt => receipt.type)).toEqual(['sound-event']);+ assets.resolveSceneAssetPaths(scene, result);+ expect(scene.entities[0].components[0].data.event).toBe('steps.esaudioevent');+ expect(fetchBinary).not.toHaveBeenCalled(); result.scope.releaseAll(); assets.releaseAll();+ });it('reads the cooked path, validates the definition, and leaves clips unloaded', async () => {const ctx = makeContext(JSON.stringify(document));const data = await new SoundEventAssetLoader().load('steps.esaudioevent', ctx);diff --git a/sdk/tests/sound-event-playback.test.ts b/sdk/tests/sound-event-playback.test.tsindex ac050861c..9a076f71c 100644--- a/sdk/tests/sound-event-playback.test.ts+++ b/sdk/tests/sound-event-playback.test.ts@@ -10,6 +10,15 @@ import { SoundEventPlayback } from '../src/audio/SoundEventPlayback';import { MiniGameAudioBackend } from '../src/audio/MiniGameAudioBackend';import type { MiniGameGlobal, MiniGameInnerAudioContext } from '../src/platform/minigame/api';import type { Entity } from '../src/types';+import { World } from '../src/ecs/world';+import { SoundEventSource } from '../src/audio/AudioComponents';+import { SoundEventSourceController, triggerSoundEventSource, stopSoundEventSource } from '../src/audio/SoundEventSource';+import { aiRegistry, noInput } from '../src/ai/fsm/AiContext';+import { ensureBuiltinAiRegistrations } from '../src/ai/builtins';+import { Blackboard } from '../src/ai/fsm/Blackboard';+import { compileScriptGraph, createScriptRunState, stepScriptGraph } from '../src/logic/ScriptGraphRunner';+import { scriptCatalog } from '../src/logic/nodes';+import { SCRIPT_GRAPH_VERSION } from '../src/logic/types';const cleanup: Array<() => void> = [];afterEach(() => { for (const close of cleanup.splice(0)) close(); vi.restoreAllMocks(); });@@ -48,6 +57,138 @@ function fixture(extra: Record<string, unknown> = {}, actualBackend?: PlatformAusetDocument: (next: typeof document) => { document = next; } };}+function sourceFixture(extra: Record<string, unknown> = {}) {+ const f = fixture(extra), world = new World(), entity = world.spawn();+ f.alive.add(entity); world.insert(entity, SoundEventSource, { event: 'steps.esaudioevent', seed: 9 });+ const controller = new SoundEventSourceController(world, f.events, f.audio);+ cleanup.unshift(() => controller.dispose());+ return { ...f, world, entity, controller, trigger: () => triggerSoundEventSource(world, entity) };+}++describe('component-owned event intents', () => {+ it('keeps same-frame cold triggers in FIFO order with one definition load', async () => {+ const { trigger, fetchText, backend } = sourceFixture();+ const handles = (await Promise.all([trigger(), trigger(), trigger()]))!;+ expect(handles.map(handle => handle?.selection?.clip)).toEqual(['a.wav', 'b.wav', 'a.wav']);+ await Promise.all(handles.map(handle => handle?.ready));+ expect(fetchText).toHaveBeenCalledOnce(); expect(backend.play).toHaveBeenCalledTimes(3);+ });++ it('bounds cold intent storage and applies event limits only through shared playback', async () => {+ const { trigger, fetchText, events, backend } = sourceFixture({ maxInstances: 1 });+ const text = deferred<string>(); fetchText.mockReturnValue(text.promise);+ const pending = Array.from({ length: 256 }, trigger);+ expect(await trigger()).toBeNull();+ text.resolve(JSON.stringify({ version: 1, clips: [{ clip: 'a.wav' }], maxInstances: 1 }));+ const handles = await Promise.all(pending); await handles[0]!.ready;+ expect(handles.filter(handle => handle?.reason === 'event-limit')).toHaveLength(255);+ expect(events.getStats()).toMatchObject({ active: 1, admitted: 1, rejected: 255 });+ expect(backend.play).toHaveBeenCalledOnce();+ });++ it.each(['stop', 'global-stop', 'remove', 'disable', 'replace', 'reinsert', 'dispose'])(+ 'cancels a cold definition on %s and resolves every waiter', async mode => {+ const { world, entity, trigger, fetchText, backend, controller, audio, events } = sourceFixture();+ const text = deferred<string>(); fetchText.mockReturnValueOnce(text.promise);+ const pending = [trigger(), trigger()];+ if (mode === 'stop') stopSoundEventSource(world, entity);+ if (mode === 'global-stop') audio.stopAll();+ if (mode === 'remove') world.remove(entity, SoundEventSource);+ if (mode === 'disable') world.update(entity, SoundEventSource, data => { data.enabled = false; });+ if (mode === 'replace') world.update(entity, SoundEventSource, data => { data.event = 'other.esaudioevent'; });+ if (mode === 'reinsert') { world.remove(entity, SoundEventSource); world.insert(entity, SoundEventSource, { event: 'steps.esaudioevent' }); }+ if (mode === 'dispose') controller.dispose();+ controller.update();+ expect(await Promise.all(pending)).toEqual([null, null]);+ text.resolve(JSON.stringify({ version: 1, clips: [{ clip: 'a.wav' }] }));+ await new Promise(done => setTimeout(done, 0));+ expect(backend.play).not.toHaveBeenCalled(); expect(events.getStats().pendingDefinitions).toBe(0);+ expect(events.getStats().active).toBe(0);+ });++ it('does not start a late clip after same-frame component removal, even before update', async () => {+ const { world, entity, trigger, fetchBinary, backend, audio } = sourceFixture();+ const clip = deferred<ArrayBuffer>(); fetchBinary.mockReturnValueOnce(clip.promise);+ const handle = (await trigger())!;+ world.remove(entity, SoundEventSource);+ clip.resolve(new ArrayBuffer(4));+ expect(await handle.ready).toBe('rejected'); expect(handle.reason).toBe('owner-gone');+ expect(backend.play).not.toHaveBeenCalled(); expect(audio.getBufferStats().bufferCount).toBe(0);+ });++ it('keeps new-generation cold triggers created by a reentrant Stop All observer', async () => {+ const f = sourceFixture(); f.controller.dispose();+ let next!: Promise<import('../src/audio/SoundEventPlayback').SoundEventHandle | null>;+ const off = f.audio.onPlaybackStop(() => { next = f.trigger(); });+ const controller = new SoundEventSourceController(f.world, f.events, f.audio);+ cleanup.unshift(() => { off(); controller.dispose(); });+ const text = deferred<string>(); f.fetchText.mockReturnValueOnce(text.promise);+ const previous = f.trigger(); f.audio.stopAll(); expect(await previous).toBeNull();+ text.resolve(JSON.stringify({ version: 1, clips: [{ clip: 'a.wav' }] }));+ expect(await (await next)!.ready).toBe('playing'); expect(f.backend.play).toHaveBeenCalledOnce();+ });++ it('cancels definitions made stale before the next controller update', async () => {+ const { trigger, fetchText, world, entity, backend, events } = sourceFixture();+ const text = deferred<string>(); fetchText.mockReturnValueOnce(text.promise);+ const pending = trigger(); world.remove(entity, SoundEventSource);+ text.resolve(JSON.stringify({ version: 1, clips: [{ clip: 'a.wav' }] }));+ expect(await pending).toBeNull(); expect(backend.play).not.toHaveBeenCalled();+ expect(events.getStats()).toMatchObject({ emitters: 0, pendingDefinitions: 0 });+ });++ it('stops only source-owned emitters and can trigger again without replaying awake', async () => {+ const { entity, world, trigger, events, controller, backend } = sourceFixture();+ world.update(entity, SoundEventSource, data => { data.playOnAwake = true; });+ const independent = (await events.load('steps.esaudioevent', { owner: entity }))!;+ const other = independent.trigger(); await other.ready;+ const owned = (await trigger())!; await owned.ready;+ stopSoundEventSource(world, entity); controller.update();+ expect(owned.status).toBe('stopped'); expect(other.status).toBe('playing');+ expect(backend.play).toHaveBeenCalledTimes(2);+ const next = (await trigger())!; expect(await next.ready).toBe('playing');+ expect(next.selection?.clip).toBe('a.wav');+ });++ it('plays awake once per incarnation and invalidates an old loading clip after seed changes', async () => {+ const { world, entity, controller, backend, fetchBinary } = sourceFixture();+ world.update(entity, SoundEventSource, data => { data.playOnAwake = true; });+ controller.update(); await new Promise(done => setTimeout(done, 0));+ controller.update(); expect(backend.play).toHaveBeenCalledOnce();+ world.remove(entity, SoundEventSource);+ world.insert(entity, SoundEventSource, { event: 'steps.esaudioevent', seed: 9, playOnAwake: true });+ const clip = deferred<ArrayBuffer>(); fetchBinary.mockReturnValue(clip.promise);+ controller.update(); await new Promise(done => setTimeout(done, 0));+ world.update(entity, SoundEventSource, data => { data.seed = 10; });+ clip.resolve(new ArrayBuffer(4)); await new Promise(done => setTimeout(done, 0));+ expect(backend.play).toHaveBeenCalledOnce();+ controller.update(); await new Promise(done => setTimeout(done, 0));+ expect(backend.play).toHaveBeenCalledTimes(2);+ });++ it('uses the same entry through graph/FSM actions and preserves other worlds on disposal', async () => {+ const a = sourceFixture(), b = sourceFixture();+ ensureBuiltinAiRegistrations();+ const ctx = { world: a.world, entity: a.entity, dt: 1 / 60, input: noInput(), blackboard: new Blackboard(),+ commands: {} as never, has: (c: typeof SoundEventSource) => a.world.has(a.entity, c),+ get: (c: typeof SoundEventSource) => a.world.get(a.entity, c), set: () => {} };+ const compiled = compileScriptGraph({ version: SCRIPT_GRAPH_VERSION,+ nodes: [{ id: 'start', kind: 'event.start' }, { id: 'a', kind: 'call', ref: 'soundEvent.trigger' },+ { id: 'b', kind: 'call', ref: 'soundEvent.trigger' }],+ edges: [{ id: 'one', from: 'start', fromPort: 'then', to: 'a', toPort: '' },+ { id: 'two', from: 'a', fromPort: 'then', to: 'b', toPort: '' }],+ }, scriptCatalog(aiRegistry));+ expect(compiled.problems).toEqual([]);+ stepScriptGraph(compiled, createScriptRunState(compiled), { ctx: ctx as never,+ bb: ctx.blackboard, registry: aiRegistry, dt: ctx.dt });+ await new Promise(done => setTimeout(done, 0)); expect(a.backend.play).toHaveBeenCalledTimes(2);+ aiRegistry.getAction('soundEvent.stop')!(ctx as never, ctx.blackboard);+ expect(a.events.getStats().active).toBe(0);+ a.controller.dispose(); expect(await a.trigger()).toBeNull();+ expect(await (await b.trigger())!.ready).toBe('playing');+ });+});+describe('event admission and owned playback', () => {it('loads definitions without fetching clips and releases its definition on emitter disposal', async () => {const { events, fetchBinary } = fixture(); const emitter = (await events.load('steps.esaudioevent', { seed: 1 }))!;diff --git a/tools/assetMetaTable.js b/tools/assetMetaTable.jsindex 49fa31912..9ab75764b 100644--- a/tools/assetMetaTable.js+++ b/tools/assetMetaTable.js@@ -91,6 +91,7 @@ export const EXT_TO_TYPE = Object.freeze({'.esanimator': 'animatorcontroller','.esavatar': 'avatar','.eslocale': 'locale',+ '.esaudioevent': 'sound-event','.inputmap': 'inputmap',// Fonts'.fnt': 'bitmapFont',