Files
prometeu-studio/discussion/lessons/DSC-0098-pbs-core-sprite-animation/LSN-0100-sprite-animation-and-shared-authoring.md
T
bquarkz bf31184d4d feat(pbs): add sprite animation and shared Studio authoring
Implement DEC-0084 with factory-only Sprite/Animator structs, complete result
lowering, validated animation sidecars, generated PBS factories and JavaFX/MCP
authoring through shared services.

Qualify native dev/release with ordinary and optimized producers, zero-allocation
playback, private-cycle reclamation, canonical Composer pixels, installed JARs
and JavaFX lifecycle. Preserve the runtime checkout and existing host ABI.
2026-11-05 15:16:07 +00:00

11 KiB

id, ticket, title, created, tags
id ticket title created tags
LSN-0100 pbs-core-sprite-animation Sprite Animation, Typed Results and Shared Authoring 2026-11-05
compiler
pbs
core
stdlib
animation
studio
packer

Context and outcome

Owner: compiler/pbs. Studio owns the neutral authoring model and editor; Packer owns registered asset identity and the effective glyph layout. DEC-0084 and PLN-0162 delivered one complete feature across these domains. Their workflow artifacts were retired after implementation; the durable contracts are PBS chapter 27 and Studio chapter 12.

Games previously supplied primitive Composer arguments and implemented animation themselves. The final implementation supplies ordinary PBS Sprite, AnimatorBuilder and Animator structs, explicit-tick playback, generated factories from canonical JSON, complete JavaFX authoring, task-authorized MCP operations and installed examples. Composer keeps its public nine arguments, int status, capability and host identity. No runtime source or ABI changed.

Model identity and playback separately

SpriteView.sprite() returns bank and glyph together. A palette, position, layer, flip and priority still belong to the caller's emission. A visual query neither advances an animator nor constructs a Sprite.

The builder fixes its bank and initial clip name. It permits one open clip, validates operations in the specified order and retains a failed draft for repair. Every build() copies all mutable clip/frame nodes before publishing an animator. Two builds have independent playback and backing; ordinary assignment aliases one animator. Only immutable strings may retain ordinary sharing.

The public types carry trusted factory-only construction metadata. Checking the spelling of an imported type would be insufficient: aliases preserve the declaring type's identity, and same-module permission is tied to the current file/module. Game source cannot manufacture the reserved attribute. Public barrels hide node types and constructor completion surfaces.

Each published clip has immutable frame links with cumulative ends and a tail link to its head. Animator retains its selected clip, current frame, phase and playback state. For positive ticks while Playing:

  1. Reject phase > LONG_MAX - ticks before addition.
  2. Loop reduces the new phase modulo the total duration.
  3. Once finishes after the entire final duration and retains the last image.
  4. Resolve the frame from cumulative ends, traversing at most one clip.
  5. Publish the new phase, cursor and state after calculations complete.

No per-tick or per-skipped-loop iteration is needed. Successful advance, negative and overflow errors, and sprite queries execute no heap allocations after construction. Builder construction and copying have their ordinary allocation costs. A VM resource trap remains a trap; recoverable domain-error preservation does not promise rollback after arbitrary VM failures.

play and select reset even when passed the current name. Use play on an action transition, then advance for continuity. Pause/resume preserve progress; resume does not restart Finished. Stop resets to Stopped; restart resets to Playing.

Preserve the complete result group

Executable result returns use the existing VM group:

Int32 status, complete typed payload
0 = success; 1..N = canonical error declaration order

Unit returns only status. An inactive reference, function or trait payload uses runtime-admitted nullable defaults. Reserved, never-assigned locals supply Null without allocating default-holder structs. Scalars and builtin groups receive their correct typed defaults. Slot count alone never establishes nominal type or error identity.

Propagation evaluates once, discards pending expression temporaries on its error path, returns the same status and supplies the enclosing function's inactive payload. Handling evaluates once and executes only its selected recovery/remap. Neither catches a VM trap. Imports, contract calls, discarded results and Registry signatures must agree on the same status-plus-payload shape. A result-effect function cannot become a plain Fn value; successful Fn payloads remain ordinary typed function references.

A useful integration pitfall appeared in let glyph = animator.sprite().glyph_id. The tuple-producing method inherited the projected field's expected int type, which prevented the method call from being selected during lowering. Lowering the receiver with its own tuple type fixes the call and subsequent projection. The state-matrix fixture exposed this before native admission.

Canonical persistence has one owner

The sidecar animations.studio.json is the editable persistence surface. Its strict version-1 codec rejects duplicate/unknown keys, unsupported versions, invalid UTF-16 strings and fractional/out-of-range integers. Durations retain exact signed 64-bit values, including numbers above JavaScript's exact integer range.

Bindings use stable selected artifact IDs, current glyph indices and fingerprints. Paths and list positions are not animation identity. Reordering, removal and replacement block preview/build until an explicit rebind. Bank relocation retains identity. Palette and playback clock never become definition fields.

prometeu-animation owns DTOs, codec, validation, revisions, rebind and timeline. It depends on no compiler, concrete Packer, JavaFX or Spring classes. Packer exposes its effective layout using the same material/composition helpers as packing. App composition adapts that public API to the neutral layout port.

Revision verification and atomic replacement run under Packer's existing project exclusion. Preparing rebind returns a binding-only candidate, old/new differences, affected frames, proposal hash and bank revision. Applying checks the exact current proposal. The hash correlates content; it introduces no new grant or approval.

Late asynchronous callbacks require attention. Cancelling the waiting task thread does not necessarily stop a queued Packer callback. Task authority and a sticky cancellation state are checked again at publication. Concurrent creates admit one winner; a cancelled late callback cannot overwrite canonical bytes.

Studio's module boundary is also real: session consumes the exported assets.AnimationOperations seam, rather than depending on the hidden assets.animation.DefaultAnimationService implementation. The modularity test caught that distinction during integration.

Generate a view instead of another document

Only registered, included banks with valid definitions publish factories:

import { create_hero } from @app:generated/animations/b_12345678123412341234123456789abc;
import { AnimationError } from @core:animation;

fn example() -> result<AnimationError> {
    let value = create_hero(3)!;
    value.play("idle")!;
    value.advance(2)!;
    let image = value.sprite();
    // Caller supplies image.bank_id/image.glyph_id plus external emission inputs.
    return ok(());
}

PBS owns this deterministic projection. Factories sort by animator ID; clip/frame order remains authored order. Revisions include the document, resolved bank and generator version, excluding timestamps and absolute paths. Included invalid definitions or a missing layout resolver fail explicitly. Physical modules cannot occupy the reserved namespace.

The compiler/LSP exposes revision-scoped read-only documents and UTF-8 origin ranges mapped to JSON pointers. The origin command revalidates the current source and opens the bank/field through Studio's authoring service. Caller-provided paths are not navigation authority. Wire metadata uses URI strings, not Java filesystem implementation objects, so JSON-RPC serialization does not reflect into private Path internals. Changed origins are rejected after edits or reconnect.

JavaFX and MCP share validation, persistence, preview and rebind services. Human draft editing stays in controls; authority and file writes stay in services. Handoff awaits animation refresh as well as the existing forms. UI autoplay merely schedules explicit preview ticks. MCP query/update schemas admit only fields for the selected operation and retain existing task admission and result envelopes.

Qualify the boundary that actually executes

The production-native matrix executes both ordinary and optimized producers in dev and release. Result fixtures cover complete payloads, once-only evaluation, recovery/remapping and uncaught traps. Animation fixtures cover ownership, all domain errors, state/time boundaries, long/count limits, int-max jumps and zero executed allocation instructions in the marked paths.

Safepoint fixtures observe live private rings, then zero retained Animator/clip/frame objects after releasing their last owner. The observed cumulative reclamation is 2,411 objects at the first collection and 4,817 at the second. Test-only near-limit and safepoint setup is isolated from shipped modules; no billions-of-elements claim or public mutation hook is implied.

A real saved-project corpus runs direct and generated animators through Composer. For both producers and native profiles, ticks 0..7 produce glyphs 0,0,1,1,1,2,0,0, alternating palettes 0/1. Every sprite pixel matches shared preview: 32 native frame observations and 16,384 pixel comparisons. The configured packaged process repeats both producer variants with 8,192 pixel comparisons. The sidecar bytes remain unchanged by palette selection and execution.

That gate found a pre-existing Composer adapter mismatch: native statuses use an Int64 carrier while the public PBS facade returns int. The private host declaration now uses long and the facade explicitly narrows using an existing intrinsic. Public arguments, status type, slot counts, capability and host identity remain unchanged. Runtime modification was unnecessary.

Installed knowledge is tested in a separate JVM outside the checkout using product JARs. It saves a Packer-bound definition, compiles generated factories, verifies read-only origins and installed MCP schemas, and supplies native firmware fixtures. The JavaFX gate authors, saves, previews, repairs drift and closes the real editor. The full regression and architecture/modularity gates pass.

See qualification evidence, concrete results and editor capture. The evidence records exact hashes, commands, environment and practical test limits. Cargo outputs stayed under /tmp; the runtime checkout remained unchanged. No runtime commits were created.

Common mistakes

  • Treating a result payload as its plain return while forgetting the status slot.
  • Allocating a default holder on every unit error or inactive payload path.
  • Letting aliases or transitive factory return types lose declaration provenance.
  • Sharing mutable builder nodes with published animators.
  • Replaying every skipped tick or loop instead of reducing phase first.
  • Calling play every frame and unintentionally resetting the cursor.
  • Retargeting frames by path/order when stable identity drifts.
  • Validating a revision before queuing work and assuming it remains current at save.
  • Keeping stale generated text as a fallback after validation fails.
  • Testing only source compilation when typed native admission and real rendering are part of the contract.