# WRK-0013 — inspeção complementar de bancos, maps e composição

Data UTC: 2026-11-17T10:42:52.544233+00:00

Owner de produto: studio. Runtime somente leitura. Sem build, testes ou execução gráfica.

- runtime: `2d5735cb13876b3608cd5a90f849ef6823fc1d94`; status: limpo
- studio: `fa37d0d0c7d9f8ea33ea630571ed6117581a1958`; status: limpo

## Fontes e hashes

- `runtime/docs/specs/runtime/15-asset-management.md` — SHA-256 `0d7eda80c59ffbb7c49340835540bc0dc93aa25d7e74078e03475673bedb8b3a`; 590 linhas.
- `runtime/docs/specs/runtime/04-gfx-peripheral.md` — SHA-256 `fb5837ade0b76df63989f5d724c8bef7247b9851408ba4b6f257acf911be5c85`; 819 linhas.
- `runtime/crates/console/prometeu-hal/src/scene_bank.rs` — SHA-256 `6ba5e4e577389355f2c8678958d23b1c74d266404959966c777798c14dc59a55`; 56 linhas.
- `runtime/crates/console/prometeu-hal/src/scene_layer.rs` — SHA-256 `11cbd34788389d959c0d134251ce9c4b2c499a76228052886a149db5c95db504`; 60 linhas.
- `runtime/crates/console/prometeu-hal/src/tile.rs` — SHA-256 `cd29513a645c79dc4ca1b4a736fe0c54478d189be74b9725e8ea716b632a62b5`; 10 linhas.
- `runtime/crates/console/prometeu-hal/src/glyph_bank.rs` — SHA-256 `caca493e059f5d22324524131a10f14c07542208d3dee52ccefa354e92eb6fc4`; 155 linhas.
- `runtime/crates/console/prometeu-hal/src/sprite.rs` — SHA-256 `9d18df0698cc97431f48bbf5a06f223ab51bf1cd721da89a1126f2c8774b83cb`; 14 linhas.
- `runtime/crates/console/prometeu-drivers/src/memory_banks.rs` — SHA-256 `19a1e6e07db298878018f3aec6ab94c36efda63911d935591a05022fc35d24e0`; 248 linhas.
- `runtime/crates/console/prometeu-drivers/src/frame_composer.rs` — SHA-256 `e108a694bc72ea210bc6a668bdc070f88328456f5f90f550f8db88f0096a79d5`; 1166 linhas.
- `studio/docs/specs/studio/12. Animation Authoring Specification.md` — SHA-256 `6b6bf6270380a11dd23bb7c919ab47a81d27e21e9560a351a83bef976f0fa4a4`; 159 linhas.
- `studio/test-projects/main/src/main.pbs` — SHA-256 `20219dd7b340bbb3d750d684e108cefa75e65a4c10f171fb7b42fedf98b71d9f`; 95 linhas.
- `studio/prometeu-studio-api/src/main/java/p/studio/api/assets/metadata/AssetStudioSceneBankMetadata.java` — SHA-256 `6b1ee951ec8b1bd82d5030946a502414ba41f1ff078266535f2b511b6af3f732`; 40 linhas.
- `studio/prometeu-studio-api/src/main/java/p/studio/api/assets/metadata/AssetStudioSceneLayerBinding.java` — SHA-256 `3adcf8c2fcfa5089714f6c9b2e73033b6345843caeb927f0c1b7e3ece9340099`; 82 linhas.

## runtime/docs/specs/runtime/15-asset-management.md:9
```text
9: 
10: PROMETEU asset management is bank-centric.
11: 
12: Assets are:
13: 
14: - cold bytes stored in the cartridge;
15: - described by cartridge metadata;
16: - materialized into host-managed banks;
17: - separate from VM heap ownership.
18: 
19: This chapter describes the runtime contract currently visible in the codebase. It is not a full tooling pipeline specification.
20: 
21: ## 2 Core Principles
22: 
23: 1. asset residency is explicit;
24: 2. asset memory belongs to the machine, not to the VM heap;
25: 3. banks and slots are hardware/runtime concepts;
26: 4. loading and activation are explicit operations;
27: 5. asset memory does not participate in GC.
28: 
29: ## 3 Cartridge Asset Artifact
30: 
31: The runtime currently consumes one primary cartridge asset artifact:
```

## runtime/docs/specs/runtime/15-asset-management.md:179
```text
179: before they are loaded by the runtime.
180: 
181: Palette indices are ordinary indices. Transparency is represented by the alpha
182: channel of the resolved RGBA8888 palette entry, not by reserving index `0`.
183: 
184: `palette_id` is valid only when it is lower than the referenced resident glyph
185: bank's `palette_count`. Canonical runtime composition MUST NOT substitute
186: transparent, black, or any other default color for `palette_id >=
187: palette_count`.
188: 
189: ### 4.2 `SCENE` asset contract in v1
190: 
191: For `BankType::SCENE`, the v1 runtime-facing contract is:
192: 
193: - `codec = NONE`
194: - payload magic is `SCNE`
195: - payload version is `1`
196: - layer count is fixed at `4`
197: - each layer carries its own glyph dependency
198: - the glyph dependency is serialized as canonical `AssetId` using signed 32-bit little-endian width
199: - the payload MUST describe cold asset dependencies only and MUST NOT encode runtime glyph slot topology
200: 
201: Even with `codec = NONE`, `SCENE` still has a bank-specific binary contract. The serialized layout is normative and distinct from any transient runtime residency state.
202: 
203: #### 4.2.1 Layer Header Layout
204: 
205: Each scene layer header is:
206: 
207: 1. `flags: u8`
208: 2. `glyph_asset_id: i32` (little-endian)
209: 3. `tile_size: u8`
210: 4. `reserved: u16`
211: 5. `parallax_x: f32`
212: 6. `parallax_y: f32`
213: 7. `width: u32`
214: 8. `height: u32`
215: 9. `tile_count: u32`
216: 10. `reserved: u32`
217: 
218: This makes the canonical per-layer header size `32` bytes.
219: 
220: Normative rules:
221: 
222: - `glyph_asset_id` MUST be interpreted as the cold identity of the glyph dependency for that layer;
223: - `glyph_asset_id` MUST NOT be interpreted as a runtime slot id;
224: - each layer MUST own exactly one glyph dependency reference;
225: - no shared dependency table exists in this contract;
226: - `tile_count` MUST equal `width * height`.
227: 
228: #### 4.2.2 Runtime Binding Semantics
229: 
230: `SCENE` assets do not own runtime residency.
231: 
232: Therefore:
233: 
234: - the runtime MUST resolve scene glyph dependencies through runtime-owned residency state;
235: - the runtime MUST maintain a runtime-owned mapping from committed glyph `AssetId` to glyph slot;
236: - scene bind and scene draw MUST consult runtime residency, not serialized slot topology;
237: - a missing scene glyph dependency is not a passive asset-status condition.
238: 
239: If a scene glyph dependency cannot be resolved:
240: 
241: - `bind_scene` MUST fail as a fatal machine error with clear logging;
242: - draw/composition MUST fail as a fatal machine error with clear logging;
243: - runtime MUST NOT continue scene composition after the missing dependency is detected.
244: 
245: ### 4.3 Decoding validation and physical payload completeness
```

## runtime/docs/specs/runtime/15-asset-management.md:280
```text
280: 
281: The runtime resolves bank context from `asset_table` using `asset_id`.
282: 
283: Internally, the runtime may still use a bank-qualified slot reference such as:
284: 
285: ```text
286: SlotRef { bank_type, index }
287: ```
288: 
289: That internal representation is derived from the resolved `AssetEntry`, not supplied by the caller.
290: 
291: ### 5.1 Canonical Bank Telemetry
292: 
293: The canonical visible bank telemetry contract is exposed by `AssetManager`.
294: 
295: The per-bank summary is slot-first and uses this shape:
296: 
297: ```text
298: BankTelemetry {
299:   bank_type
300:   used_slots
301:   total_slots
302: }
303: ```
304: 
305: Rules:
306: 
307: - the visible contract MUST NOT expose byte-oriented bank occupancy as the canonical summary;
308: - canonical bank names are `GLYPH` and `SOUNDS`;
309: - detailed occupancy inspection remains host-owned and slot-based through slot references, not bank byte totals;
310: - public runtime specs MUST NOT treat `bank.slot_info` or JSON bank inspection payloads as the long-term guest ABI;
311: - any residual byte accounting MAY exist internally, but it is not part of the visible bank telemetry contract.
```

## runtime/docs/specs/runtime/15-asset-management.md:340
```text
340: 
341: `open_slice` is the runtime-facing concept for opening a limited view over a payload slice. The runtime must not require the whole `assets.pa` payload to remain resident in RAM as its baseline operating mode.
342: 
343: `OP_MODE` selects between direct slice consumption and temporary materialization in memory.
344: 
345: For v1:
346: 
347: - `OP_MODE` is derived from `codec`/CODEX;
348: - explicit per-asset hinting is not part of the baseline contract.
349: - `TILES` with `codec = NONE` may still stage in memory before bank installation because bank-specific decode expands packed pixel indices into the resident representation.
350: - during the migration window, runtime may accept legacy `RAW` as an alias of `NONE`.
351: 
352: The runtime does not treat asset installation as implicit side effect.
353: 
354: ## 7 Residency and Ownership
355: 
356: Asset banks are host/runtime-owned memory.
357: 
358: Therefore:
359: 
360: - VM heap does not own asset residency;
361: - GC does not scan asset bank memory;
362: - shutting down a cartridge can release bank residency independently of VM heap behavior.
363: - the runtime must not keep the full `assets.pa` payload resident in RAM as a baseline requirement.
```

## runtime/docs/specs/runtime/15-asset-management.md:396
```text
396: 
397: Validation rules:
398: 
399: - `preload` is resolved by `asset_id`, not by `asset_name`;
400: - every `preload.asset_id` must exist in the same `asset_table`;
401: - no two preload entries may resolve to the same `(bank_type, slot)` pair;
402: - legacy preload keyed by `asset_name` is invalid for the current contract.
403: 
404: Lifecycle rule:
405: 
406: - `preload` is boot-time input only;
407: - it does not need to remain live after initialization completes.
408: 
409: Bootstrap rule:
410: 
411: - invalid preload is a structural cartridge error and must fail cartridge bootstrap before normal execution begins.
412: 
413: ## 10 Relationship to Other Specs
414: 
415: - [`13-cartridge.md`](13-cartridge.md) defines the cartridge package and the requirement that `assets.pa` carries its own asset header.
416: - [`16-host-abi-and-syscalls.md`](16-host-abi-and-syscalls.md) defines the syscall boundary used to manipulate assets.
417: - [`03-memory-stack-heap-and-allocation.md`](03-memory-stack-heap-and-allocation.md) defines the distinction between VM heap memory and host-owned memory.
418: 
419: ## 11 Syscall Surface and Status Policy
420: 
421: `asset` follows status-first policy.
422: 
423: Fault boundary:
424: 
425: - `Trap`: structural ABI misuse (type/arity/capability/shape mismatch);
```

## runtime/crates/console/prometeu-hal/src/scene_bank.rs:1
```text
1: use crate::scene_layer::SceneLayer;
2: 
3: #[derive(Clone, Debug)]
4: pub struct SceneBank {
5:     pub layers: [SceneLayer; 4],
6: }
```

## runtime/crates/console/prometeu-hal/src/scene_layer.rs:1
```text
1: use crate::asset::AssetId;
2: use crate::glyph_bank::TileSize;
3: use crate::tilemap::TileMap;
4: 
5: #[derive(Clone, Copy, Debug)]
6: pub struct ParallaxFactor {
7:     pub x: f32,
8:     pub y: f32,
9: }
10: 
11: #[derive(Clone, Debug)]
12: pub struct SceneLayer {
13:     pub active: bool,
14:     pub glyph_asset_id: AssetId,
15:     pub tile_size: TileSize,
16:     pub parallax_factor: ParallaxFactor,
17:     pub tilemap: TileMap,
18: }
19: 
20: #[cfg(test)]
```

## runtime/crates/console/prometeu-hal/src/sprite.rs:1
```text
1: use crate::glyph::Glyph;
2: 
3: #[derive(Clone, Copy, Debug)]
4: pub struct Sprite {
5:     pub glyph: Glyph,
6:     pub x: i32,
7:     pub y: i32,
8:     pub layer: u8,
9:     pub bank_id: u8,
10:     pub active: bool,
11:     pub flip_x: bool,
12:     pub flip_y: bool,
13:     pub priority: u8,
14: }
```

## runtime/crates/console/prometeu-drivers/src/memory_banks.rs:72
```text
72: }
73: 
74: impl Default for MemoryBanks {
75:     fn default() -> Self {
76:         Self::new()
77:     }
78: }
79: 
80: impl MemoryBanks {
81:     /// Creates a new set of memory banks with empty slots.
82:     pub fn new() -> Self {
83:         Self {
84:             glyph_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
85:             sound_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
86:             scene_bank_pool: Arc::new(RwLock::new(std::array::from_fn(|_| None))),
87:         }
88:     }
89: }
90: 
91: impl GlyphBankPoolAccess for MemoryBanks {
92:     fn glyph_bank_slot(&self, slot: usize) -> Option<Arc<GlyphBank>> {
93:         let pool = self.glyph_bank_pool.read().unwrap();
```

## runtime/crates/console/prometeu-drivers/src/frame_composer.rs:120
```text
120:     }
121: }
122: 
123: pub struct FrameComposer {
124:     scene_bank_pool: Arc<dyn SceneBankPoolAccess>,
125:     glyph_slot_index: GlyphAssetSlotIndex,
126:     viewport_width_px: usize,
127:     viewport_height_px: usize,
128:     active_scene_id: Option<usize>,
129:     active_scene: Option<Arc<SceneBank>>,
130:     scene_status: SceneStatus,
131:     camera_x_px: i32,
132:     camera_y_px: i32,
133:     cache: Option<SceneViewportCache>,
134:     resolver: Option<SceneViewportResolver>,
135:     sprite_controller: SpriteController,
136: }
137: 
138: #[derive(Clone, Debug, Default, PartialEq, Eq)]
139: pub struct ComposerBuffer {
140:     pub bound_scene: Option<BoundScenePacket>,
141:     pub camera: Camera2D,
142:     pub sprites: Vec<GameSpritePacket>,
143:     pub hud: HudPacket,
144: }
145: 
146: impl ComposerBuffer {
147:     pub fn close(self) -> Game2DFramePacket {
148:         Game2DFramePacket::new(
```

## runtime/crates/console/prometeu-drivers/src/frame_composer.rs:215
```text
215:     pub fn bind_scene(&mut self, scene_bank_id: usize) -> bool {
216:         let Some(scene) = self.scene_bank_pool.scene_bank_slot(scene_bank_id) else {
217:             self.unbind_scene();
218:             return false;
219:         };
220: 
221:         let _ = self.resolve_glyph_slots(&scene, scene_bank_id, "bind_scene");
222: 
223:         let (cache, resolver) =
224:             Self::build_scene_runtime(self.viewport_width_px, self.viewport_height_px, &scene);
225:         self.active_scene_id = Some(scene_bank_id);
226:         self.active_scene = Some(scene);
227:         self.scene_status = SceneStatus::Available { scene_bank_id };
228:         self.cache = Some(cache);
229:         self.resolver = Some(resolver);
230:         true
231:     }
```

## runtime/crates/console/prometeu-drivers/src/frame_composer.rs:404
```text
404:     fn resolve_glyph_slots(
405:         &self,
406:         scene: &SceneBank,
407:         scene_bank_id: usize,
408:         phase: &str,
409:     ) -> [usize; 4] {
410:         std::array::from_fn(|layer_index| {
411:             let layer = &scene.layers[layer_index];
412:             self.glyph_slot_index.glyph_slot_for_asset(layer.glyph_asset_id).unwrap_or_else(|| {
413:                 panic!(
414:                     "SCENE dependency fatal during {}: scene_bank_id={}, layer={}, glyph_asset_id={}",
415:                     phase, scene_bank_id, layer_index, layer.glyph_asset_id
416:                 )
417:             })
418:         })
419:     }
420: 
```

## studio/docs/specs/studio/12. Animation Authoring Specification.md:14
```text
14: 
15: Each registered glyph bank can contain animations.studio.json, a JSON UTF-8
16: sidecar distinct from asset.json and studio.asset.json. Its strict schema is:
17: 
18: ```json
19: {
20:   "schema_version": 1,
21:   "bank_asset_uuid": "<containing bank UUID>",
22:   "bindings": [{"artifact_id": "<stable selected artifact>", "glyph_id": 7,
23:                 "fingerprint": "<sha256>"}],
24:   "animators": [{"id": "hero", "initial_clip": "idle", "clips": [
25:     {"name": "idle", "mode": "loop", "frames": [
26:       {"artifact_id": "<stable selected artifact>", "duration_ticks": 4}
27:     ]}
28:   ]}]
29: }
30: ```
31: 
32: Animator IDs are unique PBS identifiers matching [A-Za-z_][A-Za-z0-9_]*. Modes
33: are once/loop; frame order matters. Each animator has nonempty named clips;
34: zero animator definitions is allowed. Decode long integers exactly. No palette,
35: position or runtime bank slot is stored. Unknown fields/versions and malformed
36: or duplicate bindings/JSON keys are errors, not fallback triggers.
37: 
38: Every referenced artifact must match the containing bank UUID and Packer's current
39: effective glyph ID/fingerprint. Reordering, removal and content replacement produce
40: blocking drift diagnostics. Explicit prepare/apply rebind presents old/new bindings
41: and affected frames, validates the result and requires the expected revision.
42: Never silently retarget by list order or path. Save validates the whole candidate
43: against the current snapshot and uses a revision check plus atomic replacement;
```

## studio/docs/specs/studio/12. Animation Authoring Specification.md:56
```text
56: projects without definitions retain an empty context and compatible entry points.
57: 
58: FESurfaceContext carries language-neutral validated snapshots; PBS alone emits
59: virtual modules at @<project-name>:generated/animations/b_<uuid-without-hyphens>.
60: Factories are create_<animator_id>(bank_id: int) -> result<AnimationError> Animator.
61: Reserve generated/animations and reject physical-module collisions. Only registered,
62: build-included banks publish factories. Invalid included definitions block build;
63: never reuse stale generated text. Sort factories by ID, preserve clip/frame order,
64: escape PBS literals and exclude timestamps/absolute paths. Keep generated modules
```

## studio/test-projects/main/src/main.pbs:1
```text
1: import { Log } from @sdk:log;
2: import { Pad, Button, Touch } from @sdk:input;
3: import { Composer } from @sdk:composer;
4: 
5: // Preloaded by Packer: Zelda3 -> glyph slot 0, tileset -> glyph slot 1,
6: // tiled2 -> scene slot 0. No separate atlas load is needed.
7: declare global scene_bound: bool = false;
```

## studio/test-projects/main/src/main.pbs:27
```text
27: {
28:     // Composer operations run during Frame, after preloads have completed.
29:     if (!scene_bound) {
30:         let status: int = Composer.bind_scene(0);
31:         if (status != 0) {
32:             Log.failure("Unable to bind the preloaded scene");
33:             return;
34:         }
35:         scene_bound = true;
36:     }
```

## studio/test-projects/main/src/main.pbs:62
```text
62:     }
63:     Composer.set_camera(camera_x, 0);
64:     Composer.emit_sprite(tile_id, 0, (Touch.x() as int) - 16, (Touch.y() as int) + 8, 2, 0, true, false, 0);
65: 
```

## Limites e interpretação

- SceneBank/layers/tilemap atuais representam mapa com quatro layers, não evidenciam um modelo de scene de jogo com entidades/scripts persistidos.
- A busca por struct Entity/GameObject/World, trait Entity/Component, enum Entity e spawn_entity não localizou um framework desses no runtime inspecionado; não é prova universal de ausência de modelos de jogo em bibliotecas externas.
- O composer recebe sprites separadamente da SceneBank; uma scene de autoria mais ampla exigirá contrato próprio de entidades/persistência/projeção.
- Identidade de asset no conteúdo e slot de residência são conceitos separados; o editor futuro não deve serializar slots na SceneBank para imitar o runtime.
- MemoryBanks usa 16 slots por família nesta implementação. A UI deve consumir orçamento/perfil qualificado, não hardcode desse número.
- Metadados de animação usam UUID/artifact identity/fingerprint; índices de glyph e slots têm papéis distintos.
- Não há implementação nova nem proposta aprovada de ECS, formato de scene amplo, geração de código ou mudança de runtime.
