diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/LSN-0100-sprite-animation-and-shared-authoring.md b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/LSN-0100-sprite-animation-and-shared-authoring.md new file mode 100644 index 00000000..41eebe8f --- /dev/null +++ b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/LSN-0100-sprite-animation-and-shared-authoring.md @@ -0,0 +1,211 @@ +--- +id: LSN-0100 +ticket: pbs-core-sprite-animation +title: Sprite Animation, Typed Results and Shared Authoring +created: 2026-11-05 +tags: [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](../../../docs/specs/compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md) +and [Studio chapter 12](../../../docs/specs/studio/12.%20Animation%20Authoring%20Specification.md). + +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: + +```text +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: + +```pbs +import { create_hero } from @app:generated/animations/b_12345678123412341234123456789abc; +import { AnimationError } from @core:animation; + +fn example() -> result { + 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](evidence/README.md), [concrete results](evidence/results.json) +and [editor capture](evidence/animation-editor.png). 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. diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/README.md b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/README.md new file mode 100644 index 00000000..c1314a8b --- /dev/null +++ b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/README.md @@ -0,0 +1,31 @@ +# DEC-0084 / PLN-0162 qualification evidence + +Owner: compiler/pbs; cross-domain Studio and Packer. Completed 2026-11-05. + +- `environment.json` records provider, installed executables, targets and commands. +- `source.sha256` identifies every changed tracked/untracked implementation file. +- `fixtures.sha256.gz` identifies the mandatory Result/Animation PBX, manifests, + packed assets and shared-preview pixel oracles in the Studio build corpus. +- `results.json` records concrete counts and limits; native logs contain assertions. +- Compressed regression and test reports preserve the final successful gates. +- `animation-editor.png` is the real JavaFX editor after authoring/save/preview. + +The production VM/firmware matrix ran ordinary and optimized producers in both +native dev/release profiles. The saved-project Composer corpus compares every +sprite pixel against the shared canonical preview while alternating palette IDs. +The configured installed process repeats that comparison for both producers. + +Heap counts cover executed allocation opcodes in the marked paths, not constructor +costs, host rendering or a claim about every theoretical program. Test-only count, +phase and safepoint setup does not add a public mutation API. Zero-quota construction +produces resource traps; it does not become a recoverable animation error. + +Origin navigation is qualified through the real compiler/LSP bridge and registry, +wire serialization, editor selection and client TypeScript compilation. The new +CodeLens was not separately exercised in a VS Code Extension Development Host. +The JavaFX image uses the standalone control with the default skin, not a full +Studio shell screenshot. + +The repository has no CLI operation to create/allocate a lesson. LSN-0100 was +prepared from the next available metadata ID; `discussion housekeep` registers +it and advances that counter. No index edit was performed manually. diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/SHA256SUMS b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/SHA256SUMS new file mode 100644 index 00000000..efbda78d --- /dev/null +++ b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/SHA256SUMS @@ -0,0 +1,21 @@ +0d28d6891ad8d385c1d103233e85f619005543528269eb6531428f07f1b348c0 README.md +d5260791f61756c7c1d5f9864e4a0c91c76751833a6e7827346a06e21672608c acceptance.md +15525c8aa73b7d940c020721a4fd1aa677d3d0c3fd6186ada0a8ff5082c0334f animation-authoring.xml.gz +95776283387855cb29abf982bc15cf680a2af90db23271e30c86784e16190fd0 animation-editor.png +2c0df78907358c81e820e5339664a221f7abd96583f13f062a303e98eb33943c animation-native-dev.log.gz +86c0ceca52378b4fb3f1750912c33abb878fc7e52d39395a7245a140b51286b0 animation-native-release.log.gz +bd3d04976189f3077709582fb5110c902503cb3af407ff82600b5f56226c6906 animation-ui.xml.gz +a4e58f9a9115d6c69e74e7add930f72f7259306c48c62cad47e3500605f9e9ec authoring-final.log.gz +9fe0bf32db9ca80997ace82d59f67782151cf9196df7e0a7346058960a0d521d composer-installed-process.log.gz +8e3faee9ff1cb98394aa3c08693e497bd03b131f92d4af78f926dec7182ae470 composer-installed-process.xml.gz +dbaa6ef29376e6c0f2763c13acbbcca9b9f188de830db8699b0f49c1bc88f8d7 environment.json +9324e7c344fdcfb0e6aaad7e00fc282a8f6b8424d115bb5f8bc0643176c29214 fixtures.sha256.gz +fa7e3732a4c3b7f2331cafbdcad22c6c30ea7a34c5222d824312b0688f782b02 fn-effect-rejection.log.gz +c0e843b7aeb63dcf4f4f0b1d206f314c5ea827cdfca33b66ddbe7c1c1e09c9fb installed-knowledge.xml.gz +9ef7dc7a127288ad4289a4e37c0d047081ffec3273659ad4912340ba27d985da regression.log.gz +d5caa3ba786b97e3d7de731f5645e9eb5fe448fe4abcc02dfecba5e2e9e9b000 result-native-dev.log.gz +10d6cb9fa5aafcd8f1c989ec87a5720e1a6944c34f47ab82e903af7bb722e39f result-native-release.log.gz +955cfe97d4033ab758024e1735f861fc12ccf1630139841abfd55d8b7f7c2668 results.json +25024cca3fdd75e59d09a6526a64c6cc7ef43d8af2f7121d849c7e61f62aedd4 source.sha256 +cd3505eb82eb5e0e60e459b93cb744a5846f520ffe53ff2a214a9378c0f55572 workflow.txt +a33cc281e5263d4e03aa0220b5ab6f7e6a4180222a980d646e68a569963217ef ../LSN-0100-sprite-animation-and-shared-authoring.md diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/acceptance.md b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/acceptance.md new file mode 100644 index 00000000..52360ed6 --- /dev/null +++ b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/acceptance.md @@ -0,0 +1,26 @@ +# Acceptance mapping + +All fourteen PLN-0162 criteria were completed. The accepted scope was not split. + +| Criterion | Implementation and observed gate | +| --- | --- | +| AC1 | English PBS 27 / Studio 12, propagated compiler/Packer/Studio chapters and indexes. Installed references read from JARs. | +| AC2 | Status-first full typed return groups. 21 Result cases × ordinary/optimized × native dev/release; trap cases remain traps; plain-Fn rejection tested. | +| AC3 | stdlib 1 core/sprite and core/animation, concrete/trait SpriteView queries, factory-only positional/named aliases rejected; forged metadata rejected. | +| AC4 | Reused builder produces independent finalized nodes. Draft repair/removal/rebuild preserves existing animators; assignment aliases. | +| AC5 | Native Loop/Once boundaries, complete state/reset behavior, pause/resume, zero/negative input, checked overflow, int-max jump and limit cases. | +| AC6 | Native instruction counters observe zero heap allocations in marked sprite/advance/error paths; bounded traversal gate; quota traps and cycle reclamation observed. | +| AC7 | Stable identities, fingerprints and exact JSON. Real Packer sidecar leaves assets.pa byte-identical; rebind detects drift; bank relocation retains identity and revision. | +| AC8 | Neutral p.animation module and layout port. Architecture and Spring Modulith gates pass. Included definitions without a resolver fail explicitly. | +| AC9 | Real build factories, reserved collision diagnostic, invalid/excluded behavior, exact UTF-8 including controls/supplementary characters, sorted/byte-identical regeneration; read-only revision-scoped JSON origins reject stale navigation/reconnect. | +| AC10 | Actual JavaFX create/frame/save/preview/rebind/origin selection/close fixture passes. Handoff awaits animation persistence/refresh and retains failed drafts. | +| AC11 | Shared manual/task services and strict MCP schemas. Valid MCP save/get/preview parity, stale revision, invalid authority, revoked task, concurrent creates and cancelled late publication tested. | +| AC12 | Direct/generated Composer pixels equal preview across tick boundaries and alternating palettes in ordinary/optimized producers and native dev/release. Configured packaged process repeats both producers. | +| AC13 | Installed JARs expose specs/modules/examples/MCP schemas and compile a saved project outside the checkout. Generated installed fixtures execute through production firmware. Runtime tree remains clean. | +| AC14 | Full Gradle regression, installed knowledge, architecture/modularity, dedicated JavaFX gate, client TypeScript compilation, native matrices and diff/workflow validation pass. | + +The new origin CodeLens was typechecked and its server/editor contracts were +qualified; a new VS Code Extension Development Host session was not performed. +The screenshot is the actual standalone JavaFX control with the default skin. +Count and safepoint fixtures use isolated test setup rather than allocating +billions of nodes or adding shipped mutation hooks. diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-authoring.xml.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-authoring.xml.gz new file mode 100644 index 00000000..608810be Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-authoring.xml.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-editor.png b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-editor.png new file mode 100644 index 00000000..728db615 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-editor.png differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-native-dev.log.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-native-dev.log.gz new file mode 100644 index 00000000..7fe66210 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-native-dev.log.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-native-release.log.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-native-release.log.gz new file mode 100644 index 00000000..ffc24806 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-native-release.log.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-ui.xml.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-ui.xml.gz new file mode 100644 index 00000000..f8fc39a0 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-ui.xml.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/authoring-final.log.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/authoring-final.log.gz new file mode 100644 index 00000000..90127466 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/authoring-final.log.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/composer-installed-process.log.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/composer-installed-process.log.gz new file mode 100644 index 00000000..18cc7087 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/composer-installed-process.log.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/composer-installed-process.xml.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/composer-installed-process.xml.gz new file mode 100644 index 00000000..a32e2fa2 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/composer-installed-process.xml.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/environment.json b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/environment.json new file mode 100644 index 00000000..af66d730 --- /dev/null +++ b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/environment.json @@ -0,0 +1,33 @@ +{ + "date": "2026-11-05", + "platform": "macOS-27.2-arm64-arm-64bit-Mach-O", + "studio_head": "1d8b8c21014b5b2e94bcd6621dbea177afc0d4eb", + "studio_tree": "uncommitted implementation; exact changed files in source.sha256", + "runtime_head": "09d8778f046a2819c50ac786bfb50e958ef5af61", + "runtime_working_tree": "clean", + "runtime_writes": false, + "runtime_commits": false, + "cargo_target": "/tmp/studio-animation-native-target", + "rustc": "rustc 1.98.1 (48a229cea 2026-09-01)", + "node": "24.21.0 (existing NVM installation; system Node has a missing ICU dependency)", + "java": { + "gradle_launcher": "Amazon Corretto 25", + "product_and_tests": "Amazon Corretto 21" + }, + "installed_runtime": "/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/dist-staging/stable/prometeu-cli-aarch64-apple-darwin", + "installed_runtime_sha256": { + "prometeu": "182e4d9a4d32201c8ad892a11c297de7059dcc0a837660bdd173be44808b9906", + "prometeu-headless": "7703190f63844d91fa125ba3a322b5e771db79a282b3cfbb3480eef76422b6ef", + "prometeu-runtime": "0e8e692395cedea799b6d555b416e40536dcabf3a98a2061327d2010c478e446" + }, + "commands": [ + "./gradlew test :prometeu-app:installedKnowledgeTest :prometeu-app:animationDesktopTest --console=plain", + "./gradlew :prometeu-app:test --tests *AnimationIntegrationTest :prometeu-app:headlessProcessTest --tests *AnimationInstalledRuntimeTest -PstudioRuntimeInstall= --console=plain", + "./gradlew :prometeu-architecture-tests:test --tests *PbsResultTest.resultFunctions* --console=plain", + "CARGO_TARGET_DIR=/tmp/studio-animation-native-target python3 tools/pbx-conformance/run.py --runtime ../runtime --result-only [--release]", + "CARGO_TARGET_DIR=/tmp/studio-animation-native-target python3 tools/pbx-conformance/run.py --runtime ../runtime --animation-only [--release]", + "NVM Node 24.21.0: node tools/vscode-extension/node_modules/typescript/bin/tsc -p tools/vscode-extension", + "git diff --check", + "discussion validate" + ] +} diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/fixtures.sha256.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/fixtures.sha256.gz new file mode 100644 index 00000000..5308cca2 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/fixtures.sha256.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/fn-effect-rejection.log.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/fn-effect-rejection.log.gz new file mode 100644 index 00000000..8a147eb0 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/fn-effect-rejection.log.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/installed-knowledge.xml.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/installed-knowledge.xml.gz new file mode 100644 index 00000000..1fb71b5d Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/installed-knowledge.xml.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/regression.log.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/regression.log.gz new file mode 100644 index 00000000..c7d3c15d Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/regression.log.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/result-native-dev.log.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/result-native-dev.log.gz new file mode 100644 index 00000000..f42169a4 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/result-native-dev.log.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/result-native-release.log.gz b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/result-native-release.log.gz new file mode 100644 index 00000000..d1fa0290 Binary files /dev/null and b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/result-native-release.log.gz differ diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/results.json b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/results.json new file mode 100644 index 00000000..3a4ed7a7 --- /dev/null +++ b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/results.json @@ -0,0 +1,134 @@ +{ + "result": { + "producer_variants": [ + "ordinary", + "optimized" + ], + "native_profiles": [ + "dev", + "release" + ], + "cases_per_producer": 21, + "native_fixture_runs": 84, + "trap_cases": "remain VM traps; handle never recovers traps" + }, + "animation": { + "cases_per_producer": 9, + "producer_variants": [ + "ordinary", + "optimized" + ], + "native_profiles": [ + "dev", + "release" + ], + "native_fixture_runs": 36, + "measured_allocations": 0, + "measured_paths": [ + "sprite via concrete/trait", + "successful advance", + "negative advance", + "overflow advance", + "factory/builder error paths" + ], + "count_setup": "test-only near-limit nodes; unchanged production operation; no billions-of-elements claim", + "frame_traversal_gate": "less than 50000 measured instructions including int-max jump" + }, + "gc": { + "profiles": [ + "dev", + "release" + ], + "producer_variants": [ + "ordinary", + "optimized" + ], + "live_root_first_safepoint": true, + "unowned_animation_clip_frame_objects_second_safepoint": 0, + "reclaimed_first_safepoint": 2411, + "reclaimed_cumulative_second_safepoint": 4817 + }, + "composer": { + "producer_variants": [ + "ordinary", + "optimized" + ], + "native_profiles": [ + "dev", + "release" + ], + "ticks": [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7 + ], + "glyphs": [ + 0, + 0, + 1, + 1, + 1, + 2, + 0, + 0 + ], + "palettes": [ + 0, + 1, + 0, + 1, + 0, + 1, + 0, + 1 + ], + "sources": [ + "direct builder", + "saved JSON generated factory" + ], + "sprite_size": [ + 16, + 16 + ], + "native_frame_observations": 32, + "native_pixel_comparisons": 16384, + "installed_process_frame_observations": 16, + "installed_process_pixel_comparisons": 8192, + "canonical_sidecar_bytes_preserved": true + }, + "ui": { + "toolkit": "actual JavaFX, standalone control, default skin", + "actions": [ + "create animator and clip", + "add frame with exact duration", + "save", + "preview canonical PNG", + "bank drift", + "prepare/apply rebind", + "JSON origin selection", + "handoff and close" + ], + "screenshot": "animation-editor.png" + }, + "navigation": { + "revision_revalidation": true, + "reconnect": true, + "stale_origin_rejection": true, + "wire_origin_serialization": true, + "client_typecheck": true, + "full_vscode_development_host_for_new_codelens": false + }, + "boundaries": { + "runtime_unchanged": true, + "neutral_model_architecture": true, + "studio_module_export_contract": true, + "binary_assets_unchanged_by_sidecar": true, + "cancelled_late_publication_blocked": true, + "concurrent_create_single_winner": true + } +} diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/source.sha256 b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/source.sha256 new file mode 100644 index 00000000..0cd9a76f --- /dev/null +++ b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/source.sha256 @@ -0,0 +1,129 @@ +bb32a9d1fc9345ee10b604a2e0e6097c4264d8040247901bd626d2dad633720d docs/specs/compiler-languages/pbs/10. Memory and Lifetime Specification.md +c8ad4792299089eb74846a177dedb592a55e1161ca36fb3d3b4682b47a7453b6 docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md +ec3a04c5c732e08c956fba7a1c1913e4915ac9dda7d3452180ec79fcd4517ea6 docs/specs/compiler-languages/pbs/27. Core Sprite and Animation Specification.md +9d2721529fafb7b984e158cbed2211d4bdf9b9bc545dbbbc18553c0784aff4e2 docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md +8fae59383422256af30625a1debd8b9d3d06bf79de4b6054fd973826b9351204 docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md +837186551dabf59a829d141f76214800c8933e383da57a279842b7ccda40266e docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md +65b38a52baf784f28f19d0ef993565c028c3731044d7fadc06cb3f465d8823fe docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md +6251c7b245371677d9c3128ed105798a713065ebdb5b3362d1a24fc70a17c20f docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md +4b66f7067ad726857842bc840dde3ca6c86e5e6bf5ccc41bb016fca4b858e4f0 docs/specs/compiler-languages/pbs/README.md +f039d441eaba2d3de051cdd5ead730b3edada225f6022ff4d5f2e450048df08b docs/specs/compiler/18. Standard Library Surface Specification.md +1eef76bdc53e7b8121ff6357ecf7e91a2b278176e189d057d804eba9385a950d docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md +e683f2b322d51848d9bcd2c63b33d926e94cc27135d8763791e6b6262e8032ab docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md +ca0edb95fea030beaa9e7f20913c46eec9de3f204a0dadbfa31d916aa9522a21 docs/specs/packer/2. Workspace, Registry, and Asset Identity Specification.md +4f380e0b4361e3a52ce286832319bfac0d45e55fc7f9f9b197fb1c87d310493e docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md +3fa1b270d1b4e2a66d12ef6f3025161f3a2a3607baf50b191fd142cd322e5956 docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md +ca3c6005183161313d4371c788058cf4bc6a4eef9a085a55201c453a6893864d docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md +41881dae01a0420ef9f20aa555363e2b8a6b8b6cf4f7126157729b91704f2ba0 docs/specs/studio/12. Animation Authoring Specification.md +1007134a4e37e1070fb90cfb6fda79be2f60a252398c856f8e8a5c13984e40b9 docs/specs/studio/4. Assets Workspace Specification.md +c265f466573474fc5b769705d1e7b80831395635dbf9b74f87965d7b1a8f0e8f docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md +6821f65531e72dfdcd9945685c26af425b6c671b200193ded10a56735c09c02d docs/specs/studio/README.md +7d5951e493364a7815066e76799b93f6a6c614a76911758e937fb70b12e3154c prometeu-animation/build.gradle.kts +4a65d23e0a708337a1d79a8c857cdd074f05b76de11ab2929a6f0d890aac6d0e prometeu-animation/src/main/java/p/animation/AnimationCodec.java +fddda8ae3f78a32d62c5efd85539f5ffab904a1ddafaa17f2becf662510abcbc prometeu-animation/src/main/java/p/animation/AnimationDiagnostic.java +1664c83f83f6c56733545707185601d22de7bf5c2027f76d0ab18b2a61c355f2 prometeu-animation/src/main/java/p/animation/AnimationDocument.java +4857bd166d3758d0a8c49ad4963142eff3e4bf64178b8dab7747ddb99308d4c4 prometeu-animation/src/main/java/p/animation/AnimationOriginNavigation.java +f77ed5b4946fea3452275e0807b0d979519d92f706832f823ae8a460907d01a1 prometeu-animation/src/main/java/p/animation/AnimationRebind.java +d31acf93ecb83f9622966e1d361dc31ef6c366dc35dce3d8bff1a8d20f035150 prometeu-animation/src/main/java/p/animation/AnimationRevision.java +ce9bdadfe16f24fcae358d7de213a8c8450ca8a5e2ed45075c6f2f10bda0d983 prometeu-animation/src/main/java/p/animation/AnimationSource.java +1363b399ef7494abe88b3cb2a1e30d0815347501305558e72b1f4f56dc086bd8 prometeu-animation/src/main/java/p/animation/AnimationTimeline.java +57fcb4956030d63b74d0824e5fa35cdd033516c851ba9cde415201cfa51ebec7 prometeu-animation/src/main/java/p/animation/AnimationValidator.java +6fd1f8b203735769e3ec7a7e62240a41fa34a654a19c09151a11f5668953df66 prometeu-animation/src/main/java/p/animation/GlyphBankLayout.java +176f288b6ea3f984c52227b26264bcf69dbe4bb5535990aa9ef37cab48e8d742 prometeu-animation/src/main/java/p/animation/GlyphBankLayoutSource.java +30980f79ba7c1aeda8c7b7be728b14852320222243f962dcc02cf8e194b85689 prometeu-animation/src/test/java/p/animation/AnimationContractTest.java +843a4dfb03afa46905642c5055171606b65e46937d5bc428d503838f7827ab20 prometeu-app/build.gradle.kts +3cd71fdfcf8dfddf60eacca7b0caff08795ff00b55f7da80d400c57b4dc30ae2 prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +954626f88beaed539a60be0f9142b4e85ab14106a6baa42abccaefb7756c5352 prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java +a320b60885537e917bef66e34ed3cedea53fa1d1580d05fc38d0e9480f1d91a3 prometeu-app/src/main/java/p/studio/app/assets/PackerGlyphBankLayouts.java +b1692849f2af66faea261e4cc7e5b68baa15919811a29fb9092971389ad9ac1a prometeu-app/src/main/java/p/studio/app/compiler/CompilerBuildGatewayAdapter.java +0c258a15eb3f34aafed92d96a6a9fdf0e2356752836972c21248a8b3b2d1cb28 prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java +919e7bcbfaf98f2027291475afc39dc68e7e9b2a086edcfb3bc75f5866e94153 prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java +ed0975206ea18373f6e5f436d7f714c96e93bd728f941fc3548cd7739f5a0486 prometeu-app/src/main/java/p/studio/app/mcp/McpAnimationTools.java +86c74b1c1ea5bb74bfc032ff1bebede93e79770d0edb5e1e598856816b9b5d64 prometeu-app/src/main/resources/mcp/studio-tools-v1.json +4c6231869b9fec9827fa0cf8dcc08a9b45c4497268d57f98fcafd91da5865310 prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java +d696dbf3b86e0dfbb49aaf750d7fd31462d4cba8cba903c5fb9de0016121ec4d prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java +1ffbcb740b830a066f4ecb7a89ad780aee9c3bd96a33965eeb9b1947c4b2be67 prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledProbe.java +61cdc1867697dfe339c4e907f1bfec5873d1a71d93f2297c69994025d3db9d4c prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledRuntimeTest.java +56af831e13d28c8c59d4deb6d21fedef9d8225d96e6748bc56a3e8c98b51b82e prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java +f96ec4cac9d2d4f033ac4449679dae1582f0980b9755b833999641d815cb18f5 prometeu-app/src/test/java/p/studio/app/animation/AnimationProjectFixture.java +4a66af119ed6d27f6acf05746770aa78cd522aea15b8a0adce303fea5fbe8f69 prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java +c22b0666b7dbda7bb1aedc2688fe35e447a05008aa0726cabee70741b8c4e02c prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java +e4a5d6062e3436dad94907cf3afa1b6c569283858c71354d0e1aff19f444c627 prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java +631f454efb56a75ec39b7ea2c99cf48cb32bf12a7b73f25f397915ae20438697 prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java +dad477da094986d9157eaf305f1bf9e15a3cac82ecdcdedabc83074bd5305303 prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java +9d4fc89ca4817842ae795e9515e8836e95b99c508e2e3b5fb8c9f3a61e51229f prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java +018a70ad1fa3edaa971c760937e258fddac8c6ae1a36c9b55575186327f357fc prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java +2a9b6e71c29729060615c10a99acc85496f9920c3bee3017fb184a61bd93961c prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java +f328dccad9f040c84d769cdeffa5d8783b78e86664a4187ff5c23c7cf81b7978 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendLanguageService.java +ff57258886cff5b367fdb78ee9518188aa98daffd7d6af44536757d3ccfb7b8f prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsCallableSlotCounter.java +4365be38ea866eced4606fbcf53e61992355f6bbdd8398b5418a01b2e68b464c prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsStdlibConstruction.java +bae95724d6b31f5367e6bd9ca96a7da1805be8141d30d506686e7f9a988b0bbb prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java +73954236ba33bcbbdecf5f8f8b6c45dab8a7dd2488e032abd34a3c12cb0a659b prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java +0985dcd45f200a0eb24da602827482f90499f790dcaa52719dc769da3893f71d prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java +d37d6e6cea1090e90913689f28db54cb0cf24e497fc3663c7ea2dc64f6f3ee4e prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringContext.java +73f8bf2d22a11191f43c51691d820a606e48c0c0f4fc746ec8ebefec71bbc0f3 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringService.java +c64c11ffce06554da57861c373f81897739c9f93b05c8f8559e292b19d1233b5 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableStackAnalyzer.java +ce9ad71e884ad106719ddbbe1db99f183b8fba75db237af08e089e280fd2401f prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java +5c6777b8d57027b18f3c19133628335af3a76008f629b9e3b44b8e5fa9bd47c5 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java +b5cc039430efbfacdc3720f72495bb661e50d195fb520cbf6dab31445147c9a4 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java +061c248e8de616e3ce8412b76930744248b1fd36e59454a05b91185bc27be7df prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java +d35633448a3023f837c743d2c96cfc0ccb1df23f2956d0d5934dc1824c686fc6 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java +b65b02effea05dd9a10b32a9a03c9843a92c1ada9902ad19b14e0de7222cbb14 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsAnimationProjection.java +6965b8325f0b7da1a83f7581984b34ea00671d66085d3210488fb672941e390f prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java +4429e1dc0dfb27e1aa145011683c589b1a3f4502be1223ef03aa8b2cddc28f65 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsModuleAssemblyService.java +5907731d1a10036d50021fe8263c2e8f9f2b79d0fddfb9a70b2d8449b42aecbc prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/main.pbs +36e78b0dafd0a4e5f4b63499a5f197870d9abaa5a2c02364339ffde3a87c3862 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/mod.barrel +61b530fa321c3e69983c8c6e0a48503534a280a9d4b266cd1b62a5fe54d9d382 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/main.pbs +29c4ffff336a54ab874ed8dce996ebd877f7b3145cdf5844836bff9a2f3757f8 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/mod.barrel +c92f3ab13a0cd2cb2e2adba7b236ce1282b89733d3dde0b1e396da950a7b7552 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/composer/main.pbs +639beb705a61799351f22109b5356520498824f326ab1af1fd711daef4cdf641 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/ANIMATION.md +2567aca3b9e0a733871c2f736c7f0a4ce43415cf5b43dddfaf93963cd6db19c6 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/animation.pbs +be65d777f43e82312d565816442bbb565dd00c6005c606a11ced58dbe6dc6f97 prometeu-compiler/prometeu-build-pipeline/build.gradle.kts +f4ec6a28525d2493d6d160409437016bf8973cc2cc01a6fe072a364fe50c29c3 prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/models/BuilderPipelineContext.java +8d6e05a68ebb707442356b9b2975d80a412b6993fe62789c6cbbbc9243e732a3 prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/AssetSurfaceContextLoader.java +c9a0ee7309b022c872346a8d7125ac6d24fa77778b9ae2dbfbca003caf6d8213 prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/stages/FrontendPhasePipelineStage.java +9a76574ee95514c0bd69d1468f55216984dd57210efc2677798dfbb899f53b81 prometeu-compiler/prometeu-frontend-api/build.gradle.kts +bf4e92a43215d760967e476bf899d0cf9f42ab26ba74c0a4bcb40f22248c8788 prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/messages/FESurfaceContext.java +bc7d38ec152c1ff250d45d3eeab1b00fe9a9c83fc384599e0f9c0a161c654863 prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendSourceDocument.java +6ec24293d82e3606663acf993106a6275094c47be0da28d720762700a56373cf prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java +9bf8484492e08ff3f4839d7e8022e3737d85a2e663987187c86235406eba8ac5 prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java +2f391046cc51604d00a1876cdc99495421d9893a324bd8b2c28edf5d59853a9c prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/ExternalSourceRegistry.java +ec8702d093e5845b47312b65cab4421a632f9c57f075843e22570c91fff2365d prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/ExternalSourceLanguageServer.java +82fa22592d2a24a79745f08aae456682994a2994ad2957c66d5ac2d51cfd3d44 prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/PrometeuLanguageServer.java +404b12a9131b6aa1607cec4c81bda55e8a403db329494f1e9a386247d4236027 prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/ExternalSourceRegistryTest.java +13079954d52a51b77880ee5988349323eb427b09001f47d1a48f0fa7532aa0c6 prometeu-packer/prometeu-packer-api/src/main/java/p/packer/PackerWorkspaceService.java +c35b1ea511199fc91dab4a7401e37d8a91c0a7debcdfe2b516194fae26ffadb1 prometeu-packer/prometeu-packer-api/src/main/java/p/packer/dtos/PackerGlyphBankLayoutDTO.java +d2659d7d9627557e907dd8e77d490c63ea72f2b3e33252601b43c66be78b953a prometeu-packer/prometeu-packer-api/src/main/java/p/packer/messages/GetGlyphBankLayoutRequest.java +8b686dd77199cf275ced2101c6351bec4876ec1dfc0dbf723d3c826e68d9a1b4 prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerAbstractBankWalker.java +276d878ce8e864e4d3badbc54bae754935d7ff565f72b150d76b34be443e0a22 prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java +af1a00db5a065f178fe3f09c487cc8e7f5bfe3da20162ea4584740e1e090a3ce prometeu-studio-api/build.gradle.kts +c9570929f5b3b7e99a42ba7f1784f763a4f35c9896bd3998385a3a3a1e8562fd prometeu-studio-api/src/main/java/p/studio/api/assets/AssetSummary.java +5581216eb1e3fbc09651120b889f75ec6619e6f4b0489bb0f6dfdd91794d0347 prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationService.java +fc5542118b270ada7c6ea383187028af87920192d7358b6a011adddf114c3af2 prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationTasks.java +4435e427529b0a7ebef4e98dc870e7598ec5d647578b9c3cecfcee2a717bada8 prometeu-studio-api/src/main/java/p/studio/api/assets/workspace/AssetWorkspaceAssetSummary.java +a8e67f1a3877be23f59c191eb40fbb2036088e53836e8dc13c2c99a43778fdf8 prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java +455af9c0f133ab62a70f30758208afd337a202c7a92b8c4064cc1c977ecd39a8 prometeu-studio-core/src/main/java/p/studio/core/assets/AnimationOperations.java +4e3db0ca8c1b47ac2f8d253188fb93a7d3c6fdccf8f755ab898b3f41181c27f6 prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java +7cd160b03ca0ef1892ed1c8ac1713ab541a4691bdc66680514907ecb0b260ea4 prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetDetails.java +420a53d8a86c6e3e2d66022f03a616396fa863e2632be4346d470d9808d4e17f prometeu-studio-core/src/main/java/p/studio/core/assets/animation/AnimationPreviewRenderer.java +f19f1fb878eeeb5b4167602520042e271f9102c0aef796e7ffe0c5590d88f52a prometeu-studio-core/src/main/java/p/studio/core/assets/animation/DefaultAnimationService.java +aaddecc065e53d8942e594cc2e3efe969988084aa7ca30906acfa5f730359c08 prometeu-studio-core/src/main/java/p/studio/core/assets/animation/ManualAnimationService.java +678c32d2cbd9f7d4a31737263fa1f2e56c7bfe4b83e168d9a79448a4c7906761 prometeu-studio-core/src/main/java/p/studio/core/session/TaskAnimationService.java +cb5fa3bd1d1384145e0cba59bdf18ad8f288949526ec6d00936089ba5a695a0b prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/events/StudioAnimationOriginRequestedEvent.java +a06eaf5fdf327388ca00073e33deb7751bd97a766161d594d51c7180799f5e04 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java +0f928aaf0e3d6cdc5224e7373ef3afa951d810ee8803b0632d07c56fd997d7ca prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java +be51cd5bb0e91986578d4a33c510f1728f66f31011f89ce43c05963f9c5239c1 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java +b95ec37e9554f5fc4f6d48dc5cb13357b36cdc476341898c69ed3ac78d5babd5 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java +bdbb2d8fcab150c398da0a41dec219f97f6b4329d5676b15e01ad3cf8ae6080a prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetListMappings.java +4701d71fc568480a3c204d117a321cd1e398d4b29bdcc4b498396bbe9343d288 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/animation/AnimationEditorControl.java +0242e87b38301dcd768b604747c368893317b3efe228f5125c821bba933b5e47 settings.gradle.kts +625305ac75a2319dd3a1cee9db450bbeb31a60d85a35b9fc03afbd0ad3441e60 tools/pbx-conformance/README.md +6c1b543960bd0ecabcd4cf89ef3cb6646df2b909cb2cf9e6965c59225a0e1a3f tools/pbx-conformance/animation.rs +51bbebb411078bf4d8336e28d35e438aba49c47deebb3ffbd55859fbda80c432 tools/pbx-conformance/main.rs +7829e50105fc9bc3ced056aa8a34714a644908483532f154a437fa41928122ab tools/pbx-conformance/result.rs +29a6623d2ba1ff3d3e1b0017a2fc10cbb790dfc7126dabf999c75250d9d9ce30 tools/pbx-conformance/run.py +ff7669746d0cb7167a84e3e383d3570968888bbedde812a79a6aaefac2a74f7e tools/vscode-extension/out/extension.js +2ba64626f79b7fe8abeb260ce8572dfd8bb1f4dfcbe8c65e5eaf2e512fecbfe7 tools/vscode-extension/out/externalSources.js +b4a1e93075da5bb89d37d5196110a4aa0ce9070f55692827eef70e9d6d9d01d1 tools/vscode-extension/package.json +2e7babd6f2272c0f96aa3d65bf4bf940dd6e2a4e5cd91f149d7d17ef40b22039 tools/vscode-extension/src/extension.ts +3fec63d03afe610d4a5d0eb7c9ff5758af5bec076d4cd01adbb8da6ba1f0fbec tools/vscode-extension/src/externalSources.ts diff --git a/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/workflow.txt b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/workflow.txt new file mode 100644 index 00000000..f234bc9c --- /dev/null +++ b/discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/workflow.txt @@ -0,0 +1,18 @@ +$ discussion mark-plan PLN-0162 done +marked plan PLN-0162 done for DSC-0098 + +$ discussion housekeep DSC-0098 --lesson discussion/lessons/DSC-0098-pbs-core-sprite-animation/LSN-0100-sprite-animation-and-shared-authoring.md +housekept DSC-0098 +removed workflow artifacts: 3 +registered lesson: LSN-0100 + +$ discussion validate +validation passed + +$ discussion inspect DSC-0098 +DSC-0098 done pbs-core-sprite-animation +PBS Core Sprite and Animation +tags: compiler, pbs, core, stdlib, sprites, animation + +lessons: + - LSN-0100 done exists /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/studio/discussion/lessons/DSC-0098-pbs-core-sprite-animation/LSN-0100-sprite-animation-and-shared-authoring.md diff --git a/docs/specs/compiler-languages/pbs/10. Memory and Lifetime Specification.md b/docs/specs/compiler-languages/pbs/10. Memory and Lifetime Specification.md index 703a6d2e..7f4ce360 100644 --- a/docs/specs/compiler-languages/pbs/10. Memory and Lifetime Specification.md +++ b/docs/specs/compiler-languages/pbs/10. Memory and Lifetime Specification.md @@ -329,3 +329,10 @@ The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Sp defines the complete type, optional-flow and storage contract. This chapter supplies shared reachability and ownership rules; Array storage and complete-group packing are defined by that owner. + + +## Animation ownership and allocation + +Every AnimatorBuilder.build materializes independent private clips, frames and backing. Immutable strings retain normal sharing; assignment retains ordinary identity/aliasing. Final frame links may form private cycles and must remain rooted/reclaimable under existing GC. After construction, executed advance and sprite paths allocate no heap objects, including negative/overflow error returns. + +See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations. diff --git a/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md b/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md index 02847fec..703cd26d 100644 --- a/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md +++ b/docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md @@ -291,3 +291,10 @@ The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specific defines the additional [MemcardBoot] marker, exact signature, neutral once-only bootstrap, project identity/slot validation and complete installed mem ABI. Its requirements apply in addition to this chapter; pause/resume remain independent. + + +## Executable result return groups + +Emit an existing typed return group: Int32 status 0 for success or canonical nominal error case index 1..N, followed by the complete plain payload group. Unit result has only status. Error payloads use admitted typed defaults, including nullable references, without constructing payload objects. Preserve typed reference/builtin/Fn/trait groups across signatures, Registry, direct/contract calls, branches and discard. Propagation fills the enclosing inactive payload and returns immediately; handle recovers locally or remaps outward. The common backend consumes neutral typed IR with no PBS branches. + +See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations. diff --git a/docs/specs/compiler-languages/pbs/27. Core Sprite and Animation Specification.md b/docs/specs/compiler-languages/pbs/27. Core Sprite and Animation Specification.md new file mode 100644 index 00000000..07e84019 --- /dev/null +++ b/docs/specs/compiler-languages/pbs/27. Core Sprite and Animation Specification.md @@ -0,0 +1,180 @@ +# Core Sprite and Animation Specification + +Status: Normative v1. Owner: compiler/pbs. Applies to Game stdlib major 1. + +## Purpose and boundaries + +The core provides ordinary executable PBS structs, not VM builtin animation types. +The caller owns bank loading, replacement and lifetime. Core validates structural +ranges and arithmetic; glyph existence and asset-to-slot correspondence belong to +the asset-aware caller. Sprite, internal clips and Animator store neither position +nor palette. Each frame is one glyph, and frame glyph IDs need not be contiguous. + +The public API, private construction and executable result rules below are +normative. Finalized clips/frames are private and immutable after publication. + +## Core API and ownership + +```pbs +// @core:sprite exports Sprite, SpriteView, SpriteError and: +fn make_sprite(bank_id: int, glyph_id: int) -> result Sprite; +// Sprite and SpriteView: +fn sprite() -> (bank_id: int, glyph_id: int); + +// @core:animation exports Animator, AnimatorBuilder, AnimationError and: +declare enum PlaybackMode(Once = 0, Loop = 1); +declare enum PlaybackState(Stopped = 0, Playing = 1, Paused = 2, Finished = 3); +fn animator_builder(bank_id: int, initial_clip: str) -> result AnimatorBuilder; + +// AnimatorBuilder: +fn begin_clip(name: str, mode: PlaybackMode) -> result; +fn add_frame(glyph_id: int, duration_ticks: long) -> result; +fn end_clip() -> result; +fn discard_clip() -> result; +fn remove_clip(name: str) -> result; +fn build() -> result Animator; + +// Animator implements SpriteView: +fn sprite() -> (bank_id: int, glyph_id: int); +fn state() -> PlaybackState; +fn active_clip() -> str; +fn clip_count() -> long; +fn frame_count(name: str) -> result long; +fn frame_at(name: str, index: long) -> result (glyph_id: int, duration_ticks: long); +fn select(name: str) -> result; +fn play(name: str) -> result; +fn pause() -> void; +fn resume() -> void; +fn stop() -> void; +fn restart() -> void; +fn advance(ticks: int) -> result; +``` + +Factories are the public construction path. `[StdlibFactoryOnly]` restricts +positional/named `new` to the type's declaring module, using trusted stdlib origin. +Game code cannot forge that metadata or evade it by alias/reexport. Types remain +ordinary PBS structs. Completion/signature help must expose usable factories. +Admit the reserved attribute only on structs from trusted stdlib origin; it is +not a game-defined annotation. Use `declare contract` and `implements` in each +concrete type's module, preserving the existing PBS contract ownership rules. +Clip/frame types and backing never escape. Sprite and Animator implement +SpriteView with joint bank/glyph query, no new Sprite or effects per read. + +Banks are int 0..255, glyphs int 0..65535, durations long 1..LONG_MAX, +LONG_MAX=9223372036854775807. Clip totals must not exceed LONG_MAX. Clip/frame +counts are long bounded by 4294967295; final clips/animator are nonempty. Frame +indices are zero-based longs. Tick input remains int; negative is an error, +zero has no effect and positive values are at most 2147483647. + +SpriteError cases are invalid_bank, invalid_glyph. AnimationError cases, in order: +invalid_bank, invalid_name, duplicate_clip, clip_already_open, no_open_clip, +empty_clip, unfinished_clip, empty_animator, initial_clip_missing, unknown_clip, +invalid_glyph, invalid_duration, invalid_ticks, index_out_of_range, limit_exceeded, +overflow. Names are nonempty exact UTF-8 strings without implicit normalization. + +Builder bank/initial name are fixed; it allows one open clip. end_clip rejects an +empty open clip without closing it; discard_clip discards only the open clip. +remove_clip requires none open. build checks open clip, empty collection, missing +initial in that order and produces Stopped at the initial clip's first frame. +Reuse must create private clips/frames for every animator. Builder edits leave +published animators unchanged. Only immutable strings may retain ordinary sharing. +No clone or external Clip attachment exists. Assignment preserves PBS identity. + +Factories check bank ranges and required names before allocation; make_sprite also +checks glyph range. begin_clip requires no open clip and an unused, valid name; +add_frame requires an open clip and valid glyph/duration. For assembly operations, +check state preconditions before arguments, then names, ranges, counts and sums in +that order. Check `total > LONG_MAX - duration` before addition. Inspection checks +clip name before frame index. All recoverable failures preserve the prior draft +or animator, including failed end_clip, unknown remove/select/play and build after +removing the initial clip. Prepare candidate storage before publishing mutations. + +### Executable result contract + +Use the existing VM return group: first an Int32 status (0 for success, 1..N in +canonical error declaration order), followed by the complete typed plain-return +payload group. Preserve reference, builtin, function and trait-pair shapes and +nominal error identity in analysis/IR; matching slot counts do not establish type +identity. Unit result contains only status. Inactive error payload slots use +runtime-admitted typed defaults, including nullable reference defaults; they must +never be read as success values or require constructing payload objects. + +`!` evaluates its operand once and immediately propagates the same error, filling +the enclosing function's inactive payload correctly even when its shape differs. +`handle` evaluates once and executes only the selected arm, preserving success, +local recovery and error remapping. Neither operation catches VM traps. Apply the +same group consistently to signatures, Registry metadata, imports/aliases, direct +and contract calls, branches and discarded results. Unit error paths must not use +the existing allocating default-holder helpers. Keep `Fn(...) -> TypeRef` grammar +and reject conversion of a result-effect function to plain Fn; successful Fn +payloads retain their ordinary typed representation. + +### Playback contract + +| Operation | State and cursor behavior | +| --- | --- | +| select(name) | From any state: Stopped at frame zero, zero phase, including the current name. | +| play(name) | From any state: Playing at frame zero, zero phase, including the current name. | +| pause() | Playing -> Paused; other states unchanged. Preserve cursor/phase. | +| resume() | Paused -> Playing; other states unchanged, including Finished. | +| stop() | From any state: Stopped/reset on selected clip. | +| restart() | From any state: Playing/reset on selected clip. | +| advance(ticks) | Reject negative in every state; zero is a no-op; positive advances only Playing. | + +Check phase > LONG_MAX - ticks before addition; overflow leaves the animator +unchanged. Loop uses the remainder after dividing the new phase by total duration. +Once finishes only after consuming the last frame's full duration, retains its +image and clamps phase to total. Frame intervals are [start,end). Seek traverses +at most one clip's frame count, never each tick or each skipped loop. Failed +selection does not change anything; clips retain no suspended progress. + +Use private finalized frame links with long duration/cumulative end, tail linking +to head, and direct selected clip/frame references. Prepare links before publishing +the animator. Advance and sprite must not allocate, including unit error returns; +array/optional wrappers must not be introduced on this path. All computations +precede visible state publication. VM resource/trap faults are not modeled domain +errors and carry no new rollback/safe-retry promise. + + +## External composition + +The caller queries SpriteView and invokes +`Composer.emit_sprite(glyph_id, palette_id, x, y, layer, bank_id, flip_x, flip_y, priority) -> int`. +Preserve host identity `(composer, emit_sprite, 1)` and capability `composer`. +Composer does not depend on core Sprite/Animator. Palette applies only to the +current emission; query or emission does not advance playback. + +Blitable and a draw manager are separate work. Entities, gameplay state machines, +events, ping-pong, clones, collision, multi-glyph frames and runtime animation +resources are outside this contract. There is no new opcode, host ABI, Registry +category or runtime metadata format. + +## Authored factory and conformance + +[Animation Authoring](../../studio/12.%20Animation%20Authoring%20Specification.md) +defines canonical JSON, binding drift, shared validation and generated sources. +Generated factories use the same builder and return effect as direct PBS code. +Factories construct fresh private clips; they never load banks or call the host. + +Conformance must execute ordinary and optimized PBX with the production loader/VM +in dev/release, compare shared preview against native playback, and count executed +heap-allocation instructions for advance/sprite after construction, including +negative/overflow errors. Zero is mandatory. Resource/trap failures are not domain +errors and do not imply rollback or safe retry. A failure to establish zero +allocations requires an explicitly authorized decision revision. + +Examples must call play on an action transition and advance for continuity; +calling play/select every frame resets playback every frame. + +## Related specifications + +See chapters 3/4 for source admission, 5/8 for module resolution/distribution, +9/10 for result/identity/lifetime and 13 for typed executable lowering. + + +## Native Composer status adaptation + +The public Composer facade retains its existing int status and nine arguments. +The private LowComposer declaration uses the native Int64 status carrier and the +facade explicitly narrows it to int. This is a PBS adapter conversion using existing +intrinsics; host identity, capability, slot count and runtime behavior are unchanged. diff --git a/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md b/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md index e27f9fee..22fb1d9c 100644 --- a/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md +++ b/docs/specs/compiler-languages/pbs/3. Core Syntax Specification.md @@ -1243,3 +1243,10 @@ may accompany them. Targets MUST be nongeneric top-level userland functions; methods, lambdas, host/interface declarations and other declaration kinds are invalid targets. Function names are arbitrary and do not select runtime roles. PBS exposes no sync statement, lifecycle syscall or termination marker. + + +## Stdlib factory-only construction + +`[StdlibFactoryOnly]` is reserved metadata on trusted stdlib structs. Both positional and named `new` are permitted only in the canonical declaring module. Imports, aliases and reexports preserve this admission boundary. Game declarations cannot forge the attribute. Public construction uses the declared recoverable factories. The existing result return-effect and `Fn(...) -> TypeRef` grammar remain unchanged. + +See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations. diff --git a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md index c42760b1..0b315b33 100644 --- a/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md +++ b/docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md @@ -866,3 +866,10 @@ The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specific defines the additional [MemcardBoot] marker, exact signature, neutral once-only bootstrap, project identity/slot validation and complete installed mem ABI. Its requirements apply in addition to this chapter; pause/resume remain independent. + + +## Factory admission and typed result identity + +Factory-only admission uses trusted canonical declaration origin, never visible spelling or slot count. Reject external positional/named construction and forged metadata; omit prohibited constructors from completion/signature help and expose public factories. Result error identity is nominal through imports and aliases; a result-effect function cannot be converted to plain Fn. + +See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations. diff --git a/docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md b/docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md index 396b2881..28d5b333 100644 --- a/docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md +++ b/docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md @@ -578,3 +578,10 @@ The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specific defines the additional [MemcardBoot] marker, exact signature, neutral once-only bootstrap, project identity/slot validation and complete installed mem ABI. Its requirements apply in addition to this chapter; pause/resume remain independent. + + +## Core animation and generated module resolution + +Game stdlib 1 distributes executable ordinary PBS modules `@core:sprite` and `@core:animation`. Private helpers retain definition-scoped resolution and trusted origin. Reserve `generated/animations` for project-owned virtual modules `@:generated/animations/b_`; physical collisions are diagnostics. Only registered build-included banks publish factories; invalid included definitions block analysis/build. + +See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations. diff --git a/docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md b/docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md index dd84a94d..770b368f 100644 --- a/docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md +++ b/docs/specs/compiler-languages/pbs/8. Stdlib Environment Packaging and Loading Specification.md @@ -366,3 +366,10 @@ documents with revision-consistent text, ranges and frontend semantic context. Hover and continued definition use that retained context. Compilation, module admission, ABI and linking rules are unchanged. See Compiler Spec 23 §8.3 and Studio Spec 11 for the consumer protocol and atomic write restrictions (DEC-0062). + + +## Executable core animation distribution + +Package ordinary PBS bodies, barrels, helpers, documentation and examples for core sprite/animation in stdlib major 1. Compile these bodies through the same executable frontend path used by collections. Restrictions specific to SDK service bodies do not apply to all stdlib functions/structs. Installed consumers must not depend on a source checkout. + +See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations. diff --git a/docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md b/docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md index 37cc9bc0..5c7b9589 100644 --- a/docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md +++ b/docs/specs/compiler-languages/pbs/9. Dynamic Semantics Specification.md @@ -420,3 +420,10 @@ The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specific defines the additional [MemcardBoot] marker, exact signature, neutral once-only bootstrap, project identity/slot validation and complete installed mem ABI. Its requirements apply in addition to this chapter; pause/resume remain independent. + + +## Result groups and explicit animation time + +A result success evaluates its payload once. Propagation and handle evaluate their operand once; only the selected recovery arm runs. Error remapping returns the enclosing error; traps are not caught. Animation advances only through explicit ticks. Queries/emissions are pure with respect to playback; repeated play/select resets the selected clip even when its name is unchanged. + +See [Core Sprite and Animation](27.%20Core%20Sprite%20and%20Animation%20Specification.md) for the complete API, ranges, state table and conformance obligations. diff --git a/docs/specs/compiler-languages/pbs/README.md b/docs/specs/compiler-languages/pbs/README.md index ac5499f8..52ccad0f 100644 --- a/docs/specs/compiler-languages/pbs/README.md +++ b/docs/specs/compiler-languages/pbs/README.md @@ -204,3 +204,5 @@ The internal resource path is `pbs-knowledge/specs/.md`; reference clients resolve IDs through the catalog instead of constructing paths. - [Memcard Bootstrap and SDK](<26. Memcard Bootstrap and SDK Specification.md>): opt-in persistence producer and runtime-consumer boundaries. + +- [Sprite and animation contract](27.%20Core%20Sprite%20and%20Animation%20Specification.md) — core API, explicit ticks, shared bank authoring and generated factories. diff --git a/docs/specs/compiler/18. Standard Library Surface Specification.md b/docs/specs/compiler/18. Standard Library Surface Specification.md index 78729f4b..7d838f64 100644 --- a/docs/specs/compiler/18. Standard Library Surface Specification.md +++ b/docs/specs/compiler/18. Standard Library Surface Specification.md @@ -252,3 +252,10 @@ This specification MUST NOT: PBS shells MUST repeat identities already published by the runtime catalogs named in section 3. + + +## Animation integration contract + +Executable library bodies retain frontend-owned source semantics. The common pipeline preserves ordered typed return groups, including a frontend status plus its full payload; it must not infer nominal identity from physical width or add PBS-specific branches. These groups use existing Registry/VM categories and host ABI. + +See the [complete animation contract](../compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md). diff --git a/docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md b/docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md index fcba4fd9..51f7f2a2 100644 --- a/docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md +++ b/docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md @@ -301,3 +301,10 @@ assigns other IDs to hooks. PBX emission consumes the existing role byte and validates final targets, without role inference from function names or frontend ASTs. Synthetic Init/Frame assembly is unchanged. FRAME_SYNC fixtures used to test controlled-call rejection do not introduce frontend sync syntax. + + +## Animation integration contract + +Executable library bodies retain frontend-owned source semantics. The common pipeline preserves ordered typed return groups, including a frontend status plus its full payload; it must not infer nominal identity from physical width or add PBS-specific branches. These groups use existing Registry/VM categories and host ABI. + +See the [complete animation contract](../compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md). diff --git a/docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md b/docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md index addf8041..27e45115 100644 --- a/docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md +++ b/docs/specs/compiler/25. Typed Registry and PBX v0 Specification.md @@ -307,3 +307,10 @@ slots 1..64, capability memcard, unique role 3 and the boundary before launch. This is distinct from a direct CALL to the hook. Host storage and headless transport remain runtime-owned and absent from the common IR. See the PBS [producer contract](<../compiler-languages/pbs/26. Memcard Bootstrap and SDK Specification.md>). + + +## Animation integration contract + +Executable library bodies retain frontend-owned source semantics. The common pipeline preserves ordered typed return groups, including a frontend status plus its full payload; it must not infer nominal identity from physical width or add PBS-specific branches. These groups use existing Registry/VM categories and host ABI. + +See the [complete animation contract](../compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md). diff --git a/docs/specs/packer/2. Workspace, Registry, and Asset Identity Specification.md b/docs/specs/packer/2. Workspace, Registry, and Asset Identity Specification.md index 50e0c35b..2b18e9c8 100644 --- a/docs/specs/packer/2. Workspace, Registry, and Asset Identity Specification.md +++ b/docs/specs/packer/2. Workspace, Registry, and Asset Identity Specification.md @@ -160,3 +160,10 @@ This specification is complete enough when: - registered asset boundaries are unambiguous; - registry authority is explicit; - identity survives relocation without ambiguity. + + +## Animation integration contract + +Expose the effective selected glyph layout through Packer API: asset UUID and stable artifact ID to glyph ID/fingerprint mapping from the same composition used for pack. Exclude `animations.studio.json` from glyph candidates and binary payload. The sidecar references existing identities and does not create an asset type, header or animation binary format. Reorder/removal/content drift requires explicit revision-checked rebind by authoring services; never retarget by path/order. + +See the [complete animation contract](../studio/12.%20Animation%20Authoring%20Specification.md). diff --git a/docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md b/docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md index ca4a2a09..b7a2a97c 100644 --- a/docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md +++ b/docs/specs/packer/3. Asset Declaration and Virtual Asset Contract Specification.md @@ -250,3 +250,10 @@ This specification is complete enough when: - the common `asset.json` shape is stable; - raw and virtual assets share a coherent baseline contract; - format-specific specs can build on it cleanly. + + +## Animation integration contract + +Expose the effective selected glyph layout through Packer API: asset UUID and stable artifact ID to glyph ID/fingerprint mapping from the same composition used for pack. Exclude `animations.studio.json` from glyph candidates and binary payload. The sidecar references existing identities and does not create an asset type, header or animation binary format. Reorder/removal/content drift requires explicit revision-checked rebind by authoring services; never retarget by path/order. + +See the [complete animation contract](../studio/12.%20Animation%20Authoring%20Specification.md). diff --git a/docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md b/docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md index b4f9cd80..cbd25e6b 100644 --- a/docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md +++ b/docs/specs/packer/4. Build Artifacts and Deterministic Packing Specification.md @@ -307,3 +307,10 @@ This specification is complete enough when: - runtime-facing artifact authority is explicit; - companion artifacts are bounded; - emitted ordering and header behavior are deterministic. + + +## Animation integration contract + +Expose the effective selected glyph layout through Packer API: asset UUID and stable artifact ID to glyph ID/fingerprint mapping from the same composition used for pack. Exclude `animations.studio.json` from glyph candidates and binary payload. The sidecar references existing identities and does not create an asset type, header or animation binary format. Reorder/removal/content drift requires explicit revision-checked rebind by authoring services; never retarget by path/order. + +See the [complete animation contract](../studio/12.%20Animation%20Authoring%20Specification.md). diff --git a/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md b/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md index 352483b6..695ccb9a 100644 --- a/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md +++ b/docs/specs/studio/11. MCP Tools and Project Knowledge Contract.md @@ -631,3 +631,10 @@ per-project desktop Run is required. Explicitly disabled integration MUST remain disabled. Preparation failure MUST remain visible in DEV readiness without blocking project use. Opening MUST NOT publish credentials or grant/acquire agent control. The coding client continues to own its configured stdio process and initial trust. + + +## Animation integration contract + +Glyph-bank animation authoring, generated-source navigation, strict task-scoped MCP tools and preview use the shared animation service and validation contract. UI/MCP preserve project authority, expected revisions, conflict/cancellation/revocation and document handoff. Persist only the canonical animation sidecar; keep generated PBS read-only and neutral services independent of JavaFX/transports. + +See the [complete animation contract](12.%20Animation%20Authoring%20Specification.md). diff --git a/docs/specs/studio/12. Animation Authoring Specification.md b/docs/specs/studio/12. Animation Authoring Specification.md new file mode 100644 index 00000000..63ef0377 --- /dev/null +++ b/docs/specs/studio/12. Animation Authoring Specification.md @@ -0,0 +1,142 @@ +# Animation Authoring Specification + +Status: Normative v1. Owner: studio. PBS projection owner: compiler/pbs. +Packer owns registered assets, composition, effective glyph indices and fingerprints. + +## Purpose + +JavaFX, AI tools and compiler consumers share one versioned editorial document, +validator and bank-layout identity contract. This sidecar is neither a runtime +asset nor generated editable PBS. The entire authoring/projection contract is +specified below. + +## Canonical document and services + +Each registered glyph bank can contain animations.studio.json, a JSON UTF-8 +sidecar distinct from asset.json and studio.asset.json. Its strict schema is: + +```json +{ + "schema_version": 1, + "bank_asset_uuid": "", + "bindings": [{"artifact_id": "", "glyph_id": 7, + "fingerprint": ""}], + "animators": [{"id": "hero", "initial_clip": "idle", "clips": [ + {"name": "idle", "mode": "loop", "frames": [ + {"artifact_id": "", "duration_ticks": 4} + ]} + ]}] +} +``` + +Animator IDs are unique PBS identifiers matching [A-Za-z_][A-Za-z0-9_]*. Modes +are once/loop; frame order matters. Each animator has nonempty named clips; +zero animator definitions is allowed. Decode long integers exactly. No palette, +position or runtime bank slot is stored. Unknown fields/versions and malformed +or duplicate bindings/JSON keys are errors, not fallback triggers. + +Every referenced artifact must match the containing bank UUID and Packer's current +effective glyph ID/fingerprint. Reordering, removal and content replacement produce +blocking drift diagnostics. Explicit prepare/apply rebind presents old/new bindings +and affected frames, validates the result and requires the expected revision. +Never silently retarget by list order or path. Save validates the whole candidate +against the current snapshot and uses a revision check plus atomic replacement; +failed validation/conflict preserves the canonical file and editable draft. +Perform revision verification and publication under the same project exclusion; +replace atomically within the same filesystem. Read/validate may expose an invalid +document with diagnostics for repair; preview/build/projection must not fall back +to an older valid document or another schema version. + +The new neutral prometeu-animation library (p.animation) owns immutable DTOs, +strict codec, shared validator, revisions and editorial preview timeline. It has +no JavaFX/Spring/compiler/concrete-packer dependency. Packer exposes effective +layout snapshots, and app supplies the neutral GlyphBankLayoutSource port. Both +Studio services and the build context loader use this shared validator. A build +with included definitions but no configured resolver fails explicitly. Existing +projects without definitions retain an empty context and compatible entry points. + +FESurfaceContext carries language-neutral validated snapshots; PBS alone emits +virtual modules at @:generated/animations/b_. +Factories are create_(bank_id: int) -> result Animator. +Reserve generated/animations and reject physical-module collisions. Only registered, +build-included banks publish factories. Invalid included definitions block build; +never reuse stale generated text. Sort factories by ID, preserve clip/frame order, +escape PBS literals and exclude timestamps/absolute paths. Keep generated modules +read-only through FrontendSourceDocument and revision-scoped ExternalSourceRegistry +URIs, with generated spans mapped to original JSON fields. No generated source +becomes a second editable persistence surface. +Generated revision includes the document, resolved bindings and generator version. +Invalidate old origins after changes/reconnect, reject generated save/rename, and +let the UI open the original JSON field through the authoring service. + +Studio API/core provides list/read, draft validation, save/delete, prepare/apply +rebind and preview. JavaFX provides complete animator/clip/frame authoring, initial +clip/mode, durations, ordering, diagnostics, save and drift repair. Preview has +play/pause, explicit ticks and palette input. Shared neutral rendering returns +canonical image plus observed bank/glyph/state/ticks; its timeline must match PBS +native execution. No palette/position is persisted in the animation definition. + +MCP adds task-authorized studio_animation_query (list/get/validate/preview) and +studio_animation_update (save/delete/prepare_rebind/apply_rebind), with strict +schemas, expected revisions and the same services as UI. Reuse existing authority, +operations, cancellation, revocation, conflict handling and document handoff. + +Both tools take projectRoot, taskId and operation, plus these exact domain fields: + +| Operation | Fields and behavior | +| --- | --- | +| query/list | Optional assetUuid filter; project definitions/diagnostics. | +| query/get | assetUuid; current document, revision, diagnostics. | +| query/validate | assetUuid, optional candidate document; no persistence. | +| query/preview | assetUuid, animatorId, clipName, nonnegative long elapsedTicks, paletteId, optional candidate document; sample from clip start. | +| update/save | assetUuid, expectedRevision, complete document; explicit null revision only for create, never overwrite an existing file on create. | +| update/delete | assetUuid, expectedRevision, animatorId; preserve other definitions. | +| update/prepare_rebind | assetUuid, expectedRevision; return diff, candidate document/hash and bank snapshot revision, without writing. | +| update/apply_rebind | assetUuid, expectedRevision, document, proposalHash, expectedBankRevision; validate the same proposed binding-only change against the current bank. | + +Reject fields belonging to a different operation. Use the existing typed result +envelope and image contract. Proposal hashes correlate content, not a new grant or +approval workflow. UI autoplay schedules explicit tick updates with a transient +preview rate; preview never persists an animation clock. + + +## Persistence and authority + +Operations use project identity, asset UUID, animator ID and expected revision; +arbitrary caller-provided file paths are not definition addresses. Resolve authority +before cache lookup. Manual, Agent and Debug use existing project exclusion, +cancellation/revocation and document handoff; no parallel grant or approval flow +is introduced. Save validates the whole document against the current layout, +checks expected revision under project exclusion and atomically replaces the file +on the same filesystem. Conflict or recoverable failure preserves canonical bytes +and the editable draft. + +Rebind is the only binding migration operation: preparation returns old/new IDs, +fingerprints and affected frames without persisting; application validates the +same proposal hash, document revision and bank revision before replacement. +Read, preview, analysis and build never silently repair or reuse stale sources. + +## Preview and UI + +The editor integrates glyph-bank details and supports create/rename/delete of +animators and clips, initial-clip/mode selection, frame addition/removal/reordering, +exact long-duration entry, diagnostics, save conflicts and explicit drift repair. +Palette and position are transient viewing inputs. Play schedules explicit ticks +using a transient preview rate; no clock is persisted in animation definitions. +The renderer returns canonical pixels and observed bank/glyph/state/ticks without +JavaFX and must reject invalid bank/references instead of simulating success. + +The timeline follows the complete state/interval table in +[Core Sprite and Animation](../compiler-languages/pbs/27.%20Core%20Sprite%20and%20Animation%20Specification.md). +Production-native conformance must compare those observations for identical input +timelines, direct/generated factories and both producer/runtime profiles. + +## Dependencies and distribution + +`prometeu-animation` (`p.animation`) contains immutable DTOs, strict JSON codec, +structural/snapshot validation, revisions and preview timeline. It depends on no +JavaFX, Spring, HTTP, compiler or concrete Packer implementation. Studio core +orchestrates persistence/layout/rendering; app composes the Packer API adapter. +PBS alone generates PBS source; compiler/backend stay independent of Studio core. + +Installed references, examples and MCP schemas must expose this same contract. diff --git a/docs/specs/studio/4. Assets Workspace Specification.md b/docs/specs/studio/4. Assets Workspace Specification.md index bc36e75f..9cf0d621 100644 --- a/docs/specs/studio/4. Assets Workspace Specification.md +++ b/docs/specs/studio/4. Assets Workspace Specification.md @@ -489,3 +489,10 @@ This specification is satisfied when the Studio `Assets` workspace: - stages sensitive mutations through preview-first flows; - proves the Studio event-driven workspace framework through lifecycle-managed local ownership; - and behaves as a didactic helper for the packer model. + + +## Animation integration contract + +Glyph-bank animation authoring, generated-source navigation, strict task-scoped MCP tools and preview use the shared animation service and validation contract. UI/MCP preserve project authority, expected revisions, conflict/cancellation/revocation and document handoff. Persist only the canonical animation sidecar; keep generated PBS read-only and neutral services independent of JavaFX/transports. + +See the [complete animation contract](12.%20Animation%20Authoring%20Specification.md). diff --git a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md index d9d220da..73d4256b 100644 --- a/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md +++ b/docs/specs/studio/9. Studio Core and Adapter Architecture Specification.md @@ -192,3 +192,10 @@ shutdown through those ports. Application infrastructure owns credentials, file locks/atomic discovery, HTTP identity checks, TOML preparation and managed installation/runtime packaging. JavaFX consumes neutral status and actions only. Filesystem publication MUST NOT run under a long-held authority monitor. + + +## Animation integration contract + +Glyph-bank animation authoring, generated-source navigation, strict task-scoped MCP tools and preview use the shared animation service and validation contract. UI/MCP preserve project authority, expected revisions, conflict/cancellation/revocation and document handoff. Persist only the canonical animation sidecar; keep generated PBS read-only and neutral services independent of JavaFX/transports. + +See the [complete animation contract](12.%20Animation%20Authoring%20Specification.md). diff --git a/docs/specs/studio/README.md b/docs/specs/studio/README.md index 58f3a041..8e408d9e 100644 --- a/docs/specs/studio/README.md +++ b/docs/specs/studio/README.md @@ -100,3 +100,5 @@ terminal remains separate. See the [specification guide](../README.md) for compiler, language and provider boundaries. + +- [Sprite and animation contract](12.%20Animation%20Authoring%20Specification.md) — core API, explicit ticks, shared bank authoring and generated factories. diff --git a/prometeu-animation/build.gradle.kts b/prometeu-animation/build.gradle.kts new file mode 100644 index 00000000..39b585d3 --- /dev/null +++ b/prometeu-animation/build.gradle.kts @@ -0,0 +1,2 @@ +plugins { id("gradle.java-library-conventions") } +dependencies { implementation(libs.jackson.databind) } diff --git a/prometeu-animation/src/main/java/p/animation/AnimationCodec.java b/prometeu-animation/src/main/java/p/animation/AnimationCodec.java new file mode 100644 index 00000000..bc611bf1 --- /dev/null +++ b/prometeu-animation/src/main/java/p/animation/AnimationCodec.java @@ -0,0 +1,75 @@ +package p.animation; + +import com.fasterxml.jackson.core.JsonParser; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.node.*; +import java.util.*; +import static p.animation.AnimationDocument.*; + +/** Strict UTF-8 JSON. Integer values never pass through floating point. */ +public final class AnimationCodec { + private final ObjectMapper mapper = new ObjectMapper().enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION) + .enable(DeserializationFeature.FAIL_ON_TRAILING_TOKENS); + public AnimationDocument decode(String json) { + try { + JsonNode root = mapper.readTree(json); + object(root, "", "schema_version", "bank_asset_uuid", "bindings", "animators"); + int version = integer(root.get("schema_version"), "/schema_version"); + if (version != 1) throw invalid("/schema_version", "Unsupported schema version"); + var bindings = new ArrayList(); int i=0; + for (var node : array(root.get("bindings"), "/bindings")) { + String p="/bindings/"+i++; object(node,p,"artifact_id","glyph_id","fingerprint"); + bindings.add(new Binding(string(node.get("artifact_id"),p+"/artifact_id"), integer(node.get("glyph_id"),p+"/glyph_id"), string(node.get("fingerprint"),p+"/fingerprint"))); + } + var animators = new ArrayList(); i=0; + for (var node : array(root.get("animators"), "/animators")) { + String p="/animators/"+i++; object(node,p,"id","initial_clip","clips"); + var clips = new ArrayList(); int j=0; + for(var clip : array(node.get("clips"),p+"/clips")) { + String cp=p+"/clips/"+j++; object(clip,cp,"name","mode","frames"); + var frames=new ArrayList(); int k=0; + for(var frame:array(clip.get("frames"),cp+"/frames")) { + String fp=cp+"/frames/"+k++; object(frame,fp,"artifact_id","duration_ticks"); + frames.add(new Frame(string(frame.get("artifact_id"),fp+"/artifact_id"), exactLong(frame.get("duration_ticks"),fp+"/duration_ticks"))); + } + clips.add(new Clip(string(clip.get("name"),cp+"/name"),string(clip.get("mode"),cp+"/mode"),frames)); + } + animators.add(new Animator(string(node.get("id"),p+"/id"),string(node.get("initial_clip"),p+"/initial_clip"),clips)); + } + return new AnimationDocument(version,string(root.get("bank_asset_uuid"),"/bank_asset_uuid"),bindings,animators); + } catch (java.io.IOException error) { throw invalid("", error.getMessage()); } + } + public String encode(AnimationDocument document) { + ObjectNode root=mapper.createObjectNode(); root.put("schema_version",document.schemaVersion()); root.put("bank_asset_uuid",document.bankAssetUuid()); + var bindings=root.putArray("bindings"); + for(var binding:document.bindings()) bindings.addObject().put("artifact_id",binding.artifactId()).put("glyph_id",binding.glyphId()).put("fingerprint",binding.fingerprint()); + var animators=root.putArray("animators"); + for(var animator:document.animators()) { + var node=animators.addObject().put("id",animator.id()).put("initial_clip",animator.initialClip()); var clips=node.putArray("clips"); + for(var clip:animator.clips()) { var c=clips.addObject().put("name",clip.name()).put("mode",clip.mode()); var frames=c.putArray("frames"); + for(var frame:clip.frames()) frames.addObject().put("artifact_id",frame.artifactId()).put("duration_ticks",frame.durationTicks()); } + } + try { return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(root)+"\n"; } + catch(java.io.IOException error) { throw new IllegalStateException(error); } + } + private static void object(JsonNode value,String pointer,String... names) { + if(value==null||!value.isObject())throw invalid(pointer,"Expected object"); + var expected=Set.of(names); var keys=value.fieldNames(); + while(keys.hasNext()){var key=keys.next();if(!expected.contains(key))throw invalid(pointer+"/"+key,"Unknown field");} + for(var name:names)if(!value.has(name))throw invalid(pointer+"/"+name,"Missing required field"); + } + private static JsonNode array(JsonNode node,String pointer){if(node==null||!node.isArray())throw invalid(pointer,"Expected array");return node;} + private static String string(JsonNode node,String pointer){ + if(node==null||!node.isTextual())throw invalid(pointer,"Expected string"); + String text=node.textValue(); + for(int i=0;i=text.length()||!Character.isLowSurrogate(text.charAt(++i)))throw invalid(pointer,"Unpaired Unicode surrogate");} + else if(Character.isLowSurrogate(c))throw invalid(pointer,"Unpaired Unicode surrogate"); + } + return text; + } + private static long exactLong(JsonNode node,String pointer){if(node==null||!node.isIntegralNumber()||!node.canConvertToLong())throw invalid(pointer,"Expected exact signed 64-bit integer");return node.longValue();} + private static int integer(JsonNode node,String pointer){long value=exactLong(node,pointer);if(valueInteger.MAX_VALUE)throw invalid(pointer,"Integer out of range");return (int)value;} + private static IllegalArgumentException invalid(String pointer,String message){return new IllegalArgumentException(pointer+": "+message);} +} diff --git a/prometeu-animation/src/main/java/p/animation/AnimationDiagnostic.java b/prometeu-animation/src/main/java/p/animation/AnimationDiagnostic.java new file mode 100644 index 00000000..aaddcf87 --- /dev/null +++ b/prometeu-animation/src/main/java/p/animation/AnimationDiagnostic.java @@ -0,0 +1,2 @@ +package p.animation; +public record AnimationDiagnostic(String code, String pointer, String message) {} diff --git a/prometeu-animation/src/main/java/p/animation/AnimationDocument.java b/prometeu-animation/src/main/java/p/animation/AnimationDocument.java new file mode 100644 index 00000000..0917d579 --- /dev/null +++ b/prometeu-animation/src/main/java/p/animation/AnimationDocument.java @@ -0,0 +1,24 @@ +package p.animation; + +import java.util.List; +import java.util.Objects; + +/** Canonical editorial values; slots, palette, position and playback clocks are external. */ +public record AnimationDocument(int schemaVersion, String bankAssetUuid, List bindings, List animators) { + public static final String FILE_NAME = "animations.studio.json"; + public AnimationDocument { + Objects.requireNonNull(bankAssetUuid); bindings = List.copyOf(bindings); animators = List.copyOf(animators); + } + public record Binding(String artifactId, int glyphId, String fingerprint) { + public Binding { Objects.requireNonNull(artifactId); Objects.requireNonNull(fingerprint); } + } + public record Animator(String id, String initialClip, List clips) { + public Animator { Objects.requireNonNull(id); Objects.requireNonNull(initialClip); clips = List.copyOf(clips); } + } + public record Clip(String name, String mode, List frames) { + public Clip { Objects.requireNonNull(name); Objects.requireNonNull(mode); frames = List.copyOf(frames); } + } + public record Frame(String artifactId, long durationTicks) { + public Frame { Objects.requireNonNull(artifactId); } + } +} diff --git a/prometeu-animation/src/main/java/p/animation/AnimationOriginNavigation.java b/prometeu-animation/src/main/java/p/animation/AnimationOriginNavigation.java new file mode 100644 index 00000000..c8f53522 --- /dev/null +++ b/prometeu-animation/src/main/java/p/animation/AnimationOriginNavigation.java @@ -0,0 +1,6 @@ +package p.animation; +import java.nio.file.Path; +import java.util.UUID; +/** Open an authored field through the Studio editor; this port never writes files. */ +@FunctionalInterface +public interface AnimationOriginNavigation { void open(Path projectRoot,UUID assetUuid,String jsonPointer); } diff --git a/prometeu-animation/src/main/java/p/animation/AnimationRebind.java b/prometeu-animation/src/main/java/p/animation/AnimationRebind.java new file mode 100644 index 00000000..91949197 --- /dev/null +++ b/prometeu-animation/src/main/java/p/animation/AnimationRebind.java @@ -0,0 +1,28 @@ +package p.animation; + +import java.util.*; +import static p.animation.AnimationDocument.*; + +/** Binding-only proposal, correlated with the exact source and bank revisions. */ +public final class AnimationRebind { + public record Difference(Binding before, Binding after, List affectedFrames) { public Difference { affectedFrames=List.copyOf(affectedFrames); } } + public record Proposal(AnimationDocument document, List differences, String proposalHash, String bankRevision) { public Proposal { differences=List.copyOf(differences); } } + public Proposal prepare(AnimationDocument document,String revision,GlyphBankLayout bank) { + var current=new HashMap();bank.glyphs().forEach(g->current.put(g.artifactId(),g)); + var bindings=new ArrayList();var differences=new ArrayList(); + for(var binding:document.bindings()) { + var glyph=current.get(binding.artifactId()); + Binding updated=glyph==null?binding:new Binding(glyph.artifactId(),glyph.glyphId(),glyph.fingerprint());bindings.add(updated); + if(!updated.equals(binding)||glyph==null){var affected=new ArrayList(); + for(int a=0;a bindings; + private Clip clip; + private long phase; + private State state=State.Stopped; + public AnimationTimeline(AnimationDocument document,String animatorId) { + animator=document.animators().stream().filter(a->a.id().equals(animatorId)).findFirst().orElseThrow(()->new IllegalArgumentException("unknown_animator")); + var values=new HashMap();document.bindings().forEach(b->values.put(b.artifactId(),b));bindings=Map.copyOf(values); + clip=find(animator.initialClip()); + } + private Clip find(String name){return animator.clips().stream().filter(c->c.name().equals(name)).findFirst().orElseThrow(()->new IllegalArgumentException("unknown_clip"));} + public void select(String name){var selected=find(name);clip=selected;phase=0;state=State.Stopped;} + public void play(String name){select(name);state=State.Playing;} + public void pause(){if(state==State.Playing)state=State.Paused;} + public void resume(){if(state==State.Paused)state=State.Playing;} + public void stop(){phase=0;state=State.Stopped;} + public void restart(){phase=0;state=State.Playing;} + public void advance(int ticks){ + if(ticks<0)throw new IllegalArgumentException("invalid_ticks"); + if(ticks==0||state!=State.Playing)return; + if(phase>Long.MAX_VALUE-ticks)throw new IllegalArgumentException("overflow"); + long next=phase+ticks;long total=total(clip);var nextState=state; + if(clip.mode().equals("loop"))next%=total; + else if(next>=total){next=total;nextState=State.Finished;} + phase=next;state=nextState; + } + public Observation observation(){ + long end=0;Frame selected=clip.frames().getLast(); + for(var frame:clip.frames()){end=Math.addExact(end,frame.durationTicks());if(phase=total)timeline.state=State.Finished;} + return timeline.observation(); + } + private static long total(Clip clip){long total=0;for(var frame:clip.frames())total=Math.addExact(total,frame.durationTicks());return total;} +} diff --git a/prometeu-animation/src/main/java/p/animation/AnimationValidator.java b/prometeu-animation/src/main/java/p/animation/AnimationValidator.java new file mode 100644 index 00000000..3b20ed74 --- /dev/null +++ b/prometeu-animation/src/main/java/p/animation/AnimationValidator.java @@ -0,0 +1,57 @@ +package p.animation; + +import java.util.*; + +/** The single structural and asset-binding validator used by Studio and compiler. */ +public final class AnimationValidator { + public List validate(AnimationDocument doc, GlyphBankLayout layout) { + var errors=new ArrayList(); + if(doc.schemaVersion()!=1)add(errors,"schema_version","/schema_version","Unsupported version"); + try { if(!doc.bankAssetUuid().matches("[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}"))throw new IllegalArgumentException("UUID syntax"); if(!UUID.fromString(doc.bankAssetUuid()).equals(layout.assetUuid()))add(errors,"bank_uuid","/bank_asset_uuid","Containing bank UUID does not match"); } + catch(IllegalArgumentException error){add(errors,"bank_uuid","/bank_asset_uuid","Invalid UUID");} + var current=new HashMap(); var indices=new HashSet(); + for(var glyph:layout.glyphs()) { + if(glyph.artifactId().isEmpty()||current.putIfAbsent(glyph.artifactId(),glyph)!=null||!indices.add(glyph.glyphId()) + ||glyph.glyphId()<0||glyph.glyphId()>65535||!glyph.fingerprint().matches("[0-9a-f]{64}")) + add(errors,"bank_layout","/bindings","Current bank layout has missing/duplicate/invalid identities"); + } + var bound=new HashMap(); indices.clear(); + for(int i=0;i65535||!indices.add(binding.glyphId()))add(errors,"invalid_glyph",p+"/glyph_id","Glyph ID is out of range or duplicated"); + var actual=current.get(binding.artifactId()); + if(actual==null)add(errors,"missing_artifact",p,"Selected artifact is absent from the current composition"); + else if(actual.glyphId()!=binding.glyphId()||!actual.fingerprint().equals(binding.fingerprint()))add(errors,"binding_drift",p,"Glyph index or fingerprint changed; explicit rebind required"); + if(!binding.fingerprint().matches("[0-9a-f]{64}"))add(errors,"invalid_fingerprint",p+"/fingerprint","Expected lowercase SHA-256"); + } + var ids=new HashSet(); + for(int i=0;i(); + for(int j=0;jLong.MAX_VALUE-frame.durationTicks())add(errors,"overflow",fp+"/duration_ticks","Clip duration exceeds signed 64-bit range"); + else total+=frame.durationTicks(); + } + } + if(animator.initialClip().isEmpty()||!names.contains(animator.initialClip()))add(errors,"initial_clip_missing",p+"/initial_clip","Initial clip must exist"); + } + return List.copyOf(errors); + } + public void requireValid(AnimationDocument doc,GlyphBankLayout layout) { + var errors=validate(doc,layout);if(!errors.isEmpty())throw new IllegalArgumentException(errors.toString()); + } + private static void add(List list,String code,String pointer,String message){list.add(new AnimationDiagnostic(code,pointer,message));} +} diff --git a/prometeu-animation/src/main/java/p/animation/GlyphBankLayout.java b/prometeu-animation/src/main/java/p/animation/GlyphBankLayout.java new file mode 100644 index 00000000..d361c3f8 --- /dev/null +++ b/prometeu-animation/src/main/java/p/animation/GlyphBankLayout.java @@ -0,0 +1,18 @@ +package p.animation; + +import java.nio.file.Path; +import java.util.List; +import java.util.UUID; +import java.util.Objects; + +/** Effective Packer composition. Paths locate current images; identity never derives from them. */ +public record GlyphBankLayout(UUID assetUuid, String revision, Path assetRoot, List glyphs, byte[] rgbaPalettes) { + public GlyphBankLayout { Objects.requireNonNull(assetUuid); Objects.requireNonNull(revision); glyphs = List.copyOf(glyphs); rgbaPalettes=rgbaPalettes.clone(); } + public GlyphBankLayout(UUID uuid,String revision,Path root,List glyphs){this(uuid,revision,root,glyphs,new byte[0]);} + @Override public byte[] rgbaPalettes(){return rgbaPalettes.clone();} + public record Glyph(String artifactId, int glyphId, String fingerprint, Path imagePath, int width, int height, byte[] indices) { + public Glyph { Objects.requireNonNull(artifactId); Objects.requireNonNull(fingerprint); indices=indices.clone(); } + public Glyph(String id,int glyph,String hash,Path path){this(id,glyph,hash,path,0,0,new byte[0]);} + @Override public byte[] indices(){return indices.clone();} + } +} diff --git a/prometeu-animation/src/main/java/p/animation/GlyphBankLayoutSource.java b/prometeu-animation/src/main/java/p/animation/GlyphBankLayoutSource.java new file mode 100644 index 00000000..1bbe32f4 --- /dev/null +++ b/prometeu-animation/src/main/java/p/animation/GlyphBankLayoutSource.java @@ -0,0 +1,11 @@ +package p.animation; +import java.nio.file.Path; +import java.util.UUID; +/** App-composed port; compiler callers inject a public Packer API adapter. */ +@FunctionalInterface +public interface GlyphBankLayoutSource { + GlyphBankLayout resolve(Path projectRoot, UUID assetUuid); + default T withLayout(Path projectRoot, UUID assetUuid, java.util.function.Function work) { + throw new UnsupportedOperationException("Project-exclusive animation access is not configured"); + } +} diff --git a/prometeu-animation/src/test/java/p/animation/AnimationContractTest.java b/prometeu-animation/src/test/java/p/animation/AnimationContractTest.java new file mode 100644 index 00000000..2683bb36 --- /dev/null +++ b/prometeu-animation/src/test/java/p/animation/AnimationContractTest.java @@ -0,0 +1,40 @@ +package p.animation; +import org.junit.jupiter.api.Test; +import java.util.*; +import static p.animation.AnimationDocument.*; +import static org.junit.jupiter.api.Assertions.*; + +class AnimationContractTest { + static final UUID ID=UUID.fromString("12345678-1234-1234-1234-123456789abc"); + static final String HASH="a".repeat(64); + static AnimationDocument document(String mode){return new AnimationDocument(1,ID.toString(),List.of(new Binding("a",7,HASH),new Binding("b",11,HASH),new Binding("c",4,HASH)),List.of(new Animator("hero"," idle ",List.of(new Clip(" idle ",mode,List.of(new Frame("a",2),new Frame("b",3),new Frame("c",1)))))));} + static GlyphBankLayout bank(){return new GlyphBankLayout(ID,"bank1",null,List.of(new GlyphBankLayout.Glyph("a",7,HASH,null),new GlyphBankLayout.Glyph("b",11,HASH,null),new GlyphBankLayout.Glyph("c",4,HASH,null)));} + @Test void strictCodecPreservesExactLongAndRejectsAmbiguousJson(){ + var codec=new AnimationCodec();var doc=new AnimationDocument(1,ID.toString(),List.of(new Binding("a",7,HASH)),List.of(new Animator("hero","idle",List.of(new Clip("idle","once",List.of(new Frame("a",9007199254740993L))))))); + String json=codec.encode(doc);assertEquals(doc,codec.decode(json)); + for(var invalid:List.of(json.replace("9007199254740993","9007199254740993.0"),json.replace("9007199254740993","9223372036854775808"),json.replace("\"schema_version\" : 1","\"schema_version\" : 1, \"schema_version\" : 1"),json.replace("\"schema_version\" : 1","\"unknown\" : 1, \"schema_version\" : 1"),json+"{}"))assertThrows(IllegalArgumentException.class,()->codec.decode(invalid),invalid); + } + @Test void identityDriftBlocksAndRebindIsAnExplicitImmutableProposal(){ + var doc=document("loop");var validator=new AnimationValidator();assertTrue(validator.validate(doc,bank()).isEmpty()); + var changed=new GlyphBankLayout(ID,"bank2",null,List.of(new GlyphBankLayout.Glyph("a",8,"b".repeat(64),null),new GlyphBankLayout.Glyph("b",11,HASH,null),new GlyphBankLayout.Glyph("c",4,HASH,null))); + assertTrue(validator.validate(doc,changed).stream().anyMatch(d->d.code().equals("binding_drift"))); + var proposal=new AnimationRebind().prepare(doc,"document1",changed); + assertEquals(7,doc.bindings().getFirst().glyphId());assertEquals(8,proposal.document().bindings().getFirst().glyphId()); + assertTrue(validator.validate(proposal.document(),changed).isEmpty());assertFalse(proposal.differences().getFirst().affectedFrames().isEmpty()); + assertNotEquals(proposal.proposalHash(),new AnimationRebind().prepare(doc,"document2",changed).proposalHash()); + } + @Test void timelineMatchesTheNativeBoundaryOracleAndPreservesFailures(){ + for(var mode:List.of("once","loop")){ + var doc=document(mode);long[] ticks={0,1,2,4,5,6,601};int[] glyphs=mode.equals("loop")?new int[]{7,7,11,11,4,7,7}:new int[]{7,7,11,11,4,4,4}; + for(int i=0;itimeline.advance(-1));assertEquals(paused,timeline.observation()); + assertThrows(IllegalArgumentException.class,()->timeline.select("idle"));assertEquals(paused,timeline.observation()); + timeline.resume();timeline.stop();assertEquals(7,timeline.observation().glyphId());timeline.restart();assertEquals(AnimationTimeline.State.Playing,timeline.observation().state()); + } + } + @Test void overflowAndInvalidReferencesAreBlockingDiagnostics(){ + var doc=new AnimationDocument(1,ID.toString(),List.of(new Binding("a",7,HASH)),List.of(new Animator("hero","idle",List.of(new Clip("idle","once",List.of(new Frame("a",Long.MAX_VALUE),new Frame("missing",1))))))); + var errors=new AnimationValidator().validate(doc,bank());assertTrue(errors.stream().anyMatch(d->d.code().equals("overflow")));assertTrue(errors.stream().anyMatch(d->d.code().equals("unbound_frame"))); + } +} diff --git a/prometeu-app/build.gradle.kts b/prometeu-app/build.gradle.kts index 296a725f..c74bb565 100644 --- a/prometeu-app/build.gradle.kts +++ b/prometeu-app/build.gradle.kts @@ -63,7 +63,7 @@ javafx { } // Opt-in desktop gate: real JavaFX toolkit and windows, no display required by normal unit tests. -tasks.named("test") { exclude("**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class", "**/MemcardInstalledRuntimeTest.class") } +tasks.named("test") { exclude("**/AnimationDesktopTest.class", "**/AnimationInstalledRuntimeTest.class", "**/DevDesktopTest.class", "**/InstalledKnowledgeTest.class", "**/HeadlessInstalledRuntimeTest.class", "**/HeadlessTaskIntegrationTest.class", "**/HeadlessMcpDesktopTest.class", "**/MemcardInstalledRuntimeTest.class") } tasks.register("devDesktopTest") { group = "verification" description = "Runs the DEV/Debug desktop lifecycle and handoff smoke tests (requires a display)." @@ -74,6 +74,16 @@ tasks.register("devDesktopTest") { systemProperty("java.awt.headless", "false") } +tasks.register("animationDesktopTest") { + group = "verification" + description = "Authors and repairs an animation through the actual JavaFX editor (requires a display)." + testClassesDirs = sourceSets["test"].output.classesDirs + classpath = sourceSets["test"].runtimeClasspath + useJUnitPlatform() + include("**/AnimationDesktopTest.class") + systemProperty("java.awt.headless", "false") +} + tasks.register("installedKnowledgeTest") { group = "verification" description = "Reads installed references and compiles their example in an isolated JVM outside the checkout." @@ -96,6 +106,9 @@ tasks.register("headlessProcessTest") { classpath = sourceSets["test"].runtimeClasspath useJUnitPlatform() include("**/HeadlessInstalledRuntimeTest.class") + include("**/AnimationInstalledRuntimeTest.class") + systemProperty("pbs.registryConformanceDirectory", + project(":prometeu-compiler:prometeu-build-pipeline").layout.buildDirectory.dir("registry-conformance").get().asFile.absolutePath) include("**/HeadlessTaskIntegrationTest.class") systemProperty("studio.test.runtimeInstall", providers.gradleProperty("studioRuntimeInstall").getOrElse("")) } diff --git a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java index 020cec9a..b723120b 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioApplicationConfiguration.java @@ -171,8 +171,28 @@ public class StudioApplicationConfiguration { } @Bean - CompilerBuildGateway compilerBuildGateway() { - return new CompilerBuildGatewayAdapter(); + p.animation.GlyphBankLayoutSource glyphBankLayoutSource(PackerWorkspaceService packer,ObjectMapper mapper) { + return new p.studio.app.assets.PackerGlyphBankLayouts(packer,mapper); + } + + @Bean + p.studio.core.assets.animation.DefaultAnimationService animationEngine(p.animation.GlyphBankLayoutSource layouts,AssetCatalog catalog) { + return new p.studio.core.assets.animation.DefaultAnimationService(layouts,catalog); + } + + @Bean + p.studio.api.assets.animation.AnimationService animationService(p.studio.core.assets.animation.DefaultAnimationService engine,p.studio.api.automation.ProjectAccess access) { + return new p.studio.core.assets.animation.ManualAnimationService(engine,access); + } + + @Bean + p.studio.api.assets.animation.AnimationTasks animationTasks(p.studio.core.project.ProjectAccessRegistry projects,ProjectCatalog catalog,p.studio.core.assets.animation.DefaultAnimationService engine) { + return new p.studio.core.session.TaskAnimationService(projects,catalog,engine); + } + + @Bean + CompilerBuildGateway compilerBuildGateway(p.animation.GlyphBankLayoutSource layouts) { + return new CompilerBuildGatewayAdapter(layouts); } @Bean @@ -213,8 +233,8 @@ public class StudioApplicationConfiguration { } @Bean - LspServerLifecycle lspServerLifecycle() { - return new LspServerLifecycleImpl(); + LspServerLifecycle lspServerLifecycle(p.animation.GlyphBankLayoutSource layouts,StudioEventBus events) { + return new LspServerLifecycleImpl(layouts,(root,uuid,pointer)->events.publish(new p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent(root,uuid,pointer))); } @Bean @@ -284,13 +304,15 @@ public class StudioApplicationConfiguration { TiledAssetService tiledAssetService, SceneBankWorkflow sceneBankWorkflow, WindowStateStore windowStateStore, - ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide) { - return new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory, + ProjectActivityHistoryStore activityHistoryStore, p.studio.api.automation.AgentConnectionGuide connectionGuide, p.studio.api.assets.animation.AnimationService animationService) { + var factory = new StudioUiFactory(projectCatalog, knownProjects, languageCatalog, projectSessionFactory, executionControllerFactory, projectWorkspaceInitializer, studioExecutor, i18n, theme, eventBus, shipper, assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow, windowStateStore, activityHistoryStore, connectionGuide); + factory.setAnimationService(animationService); + return factory; } @Bean @@ -300,8 +322,8 @@ public class StudioApplicationConfiguration { @Bean p.studio.api.automation.ProjectKnowledge projectKnowledge( - p.studio.core.project.ProjectAccessRegistry projects, ProjectCatalog catalog, ObjectMapper mapper) { - return new p.studio.app.compiler.CompilerProjectKnowledge(projects, catalog, mapper); + p.studio.core.project.ProjectAccessRegistry projects, ProjectCatalog catalog, ObjectMapper mapper, p.animation.GlyphBankLayoutSource layouts) { + return new p.studio.app.compiler.CompilerProjectKnowledge(projects, catalog, mapper, layouts); } @Bean @@ -331,10 +353,11 @@ public class StudioApplicationConfiguration { @Bean p.studio.app.mcp.McpToolRegistry mcpToolRegistry(p.studio.app.mcp.McpToolCatalog catalog, ObjectMapper mapper, p.studio.api.automation.ProjectKnowledge knowledge, p.studio.api.automation.LanguageQueries language, - p.studio.api.automation.TaskTools tasks, java.util.Optional headless) { + p.studio.api.automation.TaskTools tasks, p.studio.api.assets.animation.AnimationTasks animations, java.util.Optional headless) { var handlers = new java.util.LinkedHashMap<>(p.studio.app.mcp.McpProjectKnowledgeTools.handlers(knowledge, mapper)); handlers.putAll(p.studio.app.mcp.McpLanguageTools.handlers(language, mapper)); handlers.putAll(p.studio.app.mcp.McpTaskTools.handlers(tasks, mapper, headless.isPresent())); + handlers.putAll(p.studio.app.mcp.McpAnimationTools.handlers(animations, mapper)); return new p.studio.app.mcp.McpToolRegistry(catalog, mapper, handlers); } diff --git a/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java b/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java index 19d30390..d569efe8 100644 --- a/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java +++ b/prometeu-app/src/main/java/p/studio/app/StudioUiFactory.java @@ -58,6 +58,9 @@ public final class StudioUiFactory { private final ProjectActivityHistoryStore activityHistoryStore; private final p.studio.api.automation.AgentConnectionGuide connectionGuide; + private p.studio.api.assets.animation.AnimationService animationService; + public void setAnimationService(p.studio.api.assets.animation.AnimationService service){this.animationService=service;} + public StudioUiFactory( ProjectCatalog projectCatalog, KnownProjects knownProjects, @@ -113,11 +116,13 @@ public final class StudioUiFactory { } public StudioWindowCoordinator create(Stage stage) { - return new StudioWindowCoordinator(stage, projectCatalog, knownProjects, languageCatalog, projectSessionFactory, + var coordinator = new StudioWindowCoordinator(stage, projectCatalog, knownProjects, languageCatalog, projectSessionFactory, executionControllerFactory, projectWorkspaceInitializer, executor, i18n, theme, eventBus, shipper, assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow, windowStateStore, activityHistoryStore, connectionGuide); + if(animationService!=null)coordinator.setAnimationService(animationService); + return coordinator; } } diff --git a/prometeu-app/src/main/java/p/studio/app/assets/PackerGlyphBankLayouts.java b/prometeu-app/src/main/java/p/studio/app/assets/PackerGlyphBankLayouts.java new file mode 100644 index 00000000..cab4d824 --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/assets/PackerGlyphBankLayouts.java @@ -0,0 +1,22 @@ +package p.studio.app.assets; +import p.animation.*; +import p.packer.PackerWorkspaceService; +import p.packer.messages.*; +import java.nio.file.Path; +import java.util.UUID; +import java.util.function.Function; +import com.fasterxml.jackson.databind.ObjectMapper; +/** Only application composition knows the public Packer adapter. */ +public final class PackerGlyphBankLayouts implements GlyphBankLayoutSource { + private final PackerWorkspaceService packer;private final ObjectMapper mapper; + public PackerGlyphBankLayouts(PackerWorkspaceService packer,ObjectMapper mapper){this.packer=packer;this.mapper=mapper;} + private GetGlyphBankLayoutRequest request(Path root,UUID uuid){ + try{return new GetGlyphBankLayoutRequest(new PackerProjectContext(mapper.readTree(root.resolve("prometeu.json").toFile()).path("name").asText(),root),uuid);} + catch(java.io.IOException e){throw new IllegalArgumentException("Cannot read project identity",e);} + } + private static GlyphBankLayout map(p.packer.dtos.PackerGlyphBankLayoutDTO bank){ + return new GlyphBankLayout(bank.assetUuid(),bank.revision(),bank.assetRoot(),bank.glyphs().stream().map(g->new GlyphBankLayout.Glyph(g.artifactId(),g.glyphId(),g.fingerprint(),g.imagePath(),g.width(),g.height(),g.indices())).toList(),bank.rgbaPalettes()); + } + @Override public GlyphBankLayout resolve(Path root,UUID uuid){return map(packer.getGlyphBankLayout(request(root,uuid)));} + @Override public T withLayout(Path root,UUID uuid,Function work){return packer.withGlyphBankLayout(request(root,uuid),bank->work.apply(map(bank)));} +} diff --git a/prometeu-app/src/main/java/p/studio/app/compiler/CompilerBuildGatewayAdapter.java b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerBuildGatewayAdapter.java index 5f7852f0..99aae6b1 100644 --- a/prometeu-app/src/main/java/p/studio/app/compiler/CompilerBuildGatewayAdapter.java +++ b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerBuildGatewayAdapter.java @@ -11,11 +11,15 @@ import java.util.LinkedHashSet; import java.util.function.Consumer; public final class CompilerBuildGatewayAdapter implements CompilerBuildGateway { + private final p.animation.GlyphBankLayoutSource layouts; + public CompilerBuildGatewayAdapter(){this(null);} + public CompilerBuildGatewayAdapter(p.animation.GlyphBankLayoutSource layouts){this.layouts=layouts;} @Override public CompilerBuildOutput compile(ProjectReference project, Consumer logSink) { final var config = new BuilderPipelineConfig(false, project.rootPath().toString()); + var context=BuilderPipelineContext.fromConfig(config);context.glyphBankLayoutSource=layouts; final var result = BuilderPipelineService.INSTANCE.build( - BuilderPipelineContext.fromConfig(config), + context, LogAggregator.with(logSink)); final var capabilities = new LinkedHashSet<>( result.compileResult().analysisSnapshot().irBackend() diff --git a/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java index f5013a0a..ea714aff 100644 --- a/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java +++ b/prometeu-app/src/main/java/p/studio/app/compiler/CompilerProjectKnowledge.java @@ -26,9 +26,13 @@ public final class CompilerProjectKnowledge implements ProjectKnowledge { private final ProjectAccessRegistry openProjects; private final ProjectCatalog projects; private final ObjectMapper mapper; - private final CompilerLanguageServiceBridge languageBridge = new CompilerLanguageServiceBridge(); + private final CompilerLanguageServiceBridge languageBridge; public CompilerProjectKnowledge(ProjectAccessRegistry openProjects, ProjectCatalog projects, ObjectMapper mapper) { + this(openProjects,projects,mapper,null); + } + public CompilerProjectKnowledge(ProjectAccessRegistry openProjects,ProjectCatalog projects,ObjectMapper mapper,p.animation.GlyphBankLayoutSource layouts) { + this.languageBridge=new CompilerLanguageServiceBridge(layouts); this.openProjects = Objects.requireNonNull(openProjects); this.projects = Objects.requireNonNull(projects); this.mapper = Objects.requireNonNull(mapper); diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java b/prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java index 3f781557..3a80775e 100644 --- a/prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java +++ b/prometeu-app/src/main/java/p/studio/app/mcp/ContractSchema.java @@ -18,6 +18,7 @@ final class ContractSchema { if (schema.has("const") && !schema.get("const").equals(value)) fail(); if (schema.has("type")) { boolean valid = switch (schema.get("type").asText()) { + case "null" -> value.isNull(); case "object" -> value.isObject(); case "array" -> value.isArray(); case "string" -> value.isTextual(); @@ -27,6 +28,8 @@ final class ContractSchema { }; if (!valid) fail(); } + if(schema.has("pattern")&&!value.textValue().matches(schema.get("pattern").textValue()))fail(); + if(schema.has("minItems")&&value.size() schema.get("maximum").longValue()) fail(); diff --git a/prometeu-app/src/main/java/p/studio/app/mcp/McpAnimationTools.java b/prometeu-app/src/main/java/p/studio/app/mcp/McpAnimationTools.java new file mode 100644 index 00000000..0d071c3f --- /dev/null +++ b/prometeu-app/src/main/java/p/studio/app/mcp/McpAnimationTools.java @@ -0,0 +1,39 @@ +package p.studio.app.mcp; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.node.ObjectNode; +import p.animation.AnimationCodec; +import p.studio.api.assets.animation.*; +import p.studio.api.automation.*; +import java.nio.file.Path; +import java.util.*; +import java.util.function.Function; + +/** Wire adaptation only; UI and AI call the same shared application service. */ +public final class McpAnimationTools { + private McpAnimationTools(){} + public static Map> handlers(AnimationTasks tasks,ObjectMapper mapper){ + return Map.of("studio_animation_query",args->call(tasks,mapper,args),"studio_animation_update",args->call(tasks,mapper,args)); + } + private static McpToolResult call(AnimationTasks tasks,ObjectMapper mapper,JsonNode args){ + try { + var response=tasks.execute(Path.of(args.required("projectRoot").textValue()),args.required("taskId").textValue(),project->new AnimationService.Request( + AnimationService.Operation.valueOf(args.required("operation").textValue().toUpperCase(Locale.ROOT)),project, + args.has("assetUuid")?UUID.fromString(args.get("assetUuid").textValue()):null, + text(args,"animatorId"),text(args,"clipName"),args.has("elapsedTicks")?args.get("elapsedTicks").longValue():null, + args.has("paletteId")?args.get("paletteId").intValue():null,text(args,"expectedRevision"), + args.has("document")?new AnimationCodec().decode(args.get("document").toString()):null,text(args,"proposalHash"),text(args,"expectedBankRevision"))); + ObjectNode value=mapper.valueToTree(response); + canonicalView(mapper,value.get("view"));if(value.path("definitions").isArray())for(var view:value.get("definitions"))canonicalView(mapper,view); + if(response.proposal()!=null)((ObjectNode)value.get("proposal")).set("document",mapper.readTree(new AnimationCodec().encode(response.proposal().document()))); + if(response.preview()!=null)((ObjectNode)value.get("preview")).remove("image"); + return McpToolResult.successWithCapture(mapper,value,response.preview()==null?null:response.preview().image(),false); + }catch(ControlDeniedException|AutomationException authority){throw authority;} + catch(IllegalArgumentException invalid){return McpToolResult.failure(mapper,new AutomationFailure(AutomationFailure.Code.ANIMATION_INVALID,invalid.getMessage()));} + catch(IllegalStateException conflict){return McpToolResult.failure(mapper,new AutomationFailure(conflict.getMessage()!=null&&conflict.getMessage().contains("conflict")?AutomationFailure.Code.ANIMATION_CONFLICT:AutomationFailure.Code.INFRASTRUCTURE_FAILURE,conflict.getMessage()));} + catch(java.io.IOException failure){throw new IllegalStateException("Cannot encode animation response",failure);} + } + private static String text(JsonNode node,String field){return node.hasNonNull(field)?node.get(field).textValue():null;} + private static void canonicalView(ObjectMapper mapper,JsonNode view)throws java.io.IOException{ + if(view!=null&&view.isObject()&&view.hasNonNull("document"))((ObjectNode)view).set("document",mapper.readTree(view.required("json").asText())); + } +} diff --git a/prometeu-app/src/main/resources/mcp/studio-tools-v1.json b/prometeu-app/src/main/resources/mcp/studio-tools-v1.json index 7058906b..79fea4e9 100644 --- a/prometeu-app/src/main/resources/mcp/studio-tools-v1.json +++ b/prometeu-app/src/main/resources/mcp/studio-tools-v1.json @@ -2378,6 +2378,945 @@ "exampleValue": { "sessionId": "runtime-example" } + }, + { + "name": "studio_animation_query", + "authority": "task", + "description": "List, get, validate or preview canonical bank animation definitions through the same services as the Assets editor. Preview uses explicit ticks and transient palette input; reads never rebind.", + "inputSchema": { + "type": "object", + "oneOf": [ + { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "const": "list" + }, + "assetUuid": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "operation" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "const": "get" + }, + "assetUuid": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "operation", + "assetUuid" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "const": "validate" + }, + "assetUuid": { + "type": "string", + "minLength": 1 + }, + "document": { + "type": "object", + "properties": { + "schema_version": { + "type": "integer" + }, + "bank_asset_uuid": { + "type": "string", + "minLength": 1 + }, + "bindings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "artifact_id": { + "type": "string", + "minLength": 1 + }, + "glyph_id": { + "type": "integer" + }, + "fingerprint": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "artifact_id", + "glyph_id", + "fingerprint" + ], + "additionalProperties": false + } + }, + "animators": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "[A-Za-z_][A-Za-z0-9_]*" + }, + "initial_clip": { + "type": "string", + "minLength": 1 + }, + "clips": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "mode": { + "oneOf": [ + { + "const": "once" + }, + { + "const": "loop" + } + ] + }, + "frames": { + "type": "array", + "items": { + "type": "object", + "properties": { + "artifact_id": { + "type": "string", + "minLength": 1 + }, + "duration_ticks": { + "type": "integer" + } + }, + "required": [ + "artifact_id", + "duration_ticks" + ], + "additionalProperties": false + } + } + }, + "required": [ + "name", + "mode", + "frames" + ], + "additionalProperties": false + } + } + }, + "required": [ + "id", + "initial_clip", + "clips" + ], + "additionalProperties": false + } + } + }, + "required": [ + "schema_version", + "bank_asset_uuid", + "bindings", + "animators" + ], + "additionalProperties": false + } + }, + "required": [ + "projectRoot", + "taskId", + "operation", + "assetUuid" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "const": "preview" + }, + "assetUuid": { + "type": "string", + "minLength": 1 + }, + "animatorId": { + "type": "string", + "minLength": 1 + }, + "clipName": { + "type": "string", + "minLength": 1 + }, + "elapsedTicks": { + "type": "integer", + "minimum": 0 + }, + "paletteId": { + "type": "integer", + "minimum": 0, + "maximum": 63 + }, + "document": { + "type": "object", + "properties": { + "schema_version": { + "type": "integer" + }, + "bank_asset_uuid": { + "type": "string", + "minLength": 1 + }, + "bindings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "artifact_id": { + "type": "string", + "minLength": 1 + }, + "glyph_id": { + "type": "integer" + }, + "fingerprint": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "artifact_id", + "glyph_id", + "fingerprint" + ], + "additionalProperties": false + } + }, + "animators": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "[A-Za-z_][A-Za-z0-9_]*" + }, + "initial_clip": { + "type": "string", + "minLength": 1 + }, + "clips": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "mode": { + "oneOf": [ + { + "const": "once" + }, + { + "const": "loop" + } + ] + }, + "frames": { + "type": "array", + "items": { + "type": "object", + "properties": { + "artifact_id": { + "type": "string", + "minLength": 1 + }, + "duration_ticks": { + "type": "integer" + } + }, + "required": [ + "artifact_id", + "duration_ticks" + ], + "additionalProperties": false + } + } + }, + "required": [ + "name", + "mode", + "frames" + ], + "additionalProperties": false + } + } + }, + "required": [ + "id", + "initial_clip", + "clips" + ], + "additionalProperties": false + } + } + }, + "required": [ + "schema_version", + "bank_asset_uuid", + "bindings", + "animators" + ], + "additionalProperties": false + } + }, + "required": [ + "projectRoot", + "taskId", + "operation", + "assetUuid", + "animatorId", + "clipName", + "elapsedTicks", + "paletteId" + ], + "additionalProperties": false + } + ], + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "operation" + ] + }, + "outputSchema": { + "type": "object", + "oneOf": [ + { + "type": "object", + "properties": { + "status": { + "const": "ok" + }, + "value": { + "type": "object" + } + }, + "required": [ + "status", + "value" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "const": "error" + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "minLength": 1 + }, + "message": { + "type": "string" + }, + "runtimeError": { + "type": "object", + "additionalProperties": true + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": true, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example", + "operation": "get", + "assetUuid": "12345678-1234-1234-1234-123456789abc" + }, + "exampleValue": { + "definitions": [], + "diagnostics": [] + } + }, + { + "name": "studio_animation_update", + "authority": "task", + "description": "Save/delete animator definitions or prepare/apply an explicit binding-only rebind. Expected revisions prevent overwrites; only create accepts explicitly null expectedRevision. No arbitrary file paths or extra approval flow.", + "inputSchema": { + "type": "object", + "oneOf": [ + { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "const": "save" + }, + "assetUuid": { + "type": "string", + "minLength": 1 + }, + "expectedRevision": { + "oneOf": [ + { + "type": "string", + "minLength": 1 + }, + { + "type": "null" + } + ] + }, + "document": { + "type": "object", + "properties": { + "schema_version": { + "type": "integer" + }, + "bank_asset_uuid": { + "type": "string", + "minLength": 1 + }, + "bindings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "artifact_id": { + "type": "string", + "minLength": 1 + }, + "glyph_id": { + "type": "integer" + }, + "fingerprint": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "artifact_id", + "glyph_id", + "fingerprint" + ], + "additionalProperties": false + } + }, + "animators": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "[A-Za-z_][A-Za-z0-9_]*" + }, + "initial_clip": { + "type": "string", + "minLength": 1 + }, + "clips": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "mode": { + "oneOf": [ + { + "const": "once" + }, + { + "const": "loop" + } + ] + }, + "frames": { + "type": "array", + "items": { + "type": "object", + "properties": { + "artifact_id": { + "type": "string", + "minLength": 1 + }, + "duration_ticks": { + "type": "integer" + } + }, + "required": [ + "artifact_id", + "duration_ticks" + ], + "additionalProperties": false + } + } + }, + "required": [ + "name", + "mode", + "frames" + ], + "additionalProperties": false + } + } + }, + "required": [ + "id", + "initial_clip", + "clips" + ], + "additionalProperties": false + } + } + }, + "required": [ + "schema_version", + "bank_asset_uuid", + "bindings", + "animators" + ], + "additionalProperties": false + } + }, + "required": [ + "projectRoot", + "taskId", + "operation", + "assetUuid", + "expectedRevision", + "document" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "const": "delete" + }, + "assetUuid": { + "type": "string", + "minLength": 1 + }, + "expectedRevision": { + "type": "string", + "minLength": 1 + }, + "animatorId": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "operation", + "assetUuid", + "expectedRevision", + "animatorId" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "const": "prepare_rebind" + }, + "assetUuid": { + "type": "string", + "minLength": 1 + }, + "expectedRevision": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "operation", + "assetUuid", + "expectedRevision" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "const": "apply_rebind" + }, + "assetUuid": { + "type": "string", + "minLength": 1 + }, + "expectedRevision": { + "type": "string", + "minLength": 1 + }, + "document": { + "type": "object", + "properties": { + "schema_version": { + "type": "integer" + }, + "bank_asset_uuid": { + "type": "string", + "minLength": 1 + }, + "bindings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "artifact_id": { + "type": "string", + "minLength": 1 + }, + "glyph_id": { + "type": "integer" + }, + "fingerprint": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "artifact_id", + "glyph_id", + "fingerprint" + ], + "additionalProperties": false + } + }, + "animators": { + "type": "array", + "items": { + "type": "object", + "properties": { + "id": { + "type": "string", + "pattern": "[A-Za-z_][A-Za-z0-9_]*" + }, + "initial_clip": { + "type": "string", + "minLength": 1 + }, + "clips": { + "type": "array", + "items": { + "type": "object", + "properties": { + "name": { + "type": "string", + "minLength": 1 + }, + "mode": { + "oneOf": [ + { + "const": "once" + }, + { + "const": "loop" + } + ] + }, + "frames": { + "type": "array", + "items": { + "type": "object", + "properties": { + "artifact_id": { + "type": "string", + "minLength": 1 + }, + "duration_ticks": { + "type": "integer" + } + }, + "required": [ + "artifact_id", + "duration_ticks" + ], + "additionalProperties": false + } + } + }, + "required": [ + "name", + "mode", + "frames" + ], + "additionalProperties": false + } + } + }, + "required": [ + "id", + "initial_clip", + "clips" + ], + "additionalProperties": false + } + } + }, + "required": [ + "schema_version", + "bank_asset_uuid", + "bindings", + "animators" + ], + "additionalProperties": false + }, + "proposalHash": { + "type": "string", + "minLength": 1 + }, + "expectedBankRevision": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "operation", + "assetUuid", + "expectedRevision", + "document", + "proposalHash", + "expectedBankRevision" + ], + "additionalProperties": false + } + ], + "properties": { + "projectRoot": { + "type": "string", + "minLength": 1 + }, + "taskId": { + "type": "string", + "minLength": 1 + }, + "operation": { + "type": "string", + "minLength": 1 + } + }, + "required": [ + "projectRoot", + "taskId", + "operation" + ] + }, + "outputSchema": { + "type": "object", + "oneOf": [ + { + "type": "object", + "properties": { + "status": { + "const": "ok" + }, + "value": { + "type": "object" + } + }, + "required": [ + "status", + "value" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "status": { + "const": "error" + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "minLength": 1 + }, + "message": { + "type": "string" + }, + "runtimeError": { + "type": "object", + "additionalProperties": true + } + }, + "required": [ + "code", + "message" + ], + "additionalProperties": false + } + }, + "required": [ + "status", + "error" + ], + "additionalProperties": false + } + ] + }, + "annotations": { + "readOnlyHint": false, + "openWorldHint": false + }, + "exampleArguments": { + "projectRoot": "/projects/game", + "taskId": "task-example", + "operation": "save", + "assetUuid": "12345678-1234-1234-1234-123456789abc", + "expectedRevision": null, + "document": { + "schema_version": 1, + "bank_asset_uuid": "12345678-1234-1234-1234-123456789abc", + "bindings": [], + "animators": [] + } + }, + "exampleValue": { + "definitions": [], + "diagnostics": [] + } } ] } diff --git a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java index 7cf3b168..f5926c15 100644 --- a/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java +++ b/prometeu-app/src/test/java/p/studio/app/StudioApplicationConfigurationTest.java @@ -30,7 +30,7 @@ class StudioApplicationConfigurationTest { assertFalse(executor.isShutdown()); assertTrue(mcp.isRunning()); var tools = context.getBean(p.studio.app.mcp.McpToolRegistry.class).descriptors(); - org.junit.jupiter.api.Assertions.assertEquals(22, tools.size()); + org.junit.jupiter.api.Assertions.assertEquals(24, tools.size()); assertTrue(context.getBean(p.studio.core.runtime.HeadlessGateway.class) instanceof p.studio.app.runtime.HeadlessProcessGateway); org.junit.jupiter.api.Assertions.assertEquals("studio_project_context", tools.get(0).path("name").asText()); org.junit.jupiter.api.Assertions.assertEquals("studio_reference_read", tools.get(1).path("name").asText()); diff --git a/prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java b/prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java new file mode 100644 index 00000000..c5cf0026 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java @@ -0,0 +1,54 @@ +package p.studio.app.animation; + +import javafx.application.Platform; +import javafx.scene.Scene; +import javafx.scene.control.*; +import javafx.scene.image.ImageView; +import javafx.stage.Stage; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import p.studio.ui.javafx.workspaces.assets.details.animation.AnimationEditorControl; +import p.animation.*; +import java.nio.file.*; +import java.util.concurrent.*; +import java.util.function.*; +import static org.junit.jupiter.api.Assertions.*; + +/** Actual JavaFX editing, shared save/preview, drift repair and handoff lifecycle. */ +class AnimationDesktopTest { + @TempDir Path root; + @BeforeAll static void toolkit()throws Exception{ + var ready=new CompletableFuture(); + try{Platform.startup(()->{Platform.setImplicitExit(false);ready.complete(null);});} + catch(IllegalStateException running){ready.complete(null);} + ready.get(10,TimeUnit.SECONDS); + } + @AfterAll static void stopToolkit(){Platform.exit();} + static T fx(Supplier work)throws Exception{var result=new CompletableFuture();Platform.runLater(()->{try{result.complete(work.get());}catch(Throwable f){result.completeExceptionally(f);}});return result.get(10,TimeUnit.SECONDS);} + static void await(BooleanSupplier test)throws Exception{long end=System.nanoTime()+TimeUnit.SECONDS.toNanos(10);while(!test.getAsBoolean()){if(System.nanoTime()>end)fail("Animation editor did not finish");Thread.sleep(10);}} + static Button button(AnimationEditorControl editor,String text){return editor.lookupAll(".button").stream().filter(n->n instanceof Button b&&b.getText().equals(text)).map(n->(Button)n).findFirst().orElseThrow();} + @Test void authorsPreviewsSavesRepairsAndCloses()throws Exception{ + var fixture=new AnimationIntegrationTest();fixture.root=root;fixture.setup(); + var pool=Executors.newCachedThreadPool();var stage=new Stage[1];var editor=new AnimationEditorControl[1]; + try{ + fx(()->{editor[0]=new AnimationEditorControl(fixture.project,fixture.manual,pool);var scroll=new ScrollPane(editor[0]);scroll.setFitToWidth(true);stage[0]=new Stage();stage[0].setTitle("Animation authoring acceptance");stage[0].setScene(new Scene(scroll,1040,940));stage[0].show();editor[0].bind(fixture.uuid);return null;}); + await(()->{try{return fx(()->((Label)editor[0].lookup("#animation-status")).getText().equals("New definition"));}catch(Exception e){throw new RuntimeException(e);}}); + fx(()->{((TextField)editor[0].lookup("#animation-id")).setText("hero");button(editor[0],"New animator").fire();((ComboBox)editor[0].lookup("#animation-glyph")).getSelectionModel().selectFirst();((TextField)editor[0].lookup("#animation-duration")).setText("2");button(editor[0],"Add frame").fire();return null;}); + assertTrue(editor[0].hasUnsavedChanges().toCompletableFuture().get()); + editor[0].saveAll().toCompletableFuture().get(10,TimeUnit.SECONDS); + assertFalse(editor[0].hasUnsavedChanges().toCompletableFuture().get()); + assertEquals(2,fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.get(fixture.project,fixture.uuid)).view().document().animators().getFirst().clips().getFirst().frames().getFirst().durationTicks()); + fx(()->{button(editor[0],"Preview").fire();return null;}); + await(()->{try{return fx(()->((ImageView)editor[0].lookup("#animation-image")).getImage()!=null);}catch(Exception e){throw new RuntimeException(e);}}); + fx(()->{var snapshot=stage[0].getScene().snapshot(null);var image=new java.awt.image.BufferedImage((int)snapshot.getWidth(),(int)snapshot.getHeight(),java.awt.image.BufferedImage.TYPE_INT_ARGB);for(int y=0;y{button(editor[0],"Prepare rebind").fire();return null;}); + await(()->{try{return fx(()->!button(editor[0],"Apply rebind").isDisabled());}catch(Exception e){throw new RuntimeException(e);}}); + fx(()->{button(editor[0],"Apply rebind").fire();return null;}); + await(()->fixture.manual.execute(p.studio.api.assets.animation.AnimationService.Request.get(fixture.project,fixture.uuid)).view().diagnostics().isEmpty()); + fx(()->{editor[0].openOrigin("/animators/0/clips/0/frames/0");editor[0].close();stage[0].close();return null;}); + assertFalse(pool.isShutdown()); + }finally{fx(()->{if(editor[0]!=null)editor[0].close();if(stage[0]!=null)stage[0].close();return null;});pool.shutdownNow();fixture.close();} + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledProbe.java b/prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledProbe.java new file mode 100644 index 00000000..3505903b --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledProbe.java @@ -0,0 +1,55 @@ +package p.studio.app.animation; + +import java.nio.file.*; +import p.animation.*; +import p.studio.api.assets.animation.AnimationService; +import p.studio.compiler.models.BuilderPipelineContext; +import p.studio.compiler.messages.BuilderPipelineConfig; +import p.studio.compiler.workspaces.BuilderPipelineService; +import p.studio.compiler.backend.bytecode.BytecodeEmitter; +import p.studio.utilities.logs.LogAggregator; + +/** Runs only with installed product JARs, outside the checkout. No runtime checkout is read. */ +public final class AnimationInstalledProbe { + public static void verify(Path root,Path corpus)throws Exception{ + var f=new AnimationProjectFixture();f.root=root;f.setup(); + try{ + f.manual.execute(AnimationService.Request.save(f.project,f.uuid,null,f.document())); + Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;pub fn animationProbe()->int;"); + Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/b_"+f.uuid.toString().replace("-","")+";\n"+""" + import { AnimationError } from @core:animation; + declare global trace:int=0; + fn run()->result { + let value=create_hero(3)!;let other=create_hero(3)!; + value.play("idle")!;value.advance(2)!; + if value.sprite().glyph_id!=1 || other.sprite().glyph_id!=0 {let fail=1/0;} + trace=42;return ok(()); + } + [Frame]fn frame()->void {run();} + fn animationProbe()->int {return trace;} + """); + var context=BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,root.toString()));context.glyphBankLayoutSource=f.layouts; + var result=BuilderPipelineService.INSTANCE.compile(context,LogAggregator.stdout()); + if(result.diagnostics().stream().anyMatch(d->d.isError()))throw new AssertionError(result.diagnostics()); + Files.createDirectories(corpus); + for(boolean optimized:new boolean[]{false,true}){ + var program=optimized?context.optimizedIrvm:context.irvm; + var module=new BytecodeEmitter().emit(program.coherentEmissionPlan()); + String prefix="pbs-animation-installed"+(optimized?"-optimized":"");Files.write(corpus.resolve(prefix+".pbx"),module.serialize()); + for(int i=0;i generated PBS -> Composer -> pixels. */ +class AnimationInstalledRuntimeTest { + @TempDir Path root; + @Test void composedFramesMatchSharedPreviewAtEveryBoundary()throws Exception{ + var f=new AnimationProjectFixture();f.root=root;f.setup(); + var workers=Executors.newSingleThreadExecutor(); + try{ + f.manual.execute(AnimationService.Request.save(f.project,f.uuid,null,f.document())); + var manifest=(com.fasterxml.jackson.databind.node.ObjectNode)f.mapper.readTree(f.bankRoot.resolve("asset.json").toFile()); + ((com.fasterxml.jackson.databind.node.ObjectNode)manifest.path("preload")).put("enabled",true); + ((com.fasterxml.jackson.databind.node.ArrayNode)manifest.path("output").path("pipeline").path("palettes")) + .addObject().put("index",1).putObject("palette").putArray("rgba8888").add(0x0000ffff).add(0xff0000ff).add(0x00ff00ff); + f.mapper.writeValue(f.bankRoot.resolve("asset.json").toFile(),manifest); + Path scene=Files.createDirectories(root.resolve("assets/scene")); + var sc=f.mapper.createObjectNode().put("schema_version",1).put("asset_uuid","22345678-1234-1234-1234-123456789abc").put("name","scene").put("type","scene_bank"); + sc.putObject("preload").put("enabled",true);sc.putObject("output").put("format","SCENE/tilemap_v1").put("codec","NONE");f.mapper.writeValue(scene.resolve("asset.json").toFile(),sc); + var request=f.mapper.createObjectNode().put("schema_version",1).put("format","SCENE/tilemap_v1").put("version",1);var layers=request.putArray("layers"); + for(int i=0;i<4;i++){var layer=layers.addObject().put("active",true).put("glyph_asset_id",1).put("tile_size",16).put("parallax_factor_x",1.0).put("parallax_factor_y",1.0).put("width",1).put("height",1);layer.putArray("tiles").addObject().put("active",false).put("glyph_id",0).put("palette_id",0).put("flip_x",false).put("flip_y",false);} + f.mapper.writeValue(scene.resolve("scene-bank.pack-request.json").toFile(),request); + var registry=(com.fasterxml.jackson.databind.node.ObjectNode)f.mapper.readTree(root.resolve("assets/.prometeu/index.json").toFile());((com.fasterxml.jackson.databind.node.ArrayNode)registry.path("assets")).addObject().put("asset_id",2).put("asset_uuid",sc.path("asset_uuid").asText()).put("root","scene").put("included_in_build",true);registry.put("next_asset_id",3);f.mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry); + Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;"); + Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/b_"+f.uuid.toString().replace("-","")+";\n"+""" + import { AnimationError, PlaybackMode, animator_builder } from @core:animation; + import { Composer } from @sdk:composer; + declare global elapsed:int=0; + fn render()->result { + let a=create_hero(0)!;a.play("idle")!;a.advance(elapsed)!; + let b=animator_builder(0,"idle")!;b.begin_clip("idle",PlaybackMode.Loop)!; + b.add_frame(0,2)!;b.add_frame(1,3)!;b.add_frame(2,1)!;b.end_clip()!; + let other=b.build()!;other.play("idle")!;other.advance(elapsed)!; + if other.sprite().glyph_id!=a.sprite().glyph_id {let fail=1/0;} + if Composer.bind_scene(0)!=0 {let fail=1/0;} + let image=a.sprite();let direct=other.sprite(); + if Composer.emit_sprite(image.glyph_id,elapsed%2,32,32,0,image.bank_id,false,false,0)!=0 {let fail=1/0;} + if Composer.emit_sprite(direct.glyph_id,elapsed%2,64,32,0,direct.bank_id,false,false,0)!=0 {let fail=1/0;} + elapsed=elapsed+1;return ok(()); + } + [Frame]fn frame()->void {render();} + """); + byte[] definition=Files.readAllBytes(f.bankRoot.resolve(AnimationDocument.FILE_NAME)); + Path corpus=Path.of(System.getProperty("pbs.registryConformanceDirectory"));Files.createDirectories(corpus); + for(boolean optimized:new boolean[]{false,true}){ + p.studio.core.shipper.CompilerBuildGateway compiler=(project,sink)->{ + var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,project.rootPath().toString()));context.glyphBankLayoutSource=f.layouts; + p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.build(context,p.studio.utilities.logs.LogAggregator.with(sink)); + if(!optimized)try{Files.write(context.bytecodeArtifactPath,new p.studio.compiler.backend.bytecode.BytecodeEmitter().emit(context.irvm.coherentEmissionPlan()).serialize());}catch(java.io.IOException error){throw new java.io.UncheckedIOException(error);} + return new p.studio.core.shipper.CompilerBuildGateway.CompilerBuildOutput(context.bytecodeArtifactPath,context.irBackend.getReservedMetadata().requiredCapabilities().asList()); + }; + var build=new StudioShipperService(compiler,f.packer.workspaceService(),f.mapper,new ExecutorOperationExecutor(workers)).prepare(f.project,ignored->{}).completion().toCompletableFuture().get(30,TimeUnit.SECONDS); + assertTrue(build.success(),build.diagnostics().toString()); + String prefix="pbs-animation-composer"+(optimized?"-optimized":""); + Files.copy(root.resolve("build/program.pbx"),corpus.resolve(prefix+".pbx"),StandardCopyOption.REPLACE_EXISTING); + Files.copy(root.resolve("build/assets.pa"),corpus.resolve(prefix+".assets.pa"),StandardCopyOption.REPLACE_EXISTING); + Files.copy(build.manifestPath(),corpus.resolve(prefix+".manifest.json"),StandardCopyOption.REPLACE_EXISTING); + String install=System.getProperty("studio.test.runtimeInstall");assertNotNull(install); + var setup=new ProjectLocalStudioSetup(install,null); + var session=new HeadlessProcessGateway(f.mapper,ignored->setup).boot(f.project,"animation-"+optimized,build); + var oracle=f.mapper.createArrayNode(); + try{ + for(int tick=0;tick<8;tick++){ + var outcome=session.advance(1,ignored->{});assertEquals(AutomationOutcome.Kind.SUCCEEDED,outcome.kind(),outcome.toString()); + assertNull(session.call(TaskTools.HeadlessAction.FAULT,Map.of()).values().get("fault")); + var frame=javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(outcome.capture().png())); + var preview=f.manual.execute(new AnimationService.Request(AnimationService.Operation.PREVIEW,f.project,f.uuid,"hero","idle",(long)tick,tick%2,null,null,null,null)).preview(); + var expected=javax.imageio.ImageIO.read(new java.io.ByteArrayInputStream(preview.image().png())); + var sample=oracle.addObject().put("tick",tick).put("glyph",preview.observation().glyphId()).put("palette",tick%2); + var pixels=sample.putArray("rgba"); + for(int y=0;y<16;y++)for(int dx=0;dx<16;dx++){ + int pixel=expected.getRGB(dx,y);pixels.add(Integer.toUnsignedLong((pixel<<8)|(pixel>>>24))); + for(int x:new int[]{32,64})assertEquals(pixel,frame.getRGB(x+dx,32+y),"tick "+tick+" at "+x+" optimized="+optimized); + } + } + }finally{session.shutdown().toCompletableFuture().get(10,TimeUnit.SECONDS);} + f.mapper.writeValue(corpus.resolve(prefix+".oracle.json").toFile(),oracle); + assertArrayEquals(definition,Files.readAllBytes(f.bankRoot.resolve(AnimationDocument.FILE_NAME))); + } + }finally{workers.shutdownNow();f.close();} + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java b/prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java new file mode 100644 index 00000000..bcd3b9f4 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java @@ -0,0 +1,197 @@ +package p.studio.app.animation; + +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.io.TempDir; +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.node.*; +import p.animation.*; +import p.packer.Packer; +import p.packer.messages.*; +import p.studio.api.assets.animation.*; +import p.studio.core.assets.animation.*; +import p.studio.app.assets.PackerGlyphBankLayouts; +import p.studio.app.mcp.*; +import p.studio.core.assets.PackerAssetCatalog; +import p.studio.core.project.*; +import p.studio.core.session.*; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.api.automation.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import java.awt.image.BufferedImage; +import javax.imageio.ImageIO; +import static org.junit.jupiter.api.Assertions.*; +import static p.animation.AnimationDocument.*; + +class AnimationIntegrationTest { + @TempDir Path root; + final ObjectMapper mapper=new ObjectMapper(); + final UUID uuid=UUID.fromString("12345678-1234-1234-1234-123456789abc"); + Packer packer;PackerGlyphBankLayouts layouts;DefaultAnimationService engine;ManualAnimationService manual; + p.studio.api.project.ProjectReference project;Path bankRoot; + @BeforeEach void setup()throws Exception{ + root=root.toRealPath();bankRoot=Files.createDirectories(root.resolve("assets/hero"));Files.createDirectories(root.resolve("assets/.prometeu"));Files.createDirectories(root.resolve("src")); + Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"app\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}"); + var manifest=mapper.createObjectNode().put("schema_version",1).put("asset_uuid",uuid.toString()).put("name","hero").put("type","glyph_bank"); + manifest.putObject("preload").put("enabled",false); + var output=manifest.putObject("output").put("format","GLYPH/indexed_v1").put("codec","NONE");output.putObject("metadata").put("tile_size","16x16"); + output.putObject("pipeline").putArray("palettes").addObject().put("index",0).putObject("palette").putArray("rgba8888").add(0xff0000ff).add(0x00ff00ff).add(0x0000ffff); + var artifacts=manifest.putArray("artifacts");int[] colors={0xffff0000,0xff00ff00,0xff0000ff}; + for(int i=0;i<3;i++){var image=new BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB);for(int y=0;y<16;y++)for(int x=0;x<16;x++)image.setRGB(x,y,colors[i]);var path=bankRoot.resolve("g"+i+".png");ImageIO.write(image,"png",path.toFile());artifacts.addObject().put("artifact_id","g"+i).put("file","g"+i+".png").put("index",i).put("fingerprint",AnimationRevision.of(Files.readAllBytes(path)));} + mapper.writeValue(bankRoot.resolve("asset.json").toFile(),manifest); + var registry=mapper.createObjectNode().put("schema_version",1).put("next_asset_id",2);registry.putArray("assets").addObject().put("asset_id",1).put("asset_uuid",uuid.toString()).put("root","hero").put("included_in_build",true);mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry); + packer=Packer.bootstrap(mapper,event->{});layouts=new PackerGlyphBankLayouts(packer.workspaceService(),mapper); + engine=new DefaultAnimationService(layouts,new PackerAssetCatalog(packer.workspaceService()));manual=new ManualAnimationService(engine,path->()->{}); + project=new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper)).openProject(root); + } + @AfterEach void close(){packer.close();} + AnimationDocument document(){var bindings=layouts.resolve(root,uuid).glyphs().stream().map(g->new Binding(g.artifactId(),g.glyphId(),g.fingerprint())).toList();return new AnimationDocument(1,uuid.toString(),bindings,List.of(new Animator("hero","idle",List.of(new Clip("idle","loop",List.of(new Frame("g0",2),new Frame("g1",3),new Frame("g2",1)))))));} + AnimationService.Request request(AnimationService.Operation op,String revision,AnimationDocument doc,String hash,String bankRevision){return new AnimationService.Request(op,project,uuid,"hero","idle",2L,0,revision,doc,hash,bankRevision);} + @Test void savedDefinitionBuildsARealGeneratedFactoryAndKeepsBinaryAssetsUnchanged()throws Exception{ + var context=new PackerProjectContext("app",root);var before=packer.workspaceService().packWorkspace(new PackWorkspaceRequest(context));assertEquals(PackerOperationStatus.SUCCESS,before.status(),before.toString());byte[] binary=Files.readAllBytes(root.resolve("build/assets.pa")); + var saved=manual.execute(AnimationService.Request.save(project,uuid,null,document())).view();assertTrue(saved.diagnostics().isEmpty()); + var after=packer.workspaceService().packWorkspace(new PackWorkspaceRequest(context));assertEquals(PackerOperationStatus.SUCCESS,after.status());assertArrayEquals(binary,Files.readAllBytes(root.resolve("build/assets.pa"))); + Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;"); + String module="b_"+uuid.toString().replace("-",""); + Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/"+module+";\nimport { AnimationError } from @core:animation;\n"+""" + fn verify() -> result { let a=create_hero(3)!;a.play("idle")!;a.advance(2)!; + if a.sprite().glyph_id!=1 { let fail=1/0; }return ok(()); } + [Frame] fn frame() -> void { verify(); } + """); + var build=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));build.glyphBankLayoutSource=layouts; + var result=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(build,p.studio.utilities.logs.LogAggregator.stdout());assertTrue(result.bytecodeBytes().length>0); + var source=new p.studio.compiler.workspaces.AssetSurfaceContextLoader(layouts).load(root).animations().getFirst(); + Path generatedPath=null;String generatedText=null; + for(var id:build.fileTable.identifiers()){var handle=build.fileTable.get(id);if(handle.getCanonPath().startsWith(Path.of("/virtual/generated/animations"))&&handle.getFilename().equals("main.pbs")){generatedPath=handle.getCanonPath();generatedText=handle.readUtf8().orElseThrow();}} + assertNotNull(generatedPath);assertFalse(generatedText.contains(root.toString())); + var bridge=new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(layouts); + var generated=bridge.currentSource(new p.studio.lsp.messages.LspProjectContext("app","pbs",root),generatedPath).orElseThrow(); + assertEquals("generated",generated.origin());assertTrue(generated.readOnly());assertFalse(generated.origins().isEmpty());assertEquals("/animators/0/id",generated.origins().getFirst().jsonPointer()); + + assertThrows(IllegalStateException.class,()->new p.studio.compiler.workspaces.AssetSurfaceContextLoader().load(root)); + Files.createDirectories(root.resolve("src/generated/animations/"+module));Files.writeString(root.resolve("src/generated/animations/"+module+"/mod.barrel"),"pub fn collision() -> void;");Files.writeString(root.resolve("src/generated/animations/"+module+"/main.pbs"),"fn collision() -> void {}"); + build=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));build.glyphBankLayoutSource=layouts; + var failed=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(build,p.studio.utilities.logs.LogAggregator.stdout());assertTrue(failed.diagnostics().stream().anyMatch(d->d.getCode().equals("E_LINK_GENERATED_COLLISION")),failed.diagnostics().toString()); + } + @Test void generatedOriginsRejectStaleRevisionsAndReconnect() throws Exception { + manual.execute(AnimationService.Request.save(project,uuid,null,document())); + Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;"); + String module="b_"+uuid.toString().replace("-",""); + Files.writeString(root.resolve("src/main.pbs"),"import { create_hero } from @app:generated/animations/"+module+";\n[Frame] fn frame()->void { create_hero(1); }"); + var calls=new ArrayList(); + var bridge=new p.studio.lsp.services.compiler.CompilerLanguageServiceBridge(layouts,(r,id,p)->calls.add(id+":"+p)); + var context=new p.studio.lsp.messages.LspProjectContext("app","pbs",root); + try(var registry=new p.studio.lsp.services.compiler.ExternalSourceRegistry()){ + String consumer=registry.connect(null,false); + String text=Files.readString(root.resolve("src/main.pbs")); + var navigation=bridge.navigation(context,root.resolve("src/main.pbs").toUri().toString(),text,1,29,registry,consumer); + assertEquals(1,navigation.locations().size());String uri=navigation.locations().getFirst().uri(); + var content=registry.read(consumer,uri);var origin=content.descriptor().origins().getFirst(); + bridge.openAnimationOrigin(context,uri,origin.startOffset(),registry,consumer); + assertEquals(List.of(uuid+":/animators/0/id"),calls); + registry.disconnect(consumer);registry.connect(consumer,false); + bridge.openAnimationOrigin(context,uri,origin.startOffset(),registry,consumer); + var current=manual.execute(AnimationService.Request.get(project,uuid)).view(); + var next=new AnimationDocument(1,uuid.toString(),document().bindings(),List.of()); + manual.execute(AnimationService.Request.save(project,uuid,current.revision(),next)); + assertThrows(RuntimeException.class,()->bridge.openAnimationOrigin(context,uri,origin.startOffset(),registry,consumer)); + assertEquals(2,calls.size()); + } + } + + @Test void conflictsDriftAndExplicitRebindPreserveCanonicalBytes()throws Exception{ + var original=document();var saved=manual.execute(AnimationService.Request.save(project,uuid,null,original)).view();byte[] bytes=Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)); + assertThrows(IllegalStateException.class,()->manual.execute(AnimationService.Request.save(project,uuid,null,original)));assertArrayEquals(bytes,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME))); + ObjectNode manifest=(ObjectNode)mapper.readTree(bankRoot.resolve("asset.json").toFile());((ObjectNode)manifest.path("artifacts").get(0)).put("index",1);((ObjectNode)manifest.path("artifacts").get(1)).put("index",0);mapper.writeValue(bankRoot.resolve("asset.json").toFile(),manifest); + var drift=manual.execute(AnimationService.Request.get(project,uuid)).view();assertTrue(drift.diagnostics().stream().anyMatch(d->d.code().equals("binding_drift")));assertArrayEquals(bytes,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME))); + var prepared=manual.execute(request(AnimationService.Operation.PREPARE_REBIND,saved.revision(),null,null,null)).proposal();assertEquals(2,prepared.differences().size()); + assertThrows(IllegalStateException.class,()->manual.execute(request(AnimationService.Operation.APPLY_REBIND,saved.revision(),prepared.document(),prepared.proposalHash(),"stale-bank")));assertArrayEquals(bytes,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME))); + var updated=manual.execute(request(AnimationService.Operation.APPLY_REBIND,saved.revision(),prepared.document(),prepared.proposalHash(),prepared.bankRevision())).view();assertTrue(updated.diagnostics().isEmpty());assertNotEquals(saved.revision(),updated.revision()); + } + @Test void utf8ProjectionIsExactDeterministicAndSurvivesBankRelocation() throws Exception { + String clip="idle \"\\\n\r\té😀"+(char)0+(char)1; + var value=new AnimationDocument(1,uuid.toString(),document().bindings(),List.of( + new Animator("zeta",clip,List.of(new Clip(clip,"once",List.of(new Frame("g0",9007199254740993L))))), + new Animator("alpha",clip,List.of(new Clip(clip,"loop",List.of(new Frame("g1",1))))))); + var saved=manual.execute(AnimationService.Request.save(project,uuid,null,value)).view();String bankRevision=saved.bankRevision(); + Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;"); + Files.writeString(root.resolve("src/main.pbs"),"import {create_zeta,create_alpha} from @app:generated/animations/b_"+uuid.toString().replace("-","")+";[Frame]fn frame()->void {create_zeta(0);create_alpha(0);}"); + byte[] previous=null;String generated=null; + for(int repeat=0;repeat<2;repeat++){ + var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));context.glyphBankLayoutSource=layouts; + var result=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(context,p.studio.utilities.logs.LogAggregator.stdout()); + assertTrue(result.bytecodeModule().constPool().stream().anyMatch(c->c instanceof p.studio.compiler.backend.bytecode.BytecodeModule.StringConstant text&&text.value().equals(clip))); + if(previous!=null)assertArrayEquals(previous,result.bytecodeBytes());previous=result.bytecodeBytes(); + for(var id:context.fileTable.identifiers()){var handle=context.fileTable.get(id);if(handle.getCanonPath().startsWith(Path.of("/virtual/generated/animations"))&&handle.getFilename().equals("main.pbs"))generated=handle.readUtf8().orElseThrow();} + } + assertNotNull(generated);assertTrue(generated.indexOf("fn create_alpha")>(); + for(int i=0;i<2;i++)results.add(pool.submit(()->{start.await();try{manual.execute(AnimationService.Request.save(project,uuid,null,document()));return true;}catch(IllegalStateException conflict){return false;}})); + start.countDown();int accepted=0;for(var result:results)if(result.get(10,TimeUnit.SECONDS))accepted++; + assertEquals(1,accepted);byte[] original=Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME)); + var entered=new CountDownLatch(1);var release=new CountDownLatch(1);var settled=new CountDownLatch(1); + GlyphBankLayoutSource delayed=new GlyphBankLayoutSource(){ + public GlyphBankLayout resolve(Path path,UUID id){return layouts.resolve(path,id);} + public T withLayout(Path path,UUID id,java.util.function.Function work){ + return layouts.withLayout(path,id,bank->{entered.countDown();try{release.await(10,TimeUnit.SECONDS);return work.apply(bank);}catch(InterruptedException error){throw new RuntimeException(error);}finally{settled.countDown();}}); + } + }; + var session=new DefaultAutomationSession(root,new ExecutorOperationExecutor(pool));var access=new ProjectAccessRegistry();access.register(root,session::enterManual,()->!session.snapshot().closed(),session); + var taskService=new TaskAnimationService(access,new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper)),new DefaultAnimationService(delayed,new PackerAssetCatalog(packer.workspaceService()))); + session.grant(false).toCompletableFuture().get();String task=session.acquire().task().value(); + String revision=AnimationRevision.of(original); + var call=pool.submit(()->taskService.execute(root,task,p->AnimationService.Request.save(p,uuid,revision,document()))); + assertTrue(entered.await(5,TimeUnit.SECONDS)); + session.reclaim().toCompletableFuture().get(5,TimeUnit.SECONDS); + release.countDown();assertTrue(settled.await(5,TimeUnit.SECONDS)); + assertThrows(ExecutionException.class,()->call.get(5,TimeUnit.SECONDS)); + assertArrayEquals(original,Files.readAllBytes(bankRoot.resolve(AnimationDocument.FILE_NAME))); + session.closeAsync().toCompletableFuture().get(5,TimeUnit.SECONDS); + } finally {pool.shutdownNow();} + } + + @Test void excludedAndMalformedDefinitionsDoNotProduceStaleFactories()throws Exception{ + manual.execute(AnimationService.Request.save(project,uuid,null,document())); + Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame()->void;");Files.writeString(root.resolve("src/main.pbs"),"[Frame]fn frame()->void {}"); + Files.writeString(bankRoot.resolve(AnimationDocument.FILE_NAME),"{broken"); + var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString()));context.glyphBankLayoutSource=layouts; + var failed=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(context,p.studio.utilities.logs.LogAggregator.stdout()); + assertTrue(failed.diagnostics().stream().anyMatch(d->d.getCode().equals("E_ANIMATION_SURFACE"))); + var registry=(ObjectNode)mapper.readTree(root.resolve("assets/.prometeu/index.json").toFile());((ObjectNode)registry.path("assets").get(0)).put("included_in_build",false);mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry); + assertTrue(new p.studio.compiler.workspaces.AssetSurfaceContextLoader(layouts).load(root).animations().isEmpty()); + assertNull(manual.execute(AnimationService.Request.get(project,uuid)).view().document()); + } + + @Test void taskToolsShareDocumentsPreviewAndExistingAuthority()throws Exception{ + var workers=Executors.newCachedThreadPool();var session=new DefaultAutomationSession(root,new ExecutorOperationExecutor(workers));var access=new ProjectAccessRegistry();access.register(root,session::enterManual,()->!session.snapshot().closed(),session); + var guarded=new ManualAnimationService(engine,access);var saved=guarded.execute(AnimationService.Request.save(project,uuid,null,document())).view(); + var preview=guarded.execute(request(AnimationService.Operation.PREVIEW,null,null,null,null)).preview(); + var catalog=new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper));var tasks=new TaskAnimationService(access,catalog,engine);var tools=new McpToolRegistry(new McpToolCatalog(mapper),mapper,McpAnimationTools.handlers(tasks,mapper)); + try { + var args=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId","stale").put("operation","get").put("assetUuid",uuid.toString()); + assertEquals("INVALID_TASK",tools.call("studio_animation_query",args).wire().path("structuredContent").path("error").path("code").asText()); + session.grant(false).toCompletableFuture().join();String task=session.acquire().task().value();args.put("taskId",task); + assertThrows(ControlDeniedException.class,()->guarded.execute(AnimationService.Request.get(project,uuid))); + var get=tools.call("studio_animation_query",args).wire();assertFalse(get.path("isError").asBoolean(),get.toString());assertEquals(saved.revision(),get.path("structuredContent").path("value").path("view").path("revision").asText()); + args.put("operation","preview").put("animatorId","hero").put("clipName","idle").put("elapsedTicks",2L).put("paletteId",0); + var rendered=tools.call("studio_animation_query",args).wire();assertFalse(rendered.path("isError").asBoolean(),rendered.toString());assertArrayEquals(preview.image().png(),Base64.getDecoder().decode(rendered.path("content").get(1).path("data").asText())); + assertEquals(1,rendered.path("structuredContent").path("value").path("preview").path("observation").path("glyphId").asInt()); + var save=mapper.createObjectNode().put("projectRoot",root.toString()).put("taskId",task).put("operation","save").put("assetUuid",uuid.toString()).put("expectedRevision","stale");save.set("document",mapper.readTree(new AnimationCodec().encode(document()))); + assertEquals("ANIMATION_CONFLICT",tools.call("studio_animation_update",save).wire().path("structuredContent").path("error").path("code").asText()); + save.put("expectedRevision",saved.revision()); + var published=tools.call("studio_animation_update",save).wire();assertFalse(published.path("isError").asBoolean(),published.toString()); + assertEquals(document(),new AnimationCodec().decode(published.path("structuredContent").path("value").path("view").path("json").asText())); + session.release(session.snapshot().task()).toCompletableFuture().get(5,TimeUnit.SECONDS); + assertEquals("INVALID_TASK",tools.call("studio_animation_update",save).wire().path("structuredContent").path("error").path("code").asText()); + }finally{session.closeAsync().toCompletableFuture().get(5,TimeUnit.SECONDS);workers.shutdownNow();} + } +} diff --git a/prometeu-app/src/test/java/p/studio/app/animation/AnimationProjectFixture.java b/prometeu-app/src/test/java/p/studio/app/animation/AnimationProjectFixture.java new file mode 100644 index 00000000..d8370552 --- /dev/null +++ b/prometeu-app/src/test/java/p/studio/app/animation/AnimationProjectFixture.java @@ -0,0 +1,47 @@ +package p.studio.app.animation; + +import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.node.*; +import p.animation.*; +import p.packer.Packer; +import p.packer.messages.*; +import p.studio.api.assets.animation.*; +import p.studio.core.assets.animation.*; +import p.studio.app.assets.PackerGlyphBankLayouts; +import p.studio.app.mcp.*; +import p.studio.core.assets.PackerAssetCatalog; +import p.studio.core.project.*; +import p.studio.core.session.*; +import p.studio.app.operation.ExecutorOperationExecutor; +import p.studio.api.automation.*; +import java.nio.file.*; +import java.util.*; +import java.util.concurrent.*; +import java.awt.image.BufferedImage; +import javax.imageio.ImageIO; +import static p.animation.AnimationDocument.*; + +public class AnimationProjectFixture { + Path root; + final ObjectMapper mapper=new ObjectMapper(); + final UUID uuid=UUID.fromString("12345678-1234-1234-1234-123456789abc"); + Packer packer;PackerGlyphBankLayouts layouts;DefaultAnimationService engine;ManualAnimationService manual; + p.studio.api.project.ProjectReference project;Path bankRoot; + void setup()throws Exception{ + root=root.toRealPath();bankRoot=Files.createDirectories(root.resolve("assets/hero"));Files.createDirectories(root.resolve("assets/.prometeu"));Files.createDirectories(root.resolve("src")); + Files.writeString(root.resolve("prometeu.json"),"{\"name\":\"app\",\"version\":\"1.0.0\",\"language\":\"pbs\",\"stdlib\":\"1\",\"target\":\"Game\",\"dependencies\":[]}"); + var manifest=mapper.createObjectNode().put("schema_version",1).put("asset_uuid",uuid.toString()).put("name","hero").put("type","glyph_bank"); + manifest.putObject("preload").put("enabled",false); + var output=manifest.putObject("output").put("format","GLYPH/indexed_v1").put("codec","NONE");output.putObject("metadata").put("tile_size","16x16"); + output.putObject("pipeline").putArray("palettes").addObject().put("index",0).putObject("palette").putArray("rgba8888").add(0xff0000ff).add(0x00ff00ff).add(0x0000ffff); + var artifacts=manifest.putArray("artifacts");int[] colors={0xffff0000,0xff00ff00,0xff0000ff}; + for(int i=0;i<3;i++){var image=new BufferedImage(16,16,BufferedImage.TYPE_INT_ARGB);for(int y=0;y<16;y++)for(int x=0;x<16;x++)image.setRGB(x,y,colors[i]);var path=bankRoot.resolve("g"+i+".png");ImageIO.write(image,"png",path.toFile());artifacts.addObject().put("artifact_id","g"+i).put("file","g"+i+".png").put("index",i).put("fingerprint",AnimationRevision.of(Files.readAllBytes(path)));} + mapper.writeValue(bankRoot.resolve("asset.json").toFile(),manifest); + var registry=mapper.createObjectNode().put("schema_version",1).put("next_asset_id",2);registry.putArray("assets").addObject().put("asset_id",1).put("asset_uuid",uuid.toString()).put("root","hero").put("included_in_build",true);mapper.writeValue(root.resolve("assets/.prometeu/index.json").toFile(),registry); + packer=Packer.bootstrap(mapper,event->{});layouts=new PackerGlyphBankLayouts(packer.workspaceService(),mapper); + engine=new DefaultAnimationService(layouts,new PackerAssetCatalog(packer.workspaceService()));manual=new ManualAnimationService(engine,path->()->{}); + project=new ProjectCatalogService(root.getParent(),mapper,new ProjectLocalStudioSetupStore(mapper)).openProject(root); + } + void close(){packer.close();} + AnimationDocument document(){var bindings=layouts.resolve(root,uuid).glyphs().stream().map(g->new Binding(g.artifactId(),g.glyphId(),g.fingerprint())).toList();return new AnimationDocument(1,uuid.toString(),bindings,List.of(new Animator("hero","idle",List.of(new Clip("idle","loop",List.of(new Frame("g0",2),new Frame("g1",3),new Frame("g2",1)))))));} +} diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java index 9d8e16fb..92faccda 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeProbe.java @@ -117,20 +117,21 @@ public final class InstalledKnowledgeProbe { check(linkedResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed Linked example must compile"); Files.write(fixtures.resolve("pbs-linked-installed.pbx"),linkedResult.bytecodeBytes()); System.out.println("Installed Linked execution fixture generated"); - for(var example:java.util.Map.of("set","sets.pbs","hash","hashing.pbs","map","maps.pbs","stack-queue","stack-queue.pbs").entrySet()) { + for(var example:java.util.Map.of("set","sets.pbs","hash","hashing.pbs","map","maps.pbs","stack-queue","stack-queue.pbs","animation","animation.pbs").entrySet()) { Path exampleRoot=Files.createDirectory(Path.of(example.getKey()+"-example")).toRealPath(); Files.createDirectories(exampleRoot.resolve("src")); Files.copy(root.resolve("prometeu.json"),exampleRoot.resolve("prometeu.json")); Files.writeString(exampleRoot.resolve("src/mod.barrel"),"pub fn frame() -> void;"); - String function=switch(example.getKey()){case "set"->"setExample";case "map"->"mapsExample";case "stack-queue"->"stackQueueExample";default->"hashingExample";}; + String function=switch(example.getKey()){case "animation"->"animationExample";case "set"->"setExample";case "map"->"mapsExample";case "stack-queue"->"stackQueueExample";default->"hashingExample";}; Files.writeString(exampleRoot.resolve("src/main.pbs"),Files.readString(root.resolve("src/"+example.getValue())) - +"\n[Frame] fn frame()->void {if "+function+"()!=42 {let failure=1/0;}}"); + +(example.getKey().equals("animation")?"\n[Frame] fn frame()->void { animationExample(); }":"\n[Frame] fn frame()->void {if "+function+"()!=42 {let failure=1/0;}}")); var exampleResult=BuilderPipelineService.INSTANCE.compile( BuilderPipelineContext.fromConfig(new BuilderPipelineConfig(false,exampleRoot.toString())),LogAggregator.stdout()); check(exampleResult.diagnostics().stream().noneMatch(issue->issue.isError()),"Installed "+example.getKey()+" example must compile: "+exampleResult.diagnostics()); Files.write(fixtures.resolve("pbs-"+example.getKey()+"-installed.pbx"),exampleResult.bytecodeBytes()); System.out.println("Installed "+example.getKey()+" execution fixture generated"); } + p.studio.app.animation.AnimationInstalledProbe.verify(Files.createDirectory(Path.of("animation-authored")).toRealPath(),fixtures); verifyExternalSources(provider.getClass().getClassLoader()); registration.unsubscribe(); System.out.println("Installed knowledge verified: " + docs.size() + " references; example compiled"); diff --git a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java index b93f49a0..01a59c70 100644 --- a/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java +++ b/prometeu-app/src/test/java/p/studio/app/compiler/InstalledKnowledgeTest.java @@ -21,6 +21,8 @@ class InstalledKnowledgeTest { assertTrue(log.contains("Installed map execution fixture generated"), log); assertTrue(log.contains("Installed stack-queue execution fixture generated"), log); assertTrue(log.contains("Installed memcard execution fixture generated"), log); + assertTrue(log.contains("Installed animation execution fixture generated"), log); + assertTrue(log.contains("Installed generated animation verified"), log); } @Test void installedCompilerAndSdkCarryTheSameVerifiedCatalog() throws Exception { diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java index 50bf7232..bc533f96 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/McpContractTest.java @@ -12,7 +12,7 @@ class McpContractTest { final McpToolCatalog catalog = new McpToolCatalog(mapper); @Test void everyToolHasValidExampleAuthorityAndResultEnvelope() { - assertEquals(22, catalog.names().size()); + assertEquals(24, catalog.names().size()); for (var name : catalog.names()) { var definition = catalog.definition(name); assertDoesNotThrow(() -> catalog.validateArguments(name, definition.get("exampleArguments")), name + " arguments"); diff --git a/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java b/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java index 72244d2a..a73bf117 100644 --- a/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java +++ b/prometeu-app/src/test/java/p/studio/app/mcp/stdio/StudioMcpStdioTest.java @@ -27,7 +27,7 @@ class StudioMcpStdioTest { var count = new AtomicInteger(); String pixels = "A".repeat(1024 * 1024 + 100); try (var process = new Connector(root); var server = server(count, pixels)) { process.initialize(); - assertEquals(22, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size()); + assertEquals(24, process.request("tools/list", mapper.createObjectNode()).path("result").path("tools").size()); var waiting = process.call("studio_project_context", root); assertEquals("WAITING_FOR_ACCESS", waiting.path("structuredContent").path("error").path("code").asText()); assertFalse(Files.exists(root.resolve(".studio"))); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java b/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java index 8ef66c98..87c88cfe 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/architecture/StudioBoundaryArchTest.java @@ -7,8 +7,15 @@ import com.tngtech.archunit.lang.ArchRule; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; -@AnalyzeClasses(packages = {"p.studio", "p.packer"}, importOptions = ImportOption.DoNotIncludeTests.class) +@AnalyzeClasses(packages = {"p.studio", "p.packer", "p.animation"}, importOptions = ImportOption.DoNotIncludeTests.class) class StudioBoundaryArchTest { + @ArchTest + static final ArchRule animationModelIsNeutral = noClasses() + .that().resideInAPackage("p.animation..") + .should().dependOnClassesThat().resideInAnyPackage( + "p.studio..", "p.packer..", "javafx..", "org.springframework..") + .because("DEC-0084 shares authoring DTOs and validation without a provider or UI dependency"); + @ArchTest static final ArchRule automationTransportStaysInTheApp = noClasses() .that().resideInAnyPackage("p.studio.api..", "p.studio.core..", "p.studio.ui..") diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java new file mode 100644 index 00000000..ac9ca151 --- /dev/null +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java @@ -0,0 +1,57 @@ +package p.studio.compiler.backend.irvm; + +import org.junit.jupiter.api.Test; +import p.studio.compiler.models.SourceKind; +import p.studio.compiler.models.registry.IRRegistry; +import java.util.LinkedHashMap; +import java.nio.file.*; +import static org.junit.jupiter.api.Assertions.*; + +/** Production producers; results are independently checked by the native verifier. */ +class PbsResultTest { + @Test void resultFunctionsCannotBecomePlainFunctionValues() { + for(String value:new String[]{"let f:Fn()->int=fallible;","let f=fallible;"}){ + var diagnostics=p.studio.compiler.source.diagnostics.DiagnosticSink.empty(); + assertDoesNotThrow(()->new p.studio.compiler.pbs.PbsFrontendCompiler().compileFile(new p.studio.compiler.source.identifiers.FileId(0), + "declare error E {bad;} fn fallible()->result int {return err(E.bad);} fn check(){"+value+"}",diagnostics)); + assertTrue(diagnostics.hasErrors(),value); + } + } + + @Test void completeResultGroupsAndControlFlowReachProductionPbx() throws Exception { + var fixtures = new LinkedHashMap(); + String errors = "declare error E { bad; other; } declare error F { retry; abort; }\n"; + fixtures.put("unit-ok", "fn main() -> result { return ok(()); }"); + fixtures.put("unit-err", "fn main() -> result { return err(E.other); }"); + fixtures.put("scalar", "fn main() -> result int { return ok(42); }"); + fixtures.put("error", "fn main() -> result long { return err(E.bad); }"); + fixtures.put("tuple", "fn main() -> result (a: long, b: int) { return ok((a: 9007199254740993, b: 42)); }"); + fixtures.put("reference", "fn main() -> result array { return err(E.other); }"); + fixtures.put("propagate", "fn source() -> result int { return err(E.other); } fn main() -> result (a: long, b: str) { let v = Probe.source()!; return ok((a: v as long, b: \"unused\")); }"); + fixtures.put("nested", "fn source() -> result int { return err(E.other); } fn main() -> result int { return ok(100 + Probe.source()!); }"); + fixtures.put("recover", "fn source() -> result int { return err(E.bad); } fn main() -> result int { let v = handle Probe.source() { E.bad -> { ok(42) }, E.other -> F.abort }; return ok(v); }"); + fixtures.put("remap", "fn source() -> result int { return err(E.other); } fn main() -> result int { let v = handle Probe.source() { E.bad -> { ok(42) }, E.other -> F.abort }; return ok(v); }"); + fixtures.put("success", "fn source() -> result int { return ok(42); } fn main() -> result int { let v = handle Probe.source() { _ -> { ok(99) } }; return ok(v); }"); + fixtures.put("trait", "fn main() -> result Reader { return err(E.bad); }"); + fixtures.put("fn", "fn main() -> result Fn() -> int { return err(E.bad); }"); + fixtures.put("once", "fn source() -> result int { calls=calls+1; return err(E.bad); } fn unused() -> int { calls=calls+100; return 99; } fn main() -> result int { let value=handle Probe.source() { E.bad -> { ok(42) }, E.other -> { ok(Probe.unused()) } }; if calls!=1 { let fail=1/0; } return ok(value); }"); + fixtures.put("block-remap", "fn source() -> result int { return err(E.bad); } fn main() -> result int { let value=handle Probe.source() { E.bad -> { err(F.abort) }, _ -> { ok(42) } }; return ok(value); }"); + fixtures.put("reference-ok", "fn source() -> result array { return ok([42]); } fn main() -> result int { let values=Probe.source()!; return ok(values[0] else 0); }"); + fixtures.put("fn-ok", "fn source() -> result Fn() -> int { return ok(answer); } fn main() -> result int { let f=Probe.source()!; return ok(f()); }"); + fixtures.put("trait-ok", "fn source() -> result Fallible { return ok(new ReaderValue(42)); } fn main() -> result int { let reader=Probe.source()!; return ok(reader.read()!); }"); + fixtures.put("color-ok", "fn main() -> result Color { return ok(Color.from_raw(42)); }"); + fixtures.put("color-err", "fn main() -> result Color { return err(E.bad); }"); + fixtures.put("trap", "fn source() -> result int { let fail=1/0; return ok(1); } fn main() -> result int { let value=handle Probe.source() { _ -> { ok(42) } }; return ok(value); }"); + String color; + try(var input=p.studio.compiler.pbs.PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/core/color/main.pbs")){assertNotNull(input);color=new String(input.readAllBytes(),java.nio.charset.StandardCharsets.UTF_8);} + String support="declare global calls: int=0; fn answer() -> int { return 42; } declare contract Fallible { fn read() -> result int; } declare struct ReaderValue(pub value:int); implements Fallible for ReaderValue using reader { fn read() -> result int { return ok(reader.value); } }\n"; + var manifest = new StringBuilder(); + for (var entry : fixtures.entrySet()) for (var suffix : new String[]{"", "-optimized"}) { + var source = errors + support + color + "declare contract Reader { fn read() -> int; }\n" + entry.getValue().replace("Probe.", ""); + var module = PbsRuntimeAlignmentTest.compile("result-" + entry.getKey() + suffix, source, SourceKind.SDK_INTERFACE, "main"); + assertEquals(IRRegistry.TypeRef.builtin(0x10), module.functions().getFirst().metadata().signature().results().getFirst()); + manifest.append(entry.getKey()).append(suffix).append('\n'); + } + Files.writeString(Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("pbs-result-manifest.txt"), manifest); + } +} diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java index 05a53d82..f803af15 100644 --- a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsRuntimeAlignmentTest.java @@ -20,6 +20,9 @@ class PbsRuntimeAlignmentTest { return compile(name, source, SourceKind.SDK_INTERFACE); } static BytecodeModule compile(String name,String source,SourceKind sourceKind) throws Exception { + return compile(name,source,sourceKind,"Probe.main"); + } + static BytecodeModule compile(String name,String source,SourceKind sourceKind,String entryPoint) throws Exception { var diagnostics=DiagnosticSink.empty(); var fileId = new FileId(0); var ast = p.studio.compiler.pbs.parser.PbsParser.parse(p.studio.compiler.pbs.lexer.PbsLexer.lex(source,fileId,diagnostics),fileId,diagnostics,p.studio.compiler.pbs.parser.PbsParser.ParseMode.INTERFACE_MODULE); @@ -27,7 +30,7 @@ class PbsRuntimeAlignmentTest { new p.studio.compiler.source.identifiers.ModuleId(0),p.studio.utilities.structures.ReadOnlyList.empty(), p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(),p.studio.compiler.messages.FESurfaceContext.empty(),new p.studio.compiler.source.tables.NameTable()); assertFalse(diagnostics.hasErrors(), ()->diagnostics.stream().map(d->d.getCode()+":"+d.getMessage()).toList().toString()); - var backend=IRBackend.builder().entryPointCallableName("Probe.main").entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(0)).executableFunctions(file.executableFunctions()) + var backend=IRBackend.builder().entryPointCallableName(entryPoint).entryPointModuleId(new p.studio.compiler.source.identifiers.ModuleId(0)).executableFunctions(file.executableFunctions()) .globals(file.globals()).registry(file.registry()).intrinsicPool(file.intrinsicPool()).callableSignatures(file.callableSignatures()).build(); var program=new LowerToIRVMService().lower(backend); if (name.endsWith("-optimized")) program = new OptimizeIRVMService().optimize(program); diff --git a/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java new file mode 100644 index 00000000..45bb8967 --- /dev/null +++ b/prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java @@ -0,0 +1,269 @@ +package p.studio.compiler.backend.irvm; + +import org.junit.jupiter.api.Test; +import p.studio.compiler.models.SourceKind; +import p.studio.compiler.pbs.PbsFrontendCompiler; +import java.nio.charset.StandardCharsets; +import static org.junit.jupiter.api.Assertions.*; + +class PbsSpriteAnimationTest { + static String core() throws Exception { + var text = new StringBuilder(); + for (var path : new String[]{"sprite", "animation"}) { + try (var input = PbsFrontendCompiler.class.getResourceAsStream("/game/stdlib/1/core/"+path+"/main.pbs")) { + assertNotNull(input); + text.append(new String(input.readAllBytes(), StandardCharsets.UTF_8).replace("import { SpriteView } from @core:sprite;", "")); + } + } + return text.toString(); + } + @Test void directCoreLibraryUsesTheProductionCompiler() throws Exception { + for (var suffix : new String[]{"", "-optimized"}) { + PbsRuntimeAlignmentTest.compile("animation-basic"+suffix, core()+""" + declare service Probe { + fn main() -> result int { + let builder = animator_builder(3, "idle")!; + builder.begin_clip("idle", PlaybackMode.Loop)!; + builder.add_frame(7, 2)!; builder.add_frame(11, 3)!; builder.add_frame(4, 1)!; + builder.end_clip()!; + let first = builder.build()!; let second = builder.build()!; + first.play("idle")!; first.advance(2)!; + if second.sprite().glyph_id != 7 { let failed = 1 / 0; } + if first.sprite().glyph_id != 11 { let failed = 1 / 0; } + first.advance(4)!; + if first.sprite().glyph_id != 7 { let failed = 1 / 0; } + let frame = first.frame_at("idle", 1)!; + if frame.glyph_id != 11 { let failed = 1 / 0; } + return ok(42); + } + } + """, SourceKind.PROJECT); + } + } + @Test void playbackFailuresAndAllocationPathsHaveNativeFixtures() throws Exception { + var cases = new java.util.LinkedHashMap(); + var build = """ + fn fixture(mode: PlaybackMode) -> result Animator { + let b = animator_builder(3, "idle")!; + b.begin_clip("idle", mode)!; + b.add_frame(7, 2)!; b.add_frame(11, 3)!; b.add_frame(4, 1)!; + b.end_clip()!; return ok(b.build()!); + } + """; + cases.put("loop", """ + let a = fixture(PlaybackMode.Loop)!; a.play("idle")!; + let view: SpriteView = a; + let start = 162000001; + if view.sprite().glyph_id != 7 { let fail = 1 / 0; } + a.advance(1)!; if a.sprite().glyph_id != 7 { let fail = 1 / 0; } + a.advance(1)!; if a.sprite().glyph_id != 11 { let fail = 1 / 0; } + a.advance(3)!; if a.sprite().glyph_id != 4 { let fail = 1 / 0; } + a.advance(1)!; if a.sprite().glyph_id != 7 { let fail = 1 / 0; } + a.advance(601)!; if a.sprite().glyph_id != 7 { let fail = 1 / 0; } + a.advance(2147483647)!; if a.sprite().glyph_id != 11 { let fail = 1 / 0; } + for i: int from 0 until 100 { a.advance(0)!; view.sprite(); } + let end = 162000002; + return ok(42); + """); + cases.put("once", """ + let a = fixture(PlaybackMode.Once)!; a.play("idle")!; + let start = 162000001; + a.advance(5)!; if a.state() != PlaybackState.Playing { let fail = 1 / 0; } + if a.sprite().glyph_id != 4 { let fail = 1 / 0; } + a.advance(1)!; if a.state() != PlaybackState.Finished { let fail = 1 / 0; } + a.resume(); a.advance(100)!; + if a.sprite().glyph_id != 4 || a.state() != PlaybackState.Finished { let fail = 1 / 0; } + a.restart(); if a.sprite().glyph_id != 7 || a.state() != PlaybackState.Playing { let fail = 1 / 0; } + a.advance(2)!; a.pause(); a.advance(100)!; + if a.sprite().glyph_id != 11 { let fail = 1 / 0; } + a.resume(); a.play("idle")!; + if a.sprite().glyph_id != 7 { let fail = 1 / 0; } + a.select("idle")!; if a.state() != PlaybackState.Stopped { let fail = 1 / 0; } + let end = 162000002; return ok(42); + """); + cases.put("negative", """ + let a = fixture(PlaybackMode.Loop)!; + let start = 162000001; + handle a.advance(-1) { AnimationError.invalid_ticks -> { ok(()) }, _ -> AnimationError.overflow }; + if a.state() != PlaybackState.Stopped || a.sprite().glyph_id != 7 { let fail = 1 / 0; } + a.play("idle")!; a.advance(2)!; + handle a.advance(-1) { AnimationError.invalid_ticks -> { ok(()) }, _ -> AnimationError.overflow }; + if a.sprite().glyph_id != 11 || a.state() != PlaybackState.Playing { let fail = 1 / 0; } + let end = 162000002; return ok(42); + """); + cases.put("overflow", """ + // Isolated test-only near-limit setup; calls the unchanged production advance. + let maximum: long = 9223372036854775807; + let frame = new _AnimationFrame.make(7, maximum, maximum); + let clip = new _AnimationClip.make("idle", PlaybackMode.Once); + clip.head = frame; clip.tail = frame; clip.count = 1; clip.total = maximum; + let a = new Animator(3, clip, clip, frame, maximum - 2, PlaybackState.Playing, 1); + let start = 162000001; + handle a.advance(3) { AnimationError.overflow -> { ok(()) }, _ -> AnimationError.invalid_ticks }; + if a.sprite().glyph_id != 7 || a.state() != PlaybackState.Playing { let fail = 1 / 0; } + let end = 162000002; return ok(42); + """); + cases.put("draft", """ + let b = animator_builder(3, "idle")!; + handle b.build() { AnimationError.empty_animator -> { ok(new Animator(0, new _AnimationClip.make("", PlaybackMode.Once), new _AnimationClip.make("", PlaybackMode.Once), new _AnimationFrame.make(0, 1, 1), 0, PlaybackState.Stopped, 0)) }, _ -> AnimationError.empty_animator }; + b.begin_clip("idle", PlaybackMode.Once)!; + handle b.end_clip() { AnimationError.empty_clip -> { ok(()) }, _ -> AnimationError.empty_clip }; + b.add_frame(7, 2)!; b.end_clip()!; + let a = b.build()!; b.remove_clip("idle")!; + if a.sprite().glyph_id != 7 || a.clip_count() != (1 as long) { let fail = 1 / 0; } + b.begin_clip("idle", PlaybackMode.Loop)!; b.add_frame(11, 3)!; b.end_clip()!; + let other = b.build()!; + if other.sprite().glyph_id != 11 || a.sprite().glyph_id != 7 { let fail = 1 / 0; } + return ok(42); + """); + cases.put("limits", """ + let maximum: long = 9223372036854775807; + let b = animator_builder(255, "idle")!; + handle b.add_frame(-1, 0) { AnimationError.no_open_clip -> { ok(()) }, _ -> AnimationError.overflow }; + handle b.discard_clip() { AnimationError.no_open_clip -> { ok(()) }, _ -> AnimationError.overflow }; + b.begin_clip("idle", PlaybackMode.Once)!; + handle b.begin_clip("", PlaybackMode.Once) { AnimationError.clip_already_open -> { ok(()) }, _ -> AnimationError.overflow }; + handle b.add_frame(-1, 0) { AnimationError.invalid_glyph -> { ok(()) }, _ -> AnimationError.overflow }; + handle b.add_frame(0, 0) { AnimationError.invalid_duration -> { ok(()) }, _ -> AnimationError.overflow }; + b.add_frame(65535, maximum)!; + handle b.add_frame(0, 1) { AnimationError.overflow -> { ok(()) }, _ -> AnimationError.invalid_duration }; + handle b.remove_clip("") { AnimationError.unfinished_clip -> { ok(()) }, _ -> AnimationError.overflow }; + b.end_clip()!; + handle b.begin_clip("idle", PlaybackMode.Loop) { AnimationError.duplicate_clip -> { ok(()) }, _ -> AnimationError.overflow }; + handle b.begin_clip("", PlaybackMode.Loop) { AnimationError.invalid_name -> { ok(()) }, _ -> AnimationError.overflow }; + let a = b.build()!; + handle a.frame_at("missing", -1) { AnimationError.unknown_clip -> { ok((glyph_id: 0, duration_ticks: 0 as long)) }, _ -> AnimationError.overflow }; + handle a.frame_at("idle", 1) { AnimationError.index_out_of_range -> { ok((glyph_id: 0, duration_ticks: 0 as long)) }, _ -> AnimationError.overflow }; + handle a.select("missing") { AnimationError.unknown_clip -> { ok(()) }, _ -> AnimationError.overflow }; + handle a.play("missing") { AnimationError.unknown_clip -> { ok(()) }, _ -> AnimationError.overflow }; + if a.sprite().glyph_id != 65535 || a.state() != PlaybackState.Stopped { let fail=1/0; } + let alias = a; alias.play("idle")!; + if a.state() != PlaybackState.Playing { let fail=1/0; } + // Test-only count setup avoids billions of allocations; production add_frame executes. + let frame = new _AnimationFrame.make(7, 1, 1); + let clip = new _AnimationClip.make("idle", PlaybackMode.Once); + clip.head=frame;clip.tail=frame;clip.count=4294967295;clip.total=1; + let full = new AnimatorBuilder(0,"idle",clip,clip,clip,0,true); + handle full.add_frame(0,1) { AnimationError.limit_exceeded -> { ok(()) }, _ -> AnimationError.overflow }; + let countMaximum: long = 4294967295; + if clip.count != countMaximum { let fail=1/0; } + return ok(42); + """); + cases.put("matrix", """ + let a = fixture(PlaybackMode.Once)!; + for stage: int from 0 until 4 { + a.stop(); + if stage == 1 { a.play("idle")!;a.advance(2)!; } + if stage == 2 { a.play("idle")!;a.advance(2)!;a.pause(); } + if stage == 3 { a.play("idle")!;a.advance(6)!; } + let before = a.sprite().glyph_id;let state = a.state(); + handle a.advance(-1) { AnimationError.invalid_ticks -> { ok(()) }, _ -> AnimationError.overflow }; + a.advance(0)!;if a.state()!=state || a.sprite().glyph_id!=before {let fail=1/0;} + a.select("idle")!;if a.state()!=PlaybackState.Stopped || a.sprite().glyph_id!=7 {let fail=1/0;} + a.play("idle")!;a.advance(2)!;a.play("idle")!; + if a.sprite().glyph_id!=7 || a.state()!=PlaybackState.Playing {let fail=1/0;} + a.pause();a.pause();a.advance(100)!;if a.state()!=PlaybackState.Paused || a.sprite().glyph_id!=7 {let fail=1/0;} + a.resume();a.resume();a.advance(2)!;if a.sprite().glyph_id!=11 {let fail=1/0;} + a.stop();a.resume();if a.state()!=PlaybackState.Stopped {let fail=1/0;} + a.restart();if a.sprite().glyph_id!=7 || a.state()!=PlaybackState.Playing {let fail=1/0;} + } + return ok(42); + """); + cases.put("errors", """ + let s = handle make_sprite(255,65535) { _ -> AnimationError.invalid_glyph }; + let s0 = handle make_sprite(0,0) { _ -> AnimationError.invalid_glyph }; + let view: SpriteView = s; + let b = animator_builder(0,"idle")!;let a=fixture(PlaybackMode.Once)!; + let start=162000001; + if view.sprite().bank_id!=255 || view.sprite().glyph_id!=65535 || s0.sprite().glyph_id!=0 {let fail=1/0;} + handle make_sprite(-1,-1) { SpriteError.invalid_bank -> {ok(s)}, _ -> AnimationError.overflow }; + handle make_sprite(256,0) { SpriteError.invalid_bank -> {ok(s)}, _ -> AnimationError.overflow }; + handle make_sprite(0,-1) { SpriteError.invalid_glyph -> {ok(s)}, _ -> AnimationError.overflow }; + handle make_sprite(0,65536) { SpriteError.invalid_glyph -> {ok(s)}, _ -> AnimationError.overflow }; + handle animator_builder(256,"") { AnimationError.invalid_bank -> {ok(b)}, _ -> AnimationError.overflow }; + handle animator_builder(0,"") { AnimationError.invalid_name -> {ok(b)}, _ -> AnimationError.overflow }; + handle b.build() { AnimationError.empty_animator -> {ok(a)}, _ -> AnimationError.overflow }; + handle b.remove_clip("missing") { AnimationError.unknown_clip -> {ok(())}, _ -> AnimationError.overflow }; + handle b.end_clip() { AnimationError.no_open_clip -> {ok(())}, _ -> AnimationError.overflow }; + let end=162000002; + b.begin_clip("jump",PlaybackMode.Once)!; + handle b.build() { AnimationError.unfinished_clip -> {ok(a)}, _ -> AnimationError.overflow }; + b.add_frame(0,1)!;b.end_clip()!; + handle b.build() { AnimationError.initial_clip_missing -> {ok(a)}, _ -> AnimationError.overflow }; + b.begin_clip("discard",PlaybackMode.Loop)!;b.add_frame(1,1)!;b.discard_clip()!; + handle b.build() { AnimationError.initial_clip_missing -> {ok(a)}, _ -> AnimationError.overflow }; + if a.sprite().glyph_id!=7 {let fail=1/0;} + return ok(42); + """); + var manifest = new StringBuilder("basic\n"); + for (var entry : cases.entrySet()) { + for (var suffix : new String[]{"", "-optimized"}) + PbsRuntimeAlignmentTest.compile("animation-"+entry.getKey()+suffix, + core()+build+"declare service Probe { fn main() -> result int {"+entry.getValue()+"} }", SourceKind.PROJECT); + manifest.append(entry.getKey()).append('\n'); + } + java.nio.file.Files.writeString(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("pbs-animation-manifest.txt"), manifest); + } + + @Test void privateCyclesHaveAnExplicitNativeGcOracle() throws Exception { + String source=core()+""" + fn keep(owners: array) -> result { + let b=animator_builder(3,"idle")!;b.begin_clip("idle",PlaybackMode.Loop)!; + b.add_frame(7,2)!;b.add_frame(11,3)!;b.add_frame(4,1)!;b.end_clip()!; + owners[0]=b.build()!;return ok(()); + } + fn churn() -> result { + for i:int from 0 until 200 { let b=animator_builder(0,"x")!;b.begin_clip("x",PlaybackMode.Once)!;b.add_frame(0,1)!;b.end_clip()!;b.build(); } + return ok(()); + } + declare service Probe { fn main() -> result int { + let owners:array = new array(1);keep(owners)!; + for round:int from 0 until 2 { + if round==1 { owners.clear(0); }churn()!; + let marker=314159; + } + return ok(42); + } } + """; + for(String suffix:new String[]{"","-optimized"}){ + var module=PbsRuntimeAlignmentTest.compile("animation-gc"+suffix,source,SourceKind.PROJECT); + module=PbsStructuredValuesTest.withTestSafepoint(module); + java.nio.file.Files.write(java.nio.file.Path.of(System.getProperty("pbs.registryConformanceDirectory")).resolve("pbs-animation-gc"+suffix+".pbx"),module.serialize()); + } + } + + @Test void actualCoreImportsFactoriesAndConstructionBoundary(@org.junit.jupiter.api.io.TempDir java.nio.file.Path root) throws Exception { + java.nio.file.Files.createDirectories(root.resolve("src")); + java.nio.file.Files.writeString(root.resolve("prometeu.json"), """ + {"name":"app","version":"1.0.0","language":"pbs","stdlib":"1","target":"Game","dependencies":[]} + """); + java.nio.file.Files.writeString(root.resolve("src/mod.barrel"),"pub fn frame() -> void;"); + String imports="import { Sprite, SpriteView, SpriteError, make_sprite } from @core:sprite;\nimport { Animator, AnimatorBuilder, AnimationError, PlaybackMode, animator_builder } from @core:animation;\n"; + java.nio.file.Files.writeString(root.resolve("src/main.pbs"),imports+""" + fn verify() -> result { + let b=animator_builder(3,"idle")!;b.begin_clip("idle",PlaybackMode.Loop)!; + b.add_frame(7,2)!;b.end_clip()!;let a=b.build()!;a.play("idle")!;a.advance(2)!; + if a.sprite().glyph_id!=7 { let fail=1/0; } return ok(()); + } + [Frame] fn frame() -> void { verify(); } + """); + var context=p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())); + var analysis=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(context,p.studio.utilities.logs.LogAggregator.stdout()); + assertFalse(analysis.diagnostics().stream().anyMatch(d->d.isError()),analysis.diagnostics().toString()); + var compiled=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.compile(p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),p.studio.utilities.logs.LogAggregator.stdout()); + assertTrue(compiled.bytecodeBytes().length>0); + java.nio.file.Files.writeString(root.resolve("src/main.pbs"),imports+"[Frame] fn frame() -> void { let forged=new Sprite(3,7); }"); + analysis=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),p.studio.utilities.logs.LogAggregator.stdout()); + assertTrue(analysis.diagnostics().stream().anyMatch(d->d.getCode().equals("E_SEM_STDLIB_FACTORY_ONLY")),analysis.diagnostics().toString()); + for(String construction:new String[]{"new Alias(3,7)","new Alias.make(3,7)"}){ + java.nio.file.Files.writeString(root.resolve("src/main.pbs"),"import { Sprite as Alias } from @core:sprite;[Frame] fn frame()->void {let bad="+construction+";}"); + var denied=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),p.studio.utilities.logs.LogAggregator.stdout()); + assertTrue(denied.diagnostics().stream().anyMatch(d->d.getCode().equals("E_SEM_STDLIB_FACTORY_ONLY")),denied.diagnostics().toString()); + } + java.nio.file.Files.writeString(root.resolve("src/main.pbs"),"[StdlibFactoryOnly] declare struct Forged(value:int) {} [Frame]fn frame()->void{}"); + var forged=p.studio.compiler.workspaces.BuilderPipelineService.INSTANCE.analyze(p.studio.compiler.models.BuilderPipelineContext.fromConfig(new p.studio.compiler.messages.BuilderPipelineConfig(false,root.toString())),p.studio.utilities.logs.LogAggregator.stdout()); + assertTrue(forged.diagnostics().stream().anyMatch(d->d.isError())); + + } + +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendLanguageService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendLanguageService.java index 245c05eb..939bf61e 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendLanguageService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/PBSFrontendLanguageService.java @@ -82,13 +82,20 @@ public final class PBSFrontendLanguageService implements FrontendLanguageService if (text.isEmpty()) return Optional.empty(); final boolean bundled = surface.sourceKindByFile().get(entry.getKey()) == SourceKind.SDK_INTERFACE; final Path owner = surface.ownerRootByFile().get(entry.getKey()); - final boolean external = bundled || owner == null || !owner.toAbsolutePath().normalize().equals(request.projectRoot().toAbsolutePath().normalize()); + final boolean generated = path.toAbsolutePath().normalize().startsWith(Path.of("/virtual/generated/animations")); + final boolean external = generated || bundled || owner == null || !owner.toAbsolutePath().normalize().equals(request.projectRoot().toAbsolutePath().normalize()); final var source = new FrontendSourceDocument(path, text.orElseThrow(), - bundled ? "bundled" : external ? "dependency" : "project", + generated ? "generated" : bundled ? "bundled" : external ? "dependency" : "project", handle.getRelativePath().toString(), "pbs", external, new FrontendEditorialContext(entry.getValue(), surface.supplementalTopDeclsByFile().getOrDefault(entry.getKey(), ReadOnlyList.empty()), - context.semanticContext(), files, surface)); + context.semanticContext(), files, surface), + generated && context.semanticContext() instanceof FESurfaceContext animationContext + ? animationContext.animations().stream().map(p.studio.compiler.services.PbsAnimationProjection::generate) + .filter(g->g.path().equals(path)).flatMap(g->g.origins().stream()).toList() : List.of(), + generated && context.semanticContext() instanceof FESurfaceContext animationContext + ? animationContext.animations().stream().map(p.studio.compiler.services.PbsAnimationProjection::generate) + .filter(g->g.path().equals(path)).map(p.studio.compiler.services.PbsAnimationProjection.Generated::revision).findFirst().orElse("") : ""); // A dependency may physically overlap a project source root. External // ownership wins even if another file-table entry treats it as local. if (external) return Optional.of(source); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsCallableSlotCounter.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsCallableSlotCounter.java index 3c937f76..5242a3c7 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsCallableSlotCounter.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsCallableSlotCounter.java @@ -11,7 +11,7 @@ public final class PbsCallableSlotCounter { final PbsAst.TypeRef returnType) { return switch (returnKind) { case INFERRED_UNIT, EXPLICIT_UNIT -> 0; - case RESULT -> 1; + case RESULT -> 1 + Math.max(0, typeSlots(returnType)); case PLAIN -> Math.max(0, typeSlots(returnType)); }; } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsStdlibConstruction.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsStdlibConstruction.java new file mode 100644 index 00000000..e190f191 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsStdlibConstruction.java @@ -0,0 +1,19 @@ +package p.studio.compiler.pbs; + +import p.studio.compiler.pbs.ast.PbsAst; +import p.studio.utilities.structures.ReadOnlyList; + +/** Trusted declaration identity survives aliases/reexports; same-module admission is explicit. */ +public final class PbsStdlibConstruction { + private PbsStdlibConstruction() {} + public static boolean factoryOnly(PbsAst.TopDecl declaration) { + return declaration instanceof PbsAst.StructDecl s + && PbsSdkCollections.attribute(s.attributes(), "StdlibFactoryOnly") != null; + } + public static boolean allowed(PbsAst.TopDecl declaration, PbsAst.File file, ReadOnlyList supplemental) { + if (!factoryOnly(declaration)) return true; + if (file.topDecls().stream().anyMatch(d -> d.span().equals(declaration.span()))) return true; + return supplemental.stream().anyMatch(d -> d instanceof PbsAst.TypeBindingDecl binding + && binding.sameModule() && binding.span().getFileId().equals(file.span().getFileId()) && binding.declaration().span().equals(declaration.span())); + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java index 72e348db..0a237dab 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAst.java @@ -227,7 +227,9 @@ public final class PbsAst { } /** Imported lexical binding; retains the original declaration and the importing source scope. */ - public record TypeBindingDecl(String name, TopDecl declaration, Span span) implements TopDecl {} + public record TypeBindingDecl(String name, TopDecl declaration, Span span, boolean sameModule) implements TopDecl { + public TypeBindingDecl(String name, TopDecl declaration, Span span) { this(name, declaration, span, false); } + } public record HostDecl( String name, diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java index e7756c7d..ebc6d5c8 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/ast/PbsAstRewriter.java @@ -44,7 +44,7 @@ public class PbsAstRewriter { map(b.signatures(), this::signature), b.attributes(), b.span()); case PbsAst.GlobalDecl g -> new PbsAst.GlobalDecl(g.name(), type(g.explicitType()), expression(g.initializer(), type(g.explicitType())), g.span()); case PbsAst.ConstDecl c -> new PbsAst.ConstDecl(c.name(), type(c.explicitType()), expression(c.initializer(), type(c.explicitType())), c.attributes(), c.span()); - case PbsAst.TypeBindingDecl b -> new PbsAst.TypeBindingDecl(b.name(), declaration(b.declaration()), b.span()); + case PbsAst.TypeBindingDecl b -> new PbsAst.TypeBindingDecl(b.name(), declaration(b.declaration()), b.span(), b.sameModule()); case PbsAst.EnumDecl e -> e; case PbsAst.ErrorDecl e -> e; case PbsAst.InvalidDecl i -> i; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java index c37ad9fe..3fea2f57 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java @@ -49,6 +49,8 @@ final class PbsExecutableBodyLowerer { var separator=callableName.indexOf('.'); if(separator>0 && metadataIndex.types().services.containsKey(callableName.substring(0,separator))) context.serviceOwner=callableName.substring(0,separator); context.returnType = functionDecl.returnType(); + context.returnKind = functionDecl.returnKind(); + context.resultErrorType = functionDecl.resultErrorType(); int captureIndex = 0; for (var capture : metadataIndex.types().capturesByFunction.getOrDefault(functionDecl.name(), java.util.List.of())) { var type = capture.typeRef(); @@ -91,7 +93,7 @@ final class PbsExecutableBodyLowerer { } else terminated = lowerBlock(functionDecl.body(), context); finalizeFunctionInstructions(functionDecl, context, terminated); - final var returnSlots = functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? context.types().slots(functionDecl.returnType()) : 0; + final var returnSlots = context.types().returnSlots(functionDecl.returnKind(), functionDecl.returnType()); final int maxStackSlots; try { maxStackSlots = stackAnalyzer.analyzeMaxStackSlots(ReadOnlyList.wrap(context.instructions()), returnSlots); @@ -450,14 +452,10 @@ final class PbsExecutableBodyLowerer { case PbsAst.ElseExpr elseExpr -> lowerOptionalFallback(elseExpr, context); case PbsAst.IfExpr ifExpr -> lowerIfExpression(ifExpr, context); case PbsAst.SwitchExpr switchExpr -> lowerSwitch(switchExpr, context); - case PbsAst.HandleExpr handleExpr -> lowerUnsupportedExpression( - handleExpr.value(), - "handle expression is not lowerable in executable lowering v1", - handleExpr.span(), - context); + case PbsAst.HandleExpr handleExpr -> lowerHandle(handleExpr, context); case PbsAst.AsExpr asExpr -> lowerConversion(asExpr, context); case PbsAst.MemberExpr memberExpr -> lowerMemberExpression(memberExpr, context); - case PbsAst.PropagateExpr propagateExpr -> lowerExpression(propagateExpr.expression(), context); + case PbsAst.PropagateExpr propagateExpr -> lowerPropagate(propagateExpr, context); case PbsAst.GroupExpr groupExpr -> lowerExpression(groupExpr.expression(), context); case PbsAst.NewExpr newExpr -> { if (newExpr.typeName().equals("array")) { @@ -479,7 +477,12 @@ final class PbsExecutableBodyLowerer { lowerExpected(someExpr.value(), payload, context); wrapOptional(payload, someExpr.span(), context); } - case PbsAst.OkExpr okExpr -> lowerExpression(okExpr.value(), context); + case PbsAst.OkExpr okExpr -> { + lowerExpected(okExpr.value(), context.returnType, context); + int payload = save(context.types().slots(context.returnType), okExpr.span(), context); + emitPushI32(0, okExpr.span(), context); + emitLoadLocalSlots(payload, context.types().slots(context.returnType), okExpr.span(), context); + } case PbsAst.TupleExpr tupleExpr -> { var expected = context.expectedType; for (int index=0; index emitDefault(context.types().registryType(context.expectedType), 1, value.span(), context); - case PbsAst.ErrExpr ignored -> { - } + case PbsAst.ErrExpr error -> emitResultError(error.errorPath(), error.span(), context); case PbsAst.UnitExpr ignored -> { } } @@ -663,7 +665,7 @@ final class PbsExecutableBodyLowerer { return; } if (receiverType != null && receiverType.kind() == PbsAst.TypeRefKind.NAMED_TUPLE) { - lowerExpression(memberExpr.receiver(),context); + lowerExpected(memberExpr.receiver(),receiverType,context); int slot=save(context.types().slots(receiverType),memberExpr.span(),context); int offset=0; for(var field:receiverType.fields()) { @@ -886,6 +888,8 @@ final class PbsExecutableBodyLowerer { if (expression == null) { return 0; } + var resultSignature = resultSignature(expression, context); + if (resultSignature != null) return context.types().returnSlots(resultSignature.returnKind(), resultSignature.returnType()); var resolvedType = expressionType(expression, context); if (resolvedType != null) return context.types().slots(resolvedType); return switch (expression) { @@ -1171,6 +1175,8 @@ final class PbsExecutableBodyLowerer { private PbsAst.TypeRef expressionType(PbsAst.Expression e, PbsExecutableLoweringContext c) { if (e == null) return null; + if (e instanceof PbsAst.PropagateExpr p) return expressionType(p.expression(), c); + if (e instanceof PbsAst.HandleExpr h) return expressionType(h.value(), c); if (e instanceof PbsAst.LambdaExpr lambda) return lambda.functionType(); if (e instanceof PbsAst.ArrayLiteralExpr || e instanceof PbsAst.NoneExpr) return c.expectedType; if (e instanceof PbsAst.TupleExpr tuple) return PbsAst.TypeRef.namedTuple(ReadOnlyList.wrap(tuple.items().stream() @@ -1751,6 +1757,115 @@ final class PbsExecutableBodyLowerer { null, "", null, null, null, "", "", pops, pushes, span, new IRRegistryInstruction(kind,type,null,null,field))); } + private PbsAst.FunctionSignature resultSignature(PbsAst.Expression expression, PbsExecutableLoweringContext c) { + if (expression instanceof PbsAst.GroupExpr group) return resultSignature(group.expression(), c); + if (expression instanceof PbsAst.ApplyExpr apply) return resultSignature(applyCall(apply), c); + if (!(expression instanceof PbsAst.CallExpr call)) return null; + PbsAst.FunctionSignature signature = null; + var free = sourceFunction(call, c); + if (free != null) signature = new PbsAst.FunctionSignature(free.name(), free.parameters(), free.returnKind(), + free.returnType(), free.resultErrorType(), free.attributes(), free.span()); + if (call.callee() instanceof PbsAst.MemberExpr member) { + var owner = PbsRuntimeTypes.unwrap(expressionType(member.receiver(), c)); + if (owner != null) { + var contract = c.types().contract(owner); + if (contract != null) signature = contract.signatures().stream().filter(m -> + m.name().equals(member.memberName()) && parametersMatch(m.parameters(), call.arguments(), c)) + .findFirst().orElse(null); + else signature = c.types().signatures.get(owner.name() + "." + member.memberName() + "#" + call.arguments().size()); + } + } + if (signature == null) signature = c.types().signatures.get(PbsRuntimeTypes.path(call.callee()) + "#" + call.arguments().size()); + return signature != null && signature.returnKind() == PbsAst.ReturnKind.RESULT ? signature : null; + } + + private void clearPendingStack(Span span, PbsExecutableLoweringContext c) { + int pending = stackAnalyzer.pendingStackSlots(ReadOnlyList.wrap(c.instructions())); + for (int i = 0; i < pending; i++) + c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.POP, "", null, null, span)); + } + + private void emitInactivePayload(PbsAst.TypeRef payload, Span span, PbsExecutableLoweringContext c) { + for (var part : c.types().results(payload)) { + var declaration = c.types().registry().types().stream().filter(d -> d.identity().equals(part)).findFirst().orElseThrow(); + if (declaration.body() instanceof IRRegistry.Builtin builtin) { + switch (builtin.id()) { + case 0x10 -> emitPushI32(0, span, c); + case 0x11, 1 -> emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64, "0", span, c); + case 0x12 -> emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, "0.0", span, c); + case 0x13 -> emitPushBool(false, span, c); + case 2 -> { emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, "0.0", span, c); emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_F64, "0.0", span, c); } + case 3 -> { for (int i = 0; i < 3; i++) emitLiteral(IRBackendExecutableFunction.InstructionKind.PUSH_I64, "0", span, c); } + default -> emitNullGroup(registryWidth(part, c), span, c); + } + } else emitNullGroup(registryWidth(part, c), span, c); + } + } + + /** Extra locals start Null in the existing VM; these reserved slots are never assigned. */ + private void emitNullGroup(int width, Span span, PbsExecutableLoweringContext c) { + int slot = c.declareLocalSlots(c.nextLabel("inactive_null"), width); + emitLoadLocalSlots(slot, width, span, c); + } + + private void emitResultError(PbsAst.ErrorPath path, Span span, PbsExecutableLoweringContext c) { + emitPushI32(c.types().errorCode(path), span, c); + emitInactivePayload(c.returnType, span, c); + } + + private void lowerPropagate(PbsAst.PropagateExpr expression, PbsExecutableLoweringContext c) { + var signature = resultSignature(expression.expression(), c); + if (signature == null) { reportUnsupportedLowering("Propagation requires an exact result signature", expression.span(), c); return; } + lowerExpected(expression.expression(), signature.returnType(), c); + int width = c.types().slots(signature.returnType()); + int group = save(1 + width, expression.span(), c); + var success = c.nextLabel("result_success"); + emitGetLocal(group, expression.span(), c); emitPushI32(0, expression.span(), c); + emitBinaryOperatorInstruction("==", expression.span(), c); + emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE, success, expression.span(), c); + clearPendingStack(expression.span(), c); + emitGetLocal(group, expression.span(), c); emitInactivePayload(c.returnType, expression.span(), c); + c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET, "", null, null, expression.span())); + emitLabel(success, expression.span(), c); emitLoadLocalSlots(group + 1, width, expression.span(), c); + } + + private void lowerHandle(PbsAst.HandleExpr expression, PbsExecutableLoweringContext c) { + var signature = resultSignature(expression.value(), c); + if (signature == null) { reportUnsupportedLowering("Handle requires an exact result signature", expression.span(), c); return; } + lowerExpected(expression.value(), signature.returnType(), c); + int width = c.types().slots(signature.returnType()); + int group = save(1 + width, expression.span(), c); + var success = c.nextLabel("handle_success"); var end = c.nextLabel("handle_end"); + emitGetLocal(group, expression.span(), c); emitPushI32(0, expression.span(), c); + emitBinaryOperatorInstruction("==", expression.span(), c); + emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_TRUE, success, expression.span(), c); + for (var arm : expression.arms()) { + var next = c.nextLabel("handle_next"); + if (arm.pattern() instanceof PbsAst.ErrorPathHandlePattern pattern) { + emitGetLocal(group, arm.span(), c); emitPushI32(c.types().errorCode(pattern.path()), arm.span(), c); + emitBinaryOperatorInstruction("==", arm.span(), c); + emitJump(IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE, next, arm.span(), c); + } + var scope = c.snapshotScope(); + if (arm.block() != null) for (var statement : arm.block().statements()) lowerStatement(statement, c); + var terminal = arm.block() == null ? null : arm.block().tailExpression(); + while (terminal instanceof PbsAst.GroupExpr g) terminal = g.expression(); + var error = arm.remapTarget() != null ? arm.remapTarget() : terminal instanceof PbsAst.ErrExpr e ? e.errorPath() : null; + if (error != null) { + clearPendingStack(arm.span(), c); emitResultError(error, arm.span(), c); + c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.RET, "", null, null, arm.span())); + } else if (terminal instanceof PbsAst.OkExpr ok) { + lowerExpected(ok.value(), signature.returnType(), c); + emitJump(IRBackendExecutableFunction.InstructionKind.JMP, end, arm.span(), c); + } + c.restoreScope(scope); emitLabel(next, arm.span(), c); + } + // Static semantics proves exhaustiveness. An invalid code cannot become a payload. + c.instructions().add(new IRBackendExecutableFunction.Instruction(IRBackendExecutableFunction.InstructionKind.TRAP, "", null, null, expression.span())); + emitLabel(success, expression.span(), c); emitLoadLocalSlots(group + 1, width, expression.span(), c); + emitLabel(end, expression.span(), c); + } + private void emitDefault(IRRegistry.TypeRef type, int width, Span span, PbsExecutableLoweringContext c) { var holder = c.types().holder(type); registry(STRUCT_NEW,holder,0,0,1,span,c); @@ -1899,7 +2014,11 @@ final class PbsExecutableBodyLowerer { return hasElseBranch(stmt)&&yes&&no; } private void lowerStructNew(PbsAst.NewExpr expr,PbsExecutableLoweringContext c) { - var declaration=c.types().structs.get(expr.typeName());var ref=c.types().registryType(PbsRuntimeTypes.type(expr.typeName())); + var declaration=c.types().structs.get(expr.typeName()); + if (p.studio.compiler.pbs.PbsStdlibConstruction.factoryOnly(declaration) && !c.types().allowedFactoryOrigins.contains(declaration.span())) { + reportUnsupportedLowering("Stdlib construction requires its canonical declaring module", expr.span(), c); return; + } + var ref=c.types().registryType(PbsRuntimeTypes.type(expr.typeName())); if (p.studio.compiler.pbs.PbsSdkMemcard.isBuffer(declaration)) { if (expr.arguments().size()!=1 || expr.ctorName()!=null && !expr.ctorName().equals("make")) { reportUnsupportedLowering("MemcardBuffer requires one int capacity",expr.span(),c); @@ -1975,7 +2094,7 @@ final class PbsExecutableBodyLowerer { pops += c.types().slots(type); } emitStructuredFunction(name.name(),method.parameters().stream().map(PbsAst.Parameter::typeRef).toList(), - method.returnType(),pops,c.types().slots(method.returnType()),call.span(),c); + method.returnType(),method.returnKind(),method.resultErrorType(),pops,c.types().returnSlots(method.returnKind(),method.returnType()),call.span(),c); return true; } if(!(call.callee() instanceof PbsAst.MemberExpr member))return false; @@ -1994,7 +2113,7 @@ final class PbsExecutableBodyLowerer { int pops=2; for(int i=0;i receiverParameters(String owner, ReadOnlyList parameters) { var types = new java.util.ArrayList(); @@ -2102,7 +2221,12 @@ final class PbsExecutableBodyLowerer { private void emitStructuredFunction(String name, java.util.List parameters, PbsAst.TypeRef returnType, int pops, int pushes, Span span, PbsExecutableLoweringContext c) { - var callableId = c.exactLocalCallable(name, parameters, returnType); + emitStructuredFunction(name, parameters, returnType, PbsAst.ReturnKind.PLAIN, null, pops, pushes, span, c); + } + + private void emitStructuredFunction(String name, java.util.List parameters, PbsAst.TypeRef returnType, + PbsAst.ReturnKind kind, PbsAst.TypeRef errorType, int pops, int pushes, Span span, PbsExecutableLoweringContext c) { + var callableId = c.exactLocalCallable(name, parameters, returnType, kind, errorType); if (callableId == null) { reportUnsupportedLowering("Structured call requires exact overload: " + name, span, c); return; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringContext.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringContext.java index 2c5698c4..329d5075 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringContext.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringContext.java @@ -27,6 +27,8 @@ final class PbsExecutableLoweringContext { p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType; PbsExecutableCallableRegistry callableRegistry() { return callableRegistry; } PbsRuntimeTypes types() { return metadataIndex.types(); } + p.studio.compiler.pbs.ast.PbsAst.ReturnKind returnKind; + p.studio.compiler.pbs.ast.PbsAst.TypeRef resultErrorType; String serviceOwner; private int nextLabelId = 0; private int nextLocalSlot; @@ -97,10 +99,20 @@ final class PbsExecutableLoweringContext { p.studio.compiler.source.identifiers.CallableId exactLocalCallable(String name, java.util.List parameterTypes, p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType) { + return exactLocalCallable(name, parameterTypes, returnType, p.studio.compiler.pbs.ast.PbsAst.ReturnKind.PLAIN, null); + } + + p.studio.compiler.source.identifiers.CallableId exactLocalCallable(String name, + java.util.List parameterTypes, + p.studio.compiler.pbs.ast.PbsAst.TypeRef returnType, + p.studio.compiler.pbs.ast.PbsAst.ReturnKind kind, + p.studio.compiler.pbs.ast.PbsAst.TypeRef errorType) { for (var callable : callableRegistry.localCallables()) { var parameters = callable.functionDecl().parameters(); if (!callable.callableName().equals(name) || parameters.size() != parameterTypes.size()) continue; - boolean matches = true; + boolean matches = (callable.functionDecl().returnKind() == p.studio.compiler.pbs.ast.PbsAst.ReturnKind.RESULT) + == (kind == p.studio.compiler.pbs.ast.PbsAst.ReturnKind.RESULT) + && types().key(callable.functionDecl().resultErrorType()).equals(types().key(errorType)); for (int i = 0; i < parameters.size(); i++) matches &= types().key(parameters.get(i).typeRef()).equals(types().key(parameterTypes.get(i))); matches &= types().shapeKey(callable.functionDecl().returnType()).equals(types().shapeKey(returnType)); @@ -111,10 +123,13 @@ final class PbsExecutableLoweringContext { .collect(java.util.stream.Collectors.joining(",")) + ")->"; var output = returnType == null || returnType.kind() == p.studio.compiler.pbs.ast.PbsAst.TypeRefKind.UNIT ? "unit" : formatter.typeSurfaceKey(returnType); + if (kind == p.studio.compiler.pbs.ast.PbsAst.ReturnKind.RESULT) + output = "result<" + formatter.typeSurfaceKey(errorType) + ">" + formatter.typeSurfaceKey(returnType); + final var expectedOutput = output; var importedIds = callableIdsByNameAndArity().getOrDefault(new PbsCallableResolutionKey(nameTable().register(name), parameterTypes.size()), java.util.List.of()); var candidates = callableSignatureByCallableId().entrySet().stream().filter(entry -> importedIds.contains(entry.getKey()) && entry.getValue().arity() == parameterTypes.size() - && normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + output))).toList(); + && normalizeShape(entry.getValue().typeShape()).equals(normalizeShape(inputs + expectedOutput))).toList(); if (candidates.size() == 1) return candidates.getFirst().getKey(); return null; } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringService.java index c4dd144b..b590a4ab 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringService.java @@ -49,12 +49,12 @@ public final class PbsExecutableLoweringService { importedCallables, metadataIndex.types()); for (var entry : callableRegistry.callableSignatureByCallableId().entrySet()) { var signature = metadataIndex.types().signatures.get(entry.getValue().callableName()+"#"+entry.getValue().arity()); - if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), signature.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(signature.returnType()) : 0); + if (signature != null) callableRegistry.returnSlotsByCallableId().put(entry.getKey(), metadataIndex.types().returnSlots(signature.returnKind(), signature.returnType())); } for (var callable : callableRegistry.localCallables()) { var f=callable.functionDecl(); callableRegistry.returnSlotsByCallableId().put(callableRegistry.callableIdByDeclaration().get(callable), - f.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(f.returnType()) : 0); + metadataIndex.types().returnSlots(f.returnKind(), f.returnType())); metadataIndex.types().signatures.put(callable.callableName()+"#"+f.parameters().size(), new PbsAst.FunctionSignature(f.name(),f.parameters(),f.returnKind(),f.returnType(),f.resultErrorType(),f.attributes(),f.span())); } @@ -65,6 +65,8 @@ public final class PbsExecutableLoweringService { var candidates = callableRegistry.localCallables().stream().filter(callable -> callable.callableName().equals(metadataIndex.types().implementationCallableName(implementation, signature.name())) && callable.functionDecl().parameters().size()==signature.parameters().size()+1 + && callable.functionDecl().returnKind() == signature.returnKind() + && metadataIndex.types().key(callable.functionDecl().resultErrorType()).equals(metadataIndex.types().key(signature.resultErrorType())) && metadataIndex.types().shapeKey(callable.functionDecl().returnType()).equals(metadataIndex.types().shapeKey(signature.returnType())) && java.util.stream.IntStream.range(0, signature.parameters().size()).allMatch(i -> metadataIndex.types().key(callable.functionDecl().parameters().get(i+1).typeRef()).equals( @@ -151,7 +153,7 @@ public final class PbsExecutableLoweringService { safeToInt(functionDecl.span().getEnd()), functionDecl.parameters().stream().mapToInt(p -> metadataIndex.types().slots(p.typeRef())).sum(), loweredBody.localSlots(), - functionDecl.returnKind() == PbsAst.ReturnKind.PLAIN ? metadataIndex.types().slots(functionDecl.returnType()) : 0, + metadataIndex.types().returnSlots(functionDecl.returnKind(), functionDecl.returnType()), loweredBody.maxStackSlots(), loweredBody.instructions(), functionDecl.span(), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableStackAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableStackAnalyzer.java index 102b36f4..f047648f 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableStackAnalyzer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableStackAnalyzer.java @@ -10,8 +10,17 @@ final class PbsExecutableStackAnalyzer { int analyzeMaxStackSlots( final ReadOnlyList instructions, final int returnSlots) { + return analyze(instructions, returnSlots, false)[0]; + } + + int pendingStackSlots(ReadOnlyList instructions) { + return analyze(instructions, 0, true)[1]; + } + + private int[] analyze(ReadOnlyList instructions, + int returnSlots, boolean prefix) { if (instructions.isEmpty()) { - return Math.max(1, returnSlots); + return new int[]{Math.max(1, returnSlots), 0}; } final var labelToIndex = new HashMap(); @@ -31,6 +40,7 @@ final class PbsExecutableStackAnalyzer { worklist.add(0); var maxHeight = 0; + var tailHeight = 0; while (!worklist.isEmpty()) { final var index = worklist.removeFirst(); visited.add(index); @@ -43,7 +53,7 @@ final class PbsExecutableStackAnalyzer { case POP, SET_LOCAL, SET_GLOBAL -> { if (outHeight <= 0) { throw new ExecutableLoweringAnalysisException( - "stack underflow at " + instruction.kind().name().toLowerCase() + ": need=1 have=" + outHeight); + "stack underflow at " + index + " " + instruction.kind().name().toLowerCase() + " " + instruction.span().getStart() + ": need=1 have=" + outHeight); } outHeight -= 1; } @@ -57,7 +67,7 @@ final class PbsExecutableStackAnalyzer { case NOT, NEG -> { if (outHeight <= 0) { throw new ExecutableLoweringAnalysisException( - "stack underflow at " + instruction.kind().name().toLowerCase() + ": need=1 have=" + outHeight); + "stack underflow at " + index + " " + instruction.kind().name().toLowerCase() + " " + instruction.span().getStart() + ": need=1 have=" + outHeight); } } case REGISTRY, CALL_FUNC -> { @@ -110,17 +120,18 @@ final class PbsExecutableStackAnalyzer { || instruction.kind() == IRBackendExecutableFunction.InstructionKind.JMP_IF_FALSE) { final var targetIndex = labelToIndex.get(instruction.targetLabel()); if (targetIndex == null) { - throw new ExecutableLoweringAnalysisException("missing jump target label: " + instruction.targetLabel()); + if (!prefix) throw new ExecutableLoweringAnalysisException("missing jump target label: " + instruction.targetLabel()); } - successors.add(targetIndex); + if (targetIndex != null) successors.add(targetIndex); if (instruction.kind() == IRBackendExecutableFunction.InstructionKind.JMP) { - mergeIncomingHeights(incomingHeightByInstruction, worklist, targetIndex, outHeight); + if (targetIndex != null) mergeIncomingHeights(incomingHeightByInstruction, worklist, targetIndex, outHeight); continue; } } final var nextIndex = index + 1; if (nextIndex >= instructions.size()) { + if (prefix) { tailHeight = outHeight; continue; } throw new ExecutableLoweringAnalysisException("reachable path ends without terminal instruction"); } successors.add(nextIndex); @@ -129,10 +140,10 @@ final class PbsExecutableStackAnalyzer { } } - if (!visited.contains(instructions.size() - 1)) { + if (!prefix && !visited.contains(instructions.size() - 1)) { throw new ExecutableLoweringAnalysisException("entrypoint does not reach function tail"); } - return Math.max(1, Math.max(maxHeight, returnSlots)); + return new int[]{Math.max(1, Math.max(maxHeight, returnSlots)), tailHeight}; } private void mergeIncomingHeights( diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java index 91295690..97640d2f 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsRuntimeTypes.java @@ -14,12 +14,14 @@ final class PbsRuntimeTypes { final Map builtinNames; final Map aliases = new HashMap<>(); final Map> fields = new HashMap<>(); + final Map errors = new LinkedHashMap<>(); final Map enums = new HashMap<>(); final Map signatures = new HashMap<>(); final Map> functions = new HashMap<>(); final Map values = new HashMap<>(); final Map constants = new HashMap<>(); private final Map used = new TreeMap<>(); + final Set allowedFactoryOrigins = new HashSet<>(); final Map structs = new LinkedHashMap<>(); final Map contracts = new LinkedHashMap<>(); final p.studio.compiler.pbs.PbsContractTypes contractTypes; @@ -29,6 +31,8 @@ final class PbsRuntimeTypes { PbsRuntimeTypes(PbsAst.File ast, ReadOnlyList supplemental, Map builtins) { builtinNames = builtins; + ast.topDecls().forEach(d -> allowedFactoryOrigins.add(d.span())); + supplemental.forEach(d -> { if (d instanceof PbsAst.TypeBindingDecl b && b.sameModule() && b.span().getFileId().equals(ast.span().getFileId())) allowedFactoryOrigins.add(b.declaration().span()); }); contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplemental, p.studio.compiler.source.diagnostics.DiagnosticSink.empty()); for (var declaration : ast.topDecls()) if (declaration instanceof PbsAst.ImplementsDecl implementation) implementations.add(implementation); @@ -43,6 +47,7 @@ final class PbsRuntimeTypes { if (decl instanceof PbsAst.ContractDecl c) contracts.put(c.name(), c); if (decl instanceof PbsAst.ServiceDecl s) services.put(s.name(), s); if (decl instanceof PbsAst.EnumDecl e) enums.put(e.name(), e); + if (decl instanceof PbsAst.ErrorDecl e) errors.put(e.name(), e); if (decl instanceof PbsAst.ConstDecl c) values.put(c.name(), c.explicitType()); if (decl instanceof PbsAst.GlobalDecl g) values.put(g.name(), g.explicitType()); if (decl instanceof PbsAst.FunctionDecl f) { @@ -119,6 +124,7 @@ final class PbsRuntimeTypes { if (origin != null) return nominal + ":" + origin.key(); return t.arguments().isEmpty() ? nominal : nominal + ":" + contractTypes.key(t); } + if (contractTypes.declaration(t) instanceof PbsAst.ErrorDecl error) return nominalKey("error", error.span()); return canonical(t); } String shapeKey(PbsAst.TypeRef type) { @@ -206,7 +212,7 @@ final class PbsRuntimeTypes { for (var method : contract(t).signatures()) { var args = new ArrayList(); for(var arg : method.parameters()) for(var part : results(arg.typeRef())) args.add(new IRRegistry.NamedType(part,arg.name())); - methods.add(new IRRegistry.Method(method.name(),new IRRegistry.Signature(ReadOnlyList.wrap(args),ReadOnlyList.wrap(results(method.returnType()))))); + methods.add(new IRRegistry.Method(method.name(),new IRRegistry.Signature(ReadOnlyList.wrap(args),ReadOnlyList.wrap(returnTypes(method.returnKind(), method.returnType()))))); } used.put(ref.declarationKey(),new IRRegistry.TypeDeclaration(ref,contractTypes.display(t),new IRRegistry.Trait(ReadOnlyList.wrap(methods)))); } @@ -227,6 +233,27 @@ final class PbsRuntimeTypes { if(t.kind()==PbsAst.TypeRefKind.NAMED_TUPLE) return t.fields().stream().flatMap(f->results(f.typeRef()).stream()).toList(); return List.of(registryType(t)); } + int returnSlots(PbsAst.ReturnKind kind, PbsAst.TypeRef payload) { + return switch (kind) { + case RESULT -> 1 + slots(payload); + case PLAIN -> slots(payload); + default -> 0; + }; + } + List returnTypes(PbsAst.ReturnKind kind, PbsAst.TypeRef payload) { + if (kind == PbsAst.ReturnKind.PLAIN) return results(payload); + if (kind != PbsAst.ReturnKind.RESULT) return List.of(); + var group = new ArrayList(); + group.add(builtin(0x10)); group.addAll(results(payload)); return List.copyOf(group); + } + int errorCode(PbsAst.ErrorPath path) { + var resolved=contractTypes.declaration(PbsAst.TypeRef.simple(path.segments().getFirst(),path.span())); + var declaration=resolved instanceof PbsAst.ErrorDecl error?error:errors.get(aliases.getOrDefault(path.segments().getFirst(),path.segments().getFirst())); + if (declaration == null) throw new IllegalStateException("Missing canonical error declaration: " + path); + int index = declaration.cases().asList().indexOf(path.segments().getLast()); + if (index < 0) throw new IllegalStateException("Missing error case: " + path); + return index + 1; + } IRRegistry.FunctionMetadata metadata(PbsAst.FunctionDecl f) { // Preserve the pre-existing unsupported executable boundary for types outside this port. // The common backend still rejects missing typed metadata; never infer a carrier by width. @@ -235,7 +262,7 @@ final class PbsRuntimeTypes { private IRRegistry.FunctionMetadata supportedMetadata(PbsAst.FunctionDecl f) { var params=new ArrayList(); for(var p:f.parameters()) for(var type:results(p.typeRef())) params.add(new IRRegistry.NamedType(type,p.name())); - var returns=f.returnKind()==PbsAst.ReturnKind.PLAIN ? results(f.returnType()) : List.of(); + var returns=returnTypes(f.returnKind(), f.returnType()); var captures = capturesByFunction.getOrDefault(f.name(), List.of()).stream().flatMap(c -> results(c.typeRef()).stream()).toList(); return new IRRegistry.FunctionMetadata(new IRRegistry.Signature(ReadOnlyList.wrap(params),ReadOnlyList.wrap(returns)), ReadOnlyList.wrap(captures), switch (f.lifecycleMarker()) { diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java index ad834c73..b3ed2f8f 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/parser/PbsDeclarationParser.java @@ -696,7 +696,7 @@ final class PbsDeclarationParser { final String targetSurface) { for (final var attribute : attributes) { if ("Doc".equals(attribute.name()) || attribute.trustedSdkOrigin() && - java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap", "SdkStack", "SdkQueue", "SdkMemcardBuffer").contains(attribute.name()) && "struct declarations".equals(targetSurface)) { + java.util.Set.of("SdkList", "SdkLinked", "SdkSet", "SdkMap", "SdkStack", "SdkQueue", "SdkMemcardBuffer", "StdlibFactoryOnly").contains(attribute.name()) && "struct declarations".equals(targetSurface)) { continue; } p.studio.compiler.source.diagnostics.Diagnostics.error(context.diagnostics(), diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java index cd929e9f..f7efda8b 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsEditorialSupportService.java @@ -1483,6 +1483,7 @@ public final class PbsEditorialSupportService { } private List constructorSignaturesForTopDecl(final PbsAst.TopDecl topDecl) { + if (!p.studio.compiler.pbs.PbsStdlibConstruction.allowed(topDecl, ast, editorialSupplementalTopDecls)) return List.of(); if (topDecl instanceof PbsAst.StructDecl structDecl) { if (structDecl.ctors().isEmpty()) { return List.of(new PbsEditorialSignature(structDecl.name(), structDecl.name() + "()", List.of(), "unit")); diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java index ffa7f291..7056fe25 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowSemanticSupport.java @@ -217,6 +217,7 @@ final class PbsFlowSemanticSupport { return declaration instanceof PbsAst.StructDecl owner && owner.methods().stream() .anyMatch(m -> m.name().equals(member) && p.studio.compiler.pbs.PbsSdkCollections.attribute(m.attributes(), "SdkPrivate") != null); } + final Set allowedFactoryOrigins = new HashSet<>(); final Map> topLevelCallables = new HashMap<>(); final Map structs = new HashMap<>(); final Map services = new HashMap<>(); @@ -248,6 +249,9 @@ final class PbsFlowSemanticSupport { final var model = new Model(); model.contractTypes = new p.studio.compiler.pbs.PbsContractTypes(ast, supplementalTopDecls, diagnostics); model.contractTypes.validate(ast); + for (var declaration : ast.topDecls()) model.allowedFactoryOrigins.add(declaration.span()); + for (var declaration : supplementalTopDecls) if (declaration instanceof PbsAst.TypeBindingDecl binding && binding.sameModule() && binding.span().getFileId().equals(ast.span().getFileId())) + model.allowedFactoryOrigins.add(binding.declaration().span()); for (final var topDecl : ast.topDecls()) { model.registerKnownTopDecl(topDecl); } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java index 0689006a..29c31969 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java @@ -230,6 +230,13 @@ final class PbsFlowStructuralExpressionAnalyzer { return ExprResult.type(TypeView.optional(payloadExpected == null ? payload : payloadExpected)); } if (expression instanceof PbsAst.NewExpr newExpr) { + var declaredType = model.contractTypes.declaration(PbsAst.TypeRef.simple(newExpr.typeName(), newExpr.span())); + if (p.studio.compiler.pbs.PbsStdlibConstruction.factoryOnly(declaredType) + && !model.allowedFactoryOrigins.contains(declaredType.span())) { + Diagnostics.error(diagnostics, "E_SEM_STDLIB_FACTORY_ONLY", + "Construct this stdlib type through its public factory", newExpr.span()); + return ExprResult.type(TypeView.unknown()); + } if (p.studio.compiler.pbs.PbsSdkMemcard.isBuffer(model.contractTypes.declaration(PbsAst.TypeRef.simple(newExpr.typeName(), newExpr.span())))) { if (newExpr.arguments().size() != 1 || newExpr.ctorName() != null && !newExpr.ctorName().equals("make")) { Diagnostics.error(diagnostics, "E_SEM_MEMCARD_BUFFER_CONSTRUCTOR", diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsAnimationProjection.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsAnimationProjection.java new file mode 100644 index 00000000..078f3819 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsAnimationProjection.java @@ -0,0 +1,52 @@ +package p.studio.compiler.services; + +import p.animation.*; +import java.nio.file.Path; +import java.nio.charset.StandardCharsets; +import java.util.*; + +/** PBS-only deterministic projection; canonical persistence remains the JSON sidecar. */ +public final class PbsAnimationProjection { + public static final String VERSION="1"; + public record Generated(String moduleName,Path path,String source,String barrel,String revision,List origins) { + public Generated { origins=List.copyOf(origins); } + } + public static Generated generate(AnimationSource source) { + var text=new StringBuilder("import { Animator, AnimationError, PlaybackMode, animator_builder } from @core:animation;\n\n"); + var barrel=new StringBuilder();var origins=new ArrayList(); + var binding=new HashMap();source.document().bindings().forEach(b->binding.put(b.artifactId(),b)); + var definitions=new ArrayList<>(source.document().animators());definitions.sort(Comparator.comparing(AnimationDocument.Animator::id)); + for(var animator:definitions) { + int index=source.document().animators().indexOf(animator);String pointer="/animators/"+index; + String name="create_"+animator.id();String signature=name+"(bank_id: int) -> result Animator"; + barrel.append("pub fn ").append(signature).append(";\n"); + int begin=bytes(text);text.append("fn ").append(signature).append(" {\n"); + origins.add(new FrontendSourceDocument.OriginSpan(begin,bytes(text),source.definitionPath(),pointer+"/id",source.bank().assetUuid().toString())); + line(text,origins,source.definitionPath(),pointer+"/initial_clip"," let builder = animator_builder(bank_id, "+quote(animator.initialClip())+")!;\n"); + for(int c=0;cnew FrontendSourceDocument.OriginSpan(o.startOffset(),o.endOffset(),o.definitionPath(),o.jsonPointer(),source.bank().assetUuid().toString())).toList()); + } + private static int bytes(StringBuilder s){return s.toString().getBytes(StandardCharsets.UTF_8).length;} + private static void line(StringBuilder out,List spans,Path path,String pointer,String line){int start=bytes(out);out.append(line);spans.add(new FrontendSourceDocument.OriginSpan(start,bytes(out),path,pointer));} + public static String quote(String value){ + var out=new StringBuilder("\""); + for(int i=0;iout.append("\\\\");case '"'->out.append("\\\"");case '\n'->out.append("\\n");case '\r'->out.append("\\r");case '\t'->out.append("\\t"); + default->out.append(c); + }}return out.append('"').toString(); + } +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java index b6c3ae52..9fc74b95 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java @@ -84,7 +84,7 @@ final class PbsImportedSemanticContextService { if (sibling.fileId().equals(parsedSource.fileId())) continue; for (var declaration : sibling.ast().topDecls()) { if (isTypeDecl(declaration) || declaration instanceof PbsAst.FunctionDecl f && !f.typeParameters().isEmpty()) appendSupplementalTopDecl( - new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span()), supplementalTopDecls, supplementalKeys); + new PbsAst.TypeBindingDecl(topDeclName(declaration), declaration, parsedSource.ast().span(), true), supplementalTopDecls, supplementalKeys); if (declaration instanceof PbsAst.ImplementsDecl) appendSupplementalTopDecl(declaration, supplementalTopDecls, supplementalKeys); } } @@ -228,6 +228,37 @@ final class PbsImportedSemanticContextService { ReadOnlyList.wrap(declarations), context.importedCallables(), context.importedGlobals(), context.importedReservedMetadata())); } } while (changed); + // Factories expose usable concrete values even when callers do not import the + // return type explicitly. Preserve the declaring module for all such methods. + for(var source:parsedSourceFiles) { + var context=contexts.get(source.fileId()); + var declarations=new ArrayList<>(context.supplementalTopDecls().asList()); + var declarationKeys=new HashSet();declarations.forEach(d->declarationKeys.add(topDeclKey(d))); + var callables=new ArrayList<>(context.importedCallables().asList());var callableKeys=new HashSet(); + callables.forEach(c->callableKeys.add(c.moduleId().getIndex()+"#"+c.callableName()+"#"+c.arity()+"#"+c.shapeSurface())); + for(int index=0;index(struct.methods().asList()); + for(var ctor:struct.ctors())methods.add(new PbsAst.FunctionDecl("$ctor."+ctor.name(),ctor.parameters(),PbsAst.ReturnKind.EXPLICIT_UNIT, + PbsAst.TypeRef.unit(ctor.span()),null,ReadOnlyList.empty(),PbsAst.LifecycleMarker.NONE,ctor.body(),ctor.span())); + for(var method:methods) { + var executable=p.studio.compiler.pbs.lowering.PbsExecutableCallableRegistryFactory.withReceiver(method,struct.name(),"this"); + appendImportedCallable(callables,callableKeys,new PbsFrontendCompiler.ImportedCallableSurface(definingModule,local+"."+method.name(), + executable.parameters().size(),returnSlotsFor(executable),executable.returnKind(),executable.returnType(), + frontendCompiler.callableShapeSurfaceOf(executable),struct.name()+"."+method.name())); + } + for(var provider:sourcesByModule.getOrDefault(definingModule,new ArrayList<>()))for(var member:provider.ast().topDecls()) + if(member instanceof PbsAst.ImplementsDecl implementation&&implementation.ownerName().equals(struct.name())) { + appendSupplementalTopDecl(implementation,declarations,declarationKeys); + appendTypeDependencyDecls(implementation,topDeclsByNameByModule.getOrDefault(definingModule,Map.of()),declarations,declarationKeys); + } + } + contexts.put(source.fileId(),new PbsImportedSemanticContext(ReadOnlyList.wrap(declarations),ReadOnlyList.wrap(callables),context.importedGlobals(),context.importedReservedMetadata())); + } return contexts; } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsModuleAssemblyService.java b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsModuleAssemblyService.java index f0bf538d..a2cdfbc5 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsModuleAssemblyService.java +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsModuleAssemblyService.java @@ -72,6 +72,7 @@ final class PbsModuleAssemblyService { for (final var fileId : fileIds) { final var sourceHandle = ctx.fileTable.get(fileId); + if(sourceHandle.getRelativePath().startsWith("@generated"))continue; sourceHandle.readUtf8().ifPresentOrElse( utf8Content -> consumeSourceFile( projectDescriptor, @@ -91,6 +92,9 @@ final class PbsModuleAssemblyService { } } + loadAnimationModules(ctx, writableFileTable, projectIdByName, modulesByCoordinates, + parsedSourceFiles, moduleIdByFile, moduleTable, failedModuleIds, diagnostics); + loadReservedStdlibModules( modulesByCoordinates, parsedSourceFiles, @@ -199,6 +203,37 @@ final class PbsModuleAssemblyService { } } + private void loadAnimationModules(FrontendPhaseContext ctx, FileTable files, + Map owners, Map modules, + ArrayList parsed, Map moduleByFile, ModuleTable table, + Set failed, DiagnosticSink diagnostics) { + for(var entry:modules.entrySet()) { + var path=entry.getKey().pathSegments(); + if(path.size()>=2&&path.get(0).equals("generated")&&path.get(1).equals("animations")) { + var span=entry.getValue().sources.isEmpty()?Span.none():entry.getValue().sources.getFirst().ast().span(); + p.studio.compiler.source.diagnostics.Diagnostics.error(diagnostics,"E_LINK_GENERATED_COLLISION", + "generated/animations is reserved for read-only animation projection",span); + failed.add(moduleId(table,entry.getKey())); + } + } + for(var source:ctx.feSurfaceContext().animations()) { + var owner=owners.get(source.projectName());if(owner==null)continue; + var generated=PbsAnimationProjection.generate(source); + var coordinates=new PbsModuleVisibilityValidator.ModuleCoordinates(source.projectName(),ReadOnlyList.from("generated","animations",generated.moduleName())); + if(modules.containsKey(coordinates))continue; + var unit=new MutableModuleUnit();var module=moduleId(table,coordinates); + byte[] utf8=generated.source().getBytes(StandardCharsets.UTF_8); + var file=files.register(new SourceHandle(owner,Path.of("@generated/animations").resolve(generated.moduleName()).resolve("main.pbs"),generated.path(),utf8.length,0,ignored->()->utf8)); + var ast=parseSourceFile(file,generated.source(),diagnostics,SourceKind.PROJECT); + unit.sources.add(new PbsModuleVisibilityValidator.SourceFile(file,ast));moduleByFile.put(file,module); + parsed.add(new PbsParsedSourceFile(file,ast,module,SourceKind.PROJECT)); + byte[] barrel=generated.barrel().getBytes(StandardCharsets.UTF_8); + var barrelId=files.register(new SourceHandle(owner,Path.of("@generated/animations").resolve(generated.moduleName()).resolve("mod.barrel"),generated.path().resolveSibling("mod.barrel"),barrel.length,0,ignored->()->barrel)); + unit.barrels.add(new PbsModuleVisibilityValidator.BarrelFile(barrelId,parseBarrelFile(barrelId,generated.barrel(),diagnostics))); + moduleByFile.put(barrelId,module);modules.put(coordinates,unit); + } + } + private void loadReservedStdlibModules( final Map modulesByCoordinates, final ArrayList parsedSourceFiles, diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/main.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/main.pbs new file mode 100644 index 00000000..f62bc99a --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/main.pbs @@ -0,0 +1,199 @@ +import { SpriteView } from @core:sprite; + +declare enum PlaybackMode(Once = 0, Loop = 1); +declare enum PlaybackState(Stopped = 0, Playing = 1, Paused = 2, Finished = 3); +declare error AnimationError { + invalid_bank; invalid_name; duplicate_clip; clip_already_open; no_open_clip; + empty_clip; unfinished_clip; empty_animator; initial_clip_missing; unknown_clip; + invalid_glyph; invalid_duration; invalid_ticks; index_out_of_range; + limit_exceeded; overflow; +} + +// Module-private nodes never appear in the public barrel or API. Published frame +// rings are immutable. Direct links avoid array/optional wrappers while advancing. +declare struct _AnimationFrame(pub glyph: int, pub duration: long, pub end: long, pub mut next: _AnimationFrame) { + ctor make(glyph: int, duration: long, end: long) { + this.glyph = glyph; this.duration = duration; this.end = end; this.next = this; + } +} +declare struct _AnimationClip(pub name: str, pub mode: PlaybackMode, + pub mut head: _AnimationFrame, pub mut tail: _AnimationFrame, + pub mut count: long, pub mut total: long, pub mut next: _AnimationClip) { + ctor make(name: str, mode: PlaybackMode) { + let empty = new _AnimationFrame.make(0, 0, 0); + this.name = name; this.mode = mode; this.head = empty; this.tail = empty; + this.count = 0; this.total = 0; this.next = this; + } +} + +[StdlibFactoryOnly] +declare struct Animator(bank: int, first: _AnimationClip, selected: _AnimationClip, + cursor: _AnimationFrame, phase: long, playback: PlaybackState, count: long) { + fn sprite() -> (bank_id: int, glyph_id: int) { return (bank_id: this.bank, glyph_id: this.cursor.glyph); } + fn state() -> PlaybackState { return this.playback; } + fn active_clip() -> str { return this.selected.name; } + fn clip_count() -> long { return this.count; } + fn frame_count(name: str) -> result long { + if name == "" { return err(AnimationError.invalid_name); } + let clip = this.first; let index: long = 0; + while index < this.count { + if clip.name == name { return ok(clip.count); } + clip = clip.next; index = index + 1; + } + return err(AnimationError.unknown_clip); + } + fn frame_at(name: str, index: long) -> result (glyph_id: int, duration_ticks: long) { + if name == "" { return err(AnimationError.invalid_name); } + let clip = this.first; let ordinal: long = 0; + while ordinal < this.count { + if clip.name == name { + if index < (0 as long) || index >= clip.count { return err(AnimationError.index_out_of_range); } + let frame = clip.head; let offset: long = 0; + while offset < index { frame = frame.next; offset = offset + 1; } + return ok((glyph_id: frame.glyph, duration_ticks: frame.duration)); + } + clip = clip.next; ordinal = ordinal + 1; + } + return err(AnimationError.unknown_clip); + } + fn select(name: str) -> result { + if name == "" { return err(AnimationError.invalid_name); } + let clip = this.first; let index: long = 0; + while index < this.count { + if clip.name == name { + this.selected = clip; this.cursor = clip.head; this.phase = 0; + this.playback = PlaybackState.Stopped; return ok(()); + } + clip = clip.next; index = index + 1; + } + return err(AnimationError.unknown_clip); + } + fn play(name: str) -> result { this.select(name)!; this.playback = PlaybackState.Playing; return ok(()); } + fn pause() { if this.playback == PlaybackState.Playing { this.playback = PlaybackState.Paused; } } + fn resume() { if this.playback == PlaybackState.Paused { this.playback = PlaybackState.Playing; } } + fn stop() { this.cursor = this.selected.head; this.phase = 0; this.playback = PlaybackState.Stopped; } + fn restart() { this.cursor = this.selected.head; this.phase = 0; this.playback = PlaybackState.Playing; } + fn advance(ticks: int) -> result { + if ticks < 0 { return err(AnimationError.invalid_ticks); } + if ticks == 0 || this.playback != PlaybackState.Playing { return ok(()); } + let delta: long = ticks as long; let maximum: long = 9223372036854775807; + if this.phase > maximum - delta { return err(AnimationError.overflow); } + let nextPhase: long = this.phase + delta; + let nextState = this.playback; let nextFrame = this.selected.head; + if this.selected.mode == PlaybackMode.Loop { nextPhase = nextPhase % this.selected.total; } + else { + if nextPhase >= this.selected.total { + nextPhase = this.selected.total; nextState = PlaybackState.Finished; + nextFrame = this.selected.tail; + } + } + if nextState != PlaybackState.Finished { + while nextPhase >= nextFrame.end { nextFrame = nextFrame.next; } + } + this.phase = nextPhase; this.cursor = nextFrame; this.playback = nextState; + return ok(()); + } +} +implements SpriteView for Animator using value { + fn sprite() -> (bank_id: int, glyph_id: int) { return value.sprite(); } +} + +[StdlibFactoryOnly] +declare struct AnimatorBuilder(bank: int, initial: str, first: _AnimationClip, + last: _AnimationClip, draft: _AnimationClip, count: long, open: bool) { + fn begin_clip(name: str, mode: PlaybackMode) -> result { + if this.open { return err(AnimationError.clip_already_open); } + if name == "" { return err(AnimationError.invalid_name); } + let clip = this.first; let index: long = 0; + while index < this.count { + if clip.name == name { return err(AnimationError.duplicate_clip); } + clip = clip.next; index = index + 1; + } + let maximum: long = 4294967295; + if this.count == maximum { return err(AnimationError.limit_exceeded); } + let candidate = new _AnimationClip.make(name, mode); + this.draft = candidate; this.open = true; return ok(()); + } + fn add_frame(glyph_id: int, duration_ticks: long) -> result { + if !this.open { return err(AnimationError.no_open_clip); } + if glyph_id < 0 || glyph_id > 65535 { return err(AnimationError.invalid_glyph); } + if duration_ticks <= (0 as long) { return err(AnimationError.invalid_duration); } + let countMaximum: long = 4294967295; let durationMaximum: long = 9223372036854775807; + if this.draft.count == countMaximum { return err(AnimationError.limit_exceeded); } + if this.draft.total > durationMaximum - duration_ticks { return err(AnimationError.overflow); } + let total: long = this.draft.total + duration_ticks; + let candidate = new _AnimationFrame.make(glyph_id, duration_ticks, total); + if this.draft.count == (0 as long) { this.draft.head = candidate; } + else { this.draft.tail.next = candidate; } + candidate.next = this.draft.head; + this.draft.tail = candidate; this.draft.count = this.draft.count + 1; this.draft.total = total; + return ok(()); + } + fn end_clip() -> result { + if !this.open { return err(AnimationError.no_open_clip); } + if this.draft.count == (0 as long) { return err(AnimationError.empty_clip); } + if this.count == (0 as long) { this.first = this.draft; } + else { this.last.next = this.draft; } + this.draft.next = this.first; this.last = this.draft; + this.count = this.count + 1; this.open = false; return ok(()); + } + fn discard_clip() -> result { + if !this.open { return err(AnimationError.no_open_clip); } + this.open = false; return ok(()); + } + fn remove_clip(name: str) -> result { + if this.open { return err(AnimationError.unfinished_clip); } + if name == "" { return err(AnimationError.invalid_name); } + let previous = this.last; let clip = this.first; let index: long = 0; + while index < this.count { + if clip.name == name { + if this.count > (1 as long) { + previous.next = clip.next; + if index == (0 as long) { this.first = clip.next; } + if index == this.count - (1 as long) { this.last = previous; } + } + this.count = this.count - 1; return ok(()); + } + previous = clip; clip = clip.next; index = index + 1; + } + return err(AnimationError.unknown_clip); + } + fn build() -> result Animator { + if this.open { return err(AnimationError.unfinished_clip); } + if this.count == (0 as long) { return err(AnimationError.empty_animator); } + let source = this.first; let index: long = 0; let found = false; + while index < this.count { + if source.name == this.initial { found = true; } + source = source.next; index = index + 1; + } + if !found { return err(AnimationError.initial_clip_missing); } + // No domain errors remain. Copy every mutable node before publishing. + let first = new _AnimationClip.make("", PlaybackMode.Once); let last = first; let selected = first; + source = this.first; index = 0; + while index < this.count { + let copy = new _AnimationClip.make(source.name, source.mode); + let frame = source.head; let ordinal: long = 0; + while ordinal < source.count { + let fresh = new _AnimationFrame.make(frame.glyph, frame.duration, frame.end); + if ordinal == (0 as long) { copy.head = fresh; } + else { copy.tail.next = fresh; } + fresh.next = copy.head; copy.tail = fresh; + frame = frame.next; ordinal = ordinal + 1; + } + copy.count = source.count; copy.total = source.total; + if index == (0 as long) { first = copy; } + else { last.next = copy; } + copy.next = first; last = copy; + if source.name == this.initial { selected = copy; } + source = source.next; index = index + 1; + } + return ok(new Animator(this.bank, first, selected, selected.head, 0, PlaybackState.Stopped, this.count)); + } +} + +fn animator_builder(bank_id: int, initial_clip: str) -> result AnimatorBuilder { + if bank_id < 0 || bank_id > 255 { return err(AnimationError.invalid_bank); } + if initial_clip == "" { return err(AnimationError.invalid_name); } + let empty = new _AnimationClip.make("", PlaybackMode.Once); + return ok(new AnimatorBuilder(bank_id, initial_clip, empty, empty, empty, 0, false)); +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/mod.barrel b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/mod.barrel new file mode 100644 index 00000000..bbf24831 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/mod.barrel @@ -0,0 +1,6 @@ +pub struct Animator; +pub struct AnimatorBuilder; +pub enum PlaybackMode; +pub enum PlaybackState; +pub error AnimationError; +pub fn animator_builder(bank_id: int, initial_clip: str) -> result AnimatorBuilder; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/main.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/main.pbs new file mode 100644 index 00000000..1a7a6059 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/main.pbs @@ -0,0 +1,24 @@ +[Doc(markdown = """ +A pure visual query. Bank slots are already loaded by the caller; position and +palette belong to the emission. Querying never advances time or allocates a Sprite. +""")] +declare contract SpriteView { fn sprite() -> (bank_id: int, glyph_id: int); } + +declare error SpriteError { invalid_bank; invalid_glyph; } + +[StdlibFactoryOnly] +declare struct Sprite(bank_id: int, glyph_id: int) { + fn sprite() -> (bank_id: int, glyph_id: int) { + return (bank_id: this.bank_id, glyph_id: this.glyph_id); + } +} + +implements SpriteView for Sprite using value { + fn sprite() -> (bank_id: int, glyph_id: int) { return value.sprite(); } +} + +fn make_sprite(bank_id: int, glyph_id: int) -> result Sprite { + if bank_id < 0 || bank_id > 255 { return err(SpriteError.invalid_bank); } + if glyph_id < 0 || glyph_id > 65535 { return err(SpriteError.invalid_glyph); } + return ok(new Sprite(bank_id, glyph_id)); +} diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/mod.barrel b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/mod.barrel new file mode 100644 index 00000000..54753f32 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/mod.barrel @@ -0,0 +1,4 @@ +pub struct Sprite; +pub contract SpriteView; +pub error SpriteError; +pub fn make_sprite(bank_id: int, glyph_id: int) -> result Sprite; diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/composer/main.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/composer/main.pbs index 5e739556..5eafc6bb 100644 --- a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/composer/main.pbs +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/sdk/composer/main.pbs @@ -19,14 +19,14 @@ declare host LowComposer { """)] [Host(module = "composer", name = "bind_scene", version = 1)] [Capability(name = "composer")] - fn bind_scene(scene_bank_id: int) -> int; + fn bind_scene(scene_bank_id: int) -> long; [Doc(markdown = """ Unbinds the active scene bank. """)] [Host(module = "composer", name = "unbind_scene", version = 1)] [Capability(name = "composer")] - fn unbind_scene() -> int; + fn unbind_scene() -> long; [Doc(markdown = """ Emits a sprite command into the active scene. @@ -53,7 +53,7 @@ declare host LowComposer { flip_x: bool, flip_y: bool, priority: int - ) -> int; + ) -> long; } [Doc(markdown = """ @@ -79,7 +79,7 @@ declare service Composer """)] fn bind_scene(scene_bank_id: int) -> int { - return LowComposer.bind_scene(scene_bank_id); + return LowComposer.bind_scene(scene_bank_id) as int; } [Doc(markdown = """ @@ -87,7 +87,7 @@ declare service Composer """)] fn unbind_scene() -> int { - return LowComposer.unbind_scene(); + return LowComposer.unbind_scene() as int; } [Doc(markdown = """ @@ -115,6 +115,6 @@ declare service Composer priority: int ) -> int { - return LowComposer.emit_sprite(glyph_id, palette_id, x, y, layer, bank_id, flip_x, flip_y, priority); + return LowComposer.emit_sprite(glyph_id, palette_id, x, y, layer, bank_id, flip_x, flip_y, priority) as int; } } diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/ANIMATION.md b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/ANIMATION.md new file mode 100644 index 00000000..0c924bbf --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/ANIMATION.md @@ -0,0 +1,45 @@ +# Sprite and animation + +`@core:sprite` and `@core:animation` are ordinary PBS stdlib modules. Use +`make_sprite` or `animator_builder`; their private constructors are unavailable +to games. `src/animation.pbs` demonstrates a static sprite, Loop and Once clips, +external palette/position and two independent animators built from one builder. + +Call `play` when the action changes and call `advance` to continue it. Repeating +`play` or `select`, including the current name, resets the cursor and phase. +Ticks are explicit game ticks; no timer runs inside Animator. Assignment aliases +the same animator; another `build` creates independent clips and playback. +A Once clip finishes after the last frame's full duration and retains its image. + +For authored definitions, select a registered glyph bank in Studio Assets and +create animators/clips/frames. Save `animations.studio.json` through the editor +or task-authorized `studio_animation_update`. Glyph identity and fingerprints are +validated against the current bank. Drift blocks preview/build until explicit +prepare/apply rebind; review the proposed old/new bindings before applying it. +Palette, position and runtime bank slot are never persisted in this definition. + +For bank UUID `12345678-1234-1234-1234-123456789abc` and animator ID `hero`: + +```pbs +import { create_hero } from @app:generated/animations/b_12345678123412341234123456789abc; +import { AnimationError } from @core:animation; +fn render() -> result { + let value = create_hero(3)!; + value.play("idle")!; + value.advance(2)!; + let image = value.sprite(); + // Supply image.bank_id/image.glyph_id to the existing nine-argument Composer API. + return ok(()); +} +``` + +The virtual module is reproducible and read-only. Its CodeLens opens the original +JSON field in Studio. A changed definition invalidates older source revisions; +navigate again to obtain the current definition. Existing projects without a +sidecar publish no animation factories. Compilation with included definitions +requires the configured Packer layout resolver. + +Result calls preserve a typed status plus the complete payload. Use `!` to +propagate the same declared error, or `handle` for a selected recovery/remapping. +Neither catches VM traps. See PBS specification chapter 27 for errors, bounds, +state transitions, ownership and the zero-allocation playback contract. diff --git a/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/animation.pbs b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/animation.pbs new file mode 100644 index 00000000..b8136fd1 --- /dev/null +++ b/prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/animation.pbs @@ -0,0 +1,25 @@ +import { Sprite, SpriteError, make_sprite } from @core:sprite; +import { Animator, AnimatorBuilder, AnimationError, PlaybackMode, animator_builder } from @core:animation; +import { Composer } from @sdk:composer; + +// Palette, position and bank lifetime belong to the caller. +fn staticSprite(bank: int, palette: int, x: int, y: int) -> result int { + let value = make_sprite(bank, 7)!; + let image = value.sprite(); + return ok(Composer.emit_sprite(image.glyph_id, palette, x, y, 0, image.bank_id, false, false, 0)); +} +fn animationExample() -> result int { + let builder = animator_builder(3, "idle")!; + builder.begin_clip("idle", PlaybackMode.Loop)!; + builder.add_frame(7, 2)!; builder.add_frame(11, 3)!; builder.add_frame(4, 1)!; + builder.end_clip()!; + builder.begin_clip("jump", PlaybackMode.Once)!; + builder.add_frame(11, 2)!; builder.add_frame(4, 3)!; builder.end_clip()!; + let first = builder.build()!; let second = builder.build()!; + first.play("idle")!; first.advance(2)!; + // Independent playback: advancing first leaves second stopped on glyph 7. + if first.sprite().glyph_id != 11 || second.sprite().glyph_id != 7 { let failure=1/0; } + first.play("jump")!; first.advance(5)!; + if first.sprite().glyph_id != 4 { let failure=1/0; } + return ok(42); +} diff --git a/prometeu-compiler/prometeu-build-pipeline/build.gradle.kts b/prometeu-compiler/prometeu-build-pipeline/build.gradle.kts index 313875b3..1a0d98b0 100644 --- a/prometeu-compiler/prometeu-build-pipeline/build.gradle.kts +++ b/prometeu-compiler/prometeu-build-pipeline/build.gradle.kts @@ -3,6 +3,7 @@ plugins { } dependencies { + implementation(project(":prometeu-animation")) api(project(":prometeu-infra")) implementation(project(":prometeu-compiler:prometeu-deps")) implementation(project(":prometeu-compiler:prometeu-compiler-core")) diff --git a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/models/BuilderPipelineContext.java b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/models/BuilderPipelineContext.java index d9b7f5f1..dba11364 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/models/BuilderPipelineContext.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/models/BuilderPipelineContext.java @@ -12,6 +12,7 @@ public class BuilderPipelineContext { public final BuilderPipelineConfig config; public final SourceProviderFactory sourceProviderFactory; + public p.animation.GlyphBankLayoutSource glyphBankLayoutSource; public Path rootProjectPathCanon; public ResolvedWorkspace resolvedWorkspace; diff --git a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/AssetSurfaceContextLoader.java b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/AssetSurfaceContextLoader.java index 0aa2f6e5..6d4ac240 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/AssetSurfaceContextLoader.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/AssetSurfaceContextLoader.java @@ -18,13 +18,20 @@ public final class AssetSurfaceContextLoader { private static final Path REGISTRY_PATH = Path.of("assets", ".prometeu", "index.json"); private final ObjectMapper mapper; + private final p.animation.GlyphBankLayoutSource layouts; public AssetSurfaceContextLoader() { - this(new ObjectMapper()); + this(new ObjectMapper(), null); } AssetSurfaceContextLoader(final ObjectMapper mapper) { - this.mapper = Objects.requireNonNull(mapper, "mapper"); + this(mapper, null); + } + + public AssetSurfaceContextLoader(p.animation.GlyphBankLayoutSource layouts) { this(new ObjectMapper(), layouts); } + + private AssetSurfaceContextLoader(ObjectMapper mapper, p.animation.GlyphBankLayoutSource layouts) { + this.mapper = Objects.requireNonNull(mapper, "mapper"); this.layouts = layouts; } public FESurfaceContext load(final Path projectRoot) { @@ -38,15 +45,29 @@ public final class AssetSurfaceContextLoader { try { final var document = mapper.readValue(registryPath.toFile(), RegistryDocument.class); final var addressables = new ArrayList(); + final var animations = new ArrayList(); if (document.assets != null) { for (final var asset : document.assets) { if (asset == null || !isIncludedInBuild(asset)) { continue; } addressables.add(new Addressable(toAddress(asset.root()), asset.assetId())); + var bankRoot=projectRoot.toAbsolutePath().normalize().resolve("assets").resolve(normalizeRoot(asset.root())); + var definition=bankRoot.resolve(p.animation.AnimationDocument.FILE_NAME); + if (Files.isRegularFile(definition)) { + if(layouts==null)throw new IllegalStateException("E_ANIMATION_LAYOUT_RESOLVER: included animation bank requires GlyphBankLayoutSource"); + String text=Files.readString(definition, java.nio.charset.StandardCharsets.UTF_8); + var animation=new p.animation.AnimationCodec().decode(text); + var uuid=java.util.UUID.fromString(animation.bankAssetUuid()); + var bank=layouts.resolve(projectRoot,uuid); + if(!bank.assetRoot().toRealPath().equals(bankRoot.toRealPath()))throw new IllegalArgumentException("Animation UUID does not identify its containing registered bank"); + new p.animation.AnimationValidator().requireValid(animation,bank); + String projectName=mapper.readTree(projectRoot.resolve("prometeu.json").toFile()).path("name").asText(); + animations.add(new p.animation.AnimationSource(projectName,projectRoot.toAbsolutePath().normalize(),definition,p.animation.AnimationRevision.of(text),animation,bank)); + } } } - return new FESurfaceContext(ReadOnlyList.wrap(addressables)); + return new FESurfaceContext(ReadOnlyList.wrap(addressables),ReadOnlyList.wrap(animations)); } catch (IOException exception) { throw new IllegalStateException("Unable to load asset surface registry: " + registryPath, exception); } diff --git a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/stages/FrontendPhasePipelineStage.java b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/stages/FrontendPhasePipelineStage.java index 68c7f41e..cd4f6d29 100644 --- a/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/stages/FrontendPhasePipelineStage.java +++ b/prometeu-compiler/prometeu-build-pipeline/src/main/java/p/studio/compiler/workspaces/stages/FrontendPhasePipelineStage.java @@ -12,7 +12,6 @@ import p.studio.utilities.logs.LogAggregator; @Slf4j public class FrontendPhasePipelineStage implements PipelineStage { - private final AssetSurfaceContextLoader assetSurfaceContextLoader = new AssetSurfaceContextLoader(); @Override public BuildingIssueSink run(final BuilderPipelineContext ctx, final LogAggregator logs) { @@ -20,6 +19,15 @@ public class FrontendPhasePipelineStage implements PipelineStage { final var provider = FrontendRegistryService.require(frontedSpec.getLanguageId()); final var projectTable = ctx.resolvedWorkspace.graph().projectTable(); final var fileTable = ctx.fileTable; + final var issues = BuildingIssueSink.empty(); + final p.studio.compiler.messages.FESurfaceContext surface; + try { + surface = new AssetSurfaceContextLoader(ctx.glyphBankLayoutSource).load(ctx.resolvedWorkspace.mainProject().getRootPath()); + } catch (IllegalArgumentException | IllegalStateException failure) { + issues.report(builder -> builder.error(true).phase("frontend").code("E_ANIMATION_SURFACE") + .message(failure.getMessage())); + return issues; + } final var frontendPhaseContext = new FrontendPhaseContext( projectTable, fileTable, @@ -27,9 +35,8 @@ public class FrontendPhasePipelineStage implements PipelineStage { ctx.resolvedWorkspace.stdlib(), ctx.resolvedWorkspace.target(), p.studio.compiler.messages.HostAdmissionContext.permissiveDefault(), - assetSurfaceContextLoader.load(ctx.resolvedWorkspace.mainProject().getRootPath())); + surface); final var diagnostics = DiagnosticSink.empty(); - final var issues = BuildingIssueSink.empty(); ctx.irBackend = provider.compiler().compile(frontendPhaseContext, diagnostics, logs, issues); logs.using(log).debug("Frontend phase completed successfully!"); adaptDiagnostics(diagnostics, issues); diff --git a/prometeu-compiler/prometeu-frontend-api/build.gradle.kts b/prometeu-compiler/prometeu-frontend-api/build.gradle.kts index 06c18c58..2a6e93d0 100644 --- a/prometeu-compiler/prometeu-frontend-api/build.gradle.kts +++ b/prometeu-compiler/prometeu-frontend-api/build.gradle.kts @@ -3,6 +3,7 @@ plugins { } dependencies { + api(project(":prometeu-animation")) api(project(":prometeu-infra")) api(project(":prometeu-compiler:prometeu-compiler-core")) diff --git a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/messages/FESurfaceContext.java b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/messages/FESurfaceContext.java index 685b932a..4a50437e 100644 --- a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/messages/FESurfaceContext.java +++ b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/messages/FESurfaceContext.java @@ -6,10 +6,13 @@ import java.util.ArrayList; import java.util.LinkedHashMap; public record FESurfaceContext( - ReadOnlyList assets) { + ReadOnlyList assets, ReadOnlyList animations) { + + public FESurfaceContext(ReadOnlyList assets) { this(assets, ReadOnlyList.empty()); } public FESurfaceContext { assets = normalizeAssets(assets); + animations = animations == null ? ReadOnlyList.empty() : animations; } public static FESurfaceContext empty() { diff --git a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendSourceDocument.java b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendSourceDocument.java index f8446815..f763fd46 100644 --- a/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendSourceDocument.java +++ b/prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/services/FrontendSourceDocument.java @@ -10,7 +10,13 @@ import java.util.Objects; /** A compiler-known source and the semantic context for exactly that content. */ public record FrontendSourceDocument( Path path, String text, String origin, String name, String languageId, - boolean readOnly, FrontendEditorialContext context) { + boolean readOnly, FrontendEditorialContext context, java.util.List origins, String generationRevision) { + public record OriginSpan(int startOffset, int endOffset, Path definitionPath, String jsonPointer, String assetUuid) { + public OriginSpan(int startOffset,int endOffset,Path path,String pointer){this(startOffset,endOffset,path,pointer,null);} + } + public FrontendSourceDocument(Path path,String text,String origin,String name,String languageId,boolean readOnly,FrontendEditorialContext context) { + this(path,text,origin,name,languageId,readOnly,context,java.util.List.of(),""); + } public FrontendSourceDocument { path = Objects.requireNonNull(path).toAbsolutePath().normalize(); Objects.requireNonNull(text); @@ -18,12 +24,13 @@ public record FrontendSourceDocument( Objects.requireNonNull(name); Objects.requireNonNull(languageId); Objects.requireNonNull(context); + origins=java.util.List.copyOf(origins); generationRevision=Objects.requireNonNull(generationRevision); } public String revision() { try { return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256") - .digest(text.getBytes(StandardCharsets.UTF_8))); + .digest((generationRevision.isEmpty()?text:text+"\n"+generationRevision).getBytes(StandardCharsets.UTF_8))); } catch (NoSuchAlgorithmException impossible) { throw new IllegalStateException(impossible); } diff --git a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java index 4e629f9a..799ec67c 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/LspServerLifecycleImpl.java @@ -14,8 +14,11 @@ public final class LspServerLifecycleImpl implements LspServerLifecycle { private final CompilerLanguageServiceBridge compilerBridge; private final ConcurrentMap activeServers; - public LspServerLifecycleImpl() { - this.compilerBridge = new CompilerLanguageServiceBridge(); + public LspServerLifecycleImpl() { this(null); } + + public LspServerLifecycleImpl(p.animation.GlyphBankLayoutSource layouts) { this(layouts,null); } + public LspServerLifecycleImpl(p.animation.GlyphBankLayoutSource layouts,p.animation.AnimationOriginNavigation navigation) { + this.compilerBridge = new CompilerLanguageServiceBridge(layouts,navigation); this.serverHostFactory = new TcpLspServerHostFactory(); this.activeServers = new ConcurrentHashMap<>(); } diff --git a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java index 682dda12..3d5a0e3d 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/CompilerLanguageServiceBridge.java @@ -115,14 +115,32 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg } return new BaselineDefinition(List.copyOf(mapped)); } - private final AssetSurfaceContextLoader assetSurfaceContextLoader = new AssetSurfaceContextLoader(); + private final AssetSurfaceContextLoader assetSurfaceContextLoader; + private final p.animation.GlyphBankLayoutSource layouts; + private p.animation.AnimationOriginNavigation animationNavigation; private final Function frontendProviderResolver; public CompilerLanguageServiceBridge() { this(FrontendRegistryService::require); } - CompilerLanguageServiceBridge(final Function frontendProviderResolver) { + public CompilerLanguageServiceBridge(p.animation.GlyphBankLayoutSource layouts) { this(FrontendRegistryService::require, layouts); } + public CompilerLanguageServiceBridge(p.animation.GlyphBankLayoutSource layouts,p.animation.AnimationOriginNavigation navigation) { + this(FrontendRegistryService::require,layouts);this.animationNavigation=navigation; + } + public void openAnimationOrigin(LspProjectContext context,String uri,int offset,ExternalSourceRegistry registry,String consumer) { + if(animationNavigation==null||offset<0)throw new IllegalArgumentException("Animation origin navigation is unavailable"); + registry.revalidate(consumer,uri,path->currentSource(context,path)); + var source=registry.source(consumer,uri); + if(!source.origin().equals("generated"))throw new IllegalArgumentException("Source is not generated animation"); + var origin=source.origins().stream().filter(o->o.assetUuid()!=null&&offset>=o.startOffset()&&offsetnew IllegalArgumentException("No authored animation field at this position")); + animationNavigation.open(context.projectRoot(),java.util.UUID.fromString(origin.assetUuid()),origin.jsonPointer()); + } + + CompilerLanguageServiceBridge(final Function frontendProviderResolver) { this(frontendProviderResolver,null); } + + private CompilerLanguageServiceBridge(Function frontendProviderResolver,p.animation.GlyphBankLayoutSource layouts) { + this.layouts=layouts;this.assetSurfaceContextLoader=new AssetSurfaceContextLoader(layouts); this.frontendProviderResolver = Objects.requireNonNull(frontendProviderResolver, "frontendProviderResolver"); } @@ -367,6 +385,7 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg context.projectRoot().toString(), "core-v1", SourceProviderFactory.overlayUtf8(Map.of()))); + pipelineContext.glyphBankLayoutSource=layouts; BuilderPipelineService.INSTANCE.analyze(pipelineContext, LogAggregator.empty()); final FrontendPhaseContext frontendPhaseContext = new FrontendPhaseContext( pipelineContext.resolvedWorkspace.graph().projectTable(), @@ -888,6 +907,7 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg context.projectRoot().toString(), "core-v1", SourceProviderFactory.overlayUtf8(overlays))); + pipelineContext.glyphBankLayoutSource=layouts; return BuilderPipelineService.INSTANCE.analyze(pipelineContext, LogAggregator.empty()); } @@ -906,6 +926,7 @@ public final class CompilerLanguageServiceBridge implements LanguageServiceBridg context.projectRoot().toString(), "core-v1", SourceProviderFactory.overlayUtf8(text == null ? Map.of() : Map.of(documentPath, text)))); + pipelineContext.glyphBankLayoutSource=layouts; BuilderPipelineService.INSTANCE.analyze(pipelineContext, LogAggregator.empty()); final FileId fileId = findFileId(pipelineContext, documentPath); if (fileId == null) { diff --git a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/ExternalSourceRegistry.java b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/ExternalSourceRegistry.java index 0f2d0be5..252b6375 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/ExternalSourceRegistry.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/compiler/ExternalSourceRegistry.java @@ -8,8 +8,15 @@ import java.util.function.Function; /** Owned by one project host, never by the shared compiler bridge. */ public final class ExternalSourceRegistry implements AutoCloseable { + /** Wire metadata must contain URI/text values, never filesystem implementation objects. */ + public record Origin(int startOffset, int endOffset, String definitionPath, String jsonPointer, String assetUuid) { + private static Origin from(FrontendSourceDocument.OriginSpan span) { + return new Origin(span.startOffset(), span.endOffset(), span.definitionPath().toUri().toString(), + span.jsonPointer(), span.assetUuid()); + } + } public record Descriptor(String uri, String revision, String origin, String name, - String languageId, boolean readOnly) {} + String languageId, boolean readOnly, List origins) {} public record Content(Descriptor descriptor, String text) {} private static final class Entry { final Descriptor descriptor; @@ -55,7 +62,7 @@ public final class ExternalSourceRegistry implements AutoCloseable { // must not change the opaque identity by normalizing escaped slashes. final String uri = "prometeu-source://" + session + "/" + UUID.randomUUID() + "/" + source.revision() + "/" + source.name().replaceAll("[^A-Za-z0-9._-]", "-"); - entry = new Entry(new Descriptor(uri, source.revision(), source.origin(), source.name(), source.languageId(), true), source); + entry = new Entry(new Descriptor(uri, source.revision(), source.origin(), source.name(), source.languageId(), true, source.origins().stream().map(Origin::from).toList()), source); entries.put(uri, entry); } consumer.grants.add(entry.descriptor.uri()); @@ -68,7 +75,7 @@ public final class ExternalSourceRegistry implements AutoCloseable { return left == right || left != null && left.path().equals(right.path()) && left.context().projectSurface() != null && left.context().projectSurface() == right.context().projectSurface() - && left.text().equals(right.text()); + && left.text().equals(right.text()) && left.revision().equals(right.revision()); } public synchronized FrontendSourceDocument source(String consumerId, String uri) { diff --git a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/ExternalSourceLanguageServer.java b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/ExternalSourceLanguageServer.java index 6252edcf..acf2e521 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/ExternalSourceLanguageServer.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/ExternalSourceLanguageServer.java @@ -7,6 +7,8 @@ import java.util.concurrent.CompletableFuture; public interface ExternalSourceLanguageServer extends LanguageServer { record Request(String consumerId, String uri) {} + record AnimationOriginRequest(String consumerId,String uri,int offset) {} + @JsonRequest("prometeu/openAnimationOrigin") CompletableFuture openAnimationOrigin(AnimationOriginRequest request); @JsonRequest("prometeu/readExternalSource") CompletableFuture readExternalSource(Request request); @JsonRequest("prometeu/retainExternalSource") CompletableFuture retainExternalSource(Request request); @JsonRequest("prometeu/releaseExternalSource") CompletableFuture releaseExternalSource(Request request); diff --git a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/PrometeuLanguageServer.java b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/PrometeuLanguageServer.java index 9fec5632..7c3fa05e 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/PrometeuLanguageServer.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/main/java/p/studio/lsp/services/protocol/PrometeuLanguageServer.java @@ -61,6 +61,11 @@ public final class PrometeuLanguageServer implements ExternalSourceLanguageServe failure.getMessage(), null))); } } + @Override public CompletableFuture openAnimationOrigin(AnimationOriginRequest request) { + return external(new Request(request.consumerId(),request.uri()),()->{ + ((CompilerLanguageServiceBridge)languageServiceBridge).openAnimationOrigin(project,request.uri(),request.offset(),externalSources,consumerId);return null; + }); + } @Override public CompletableFuture readExternalSource(Request request) { return external(request, () -> externalSources.read(consumerId, request.uri())); } diff --git a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/ExternalSourceRegistryTest.java b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/ExternalSourceRegistryTest.java index 72e21b47..07231ad3 100644 --- a/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/ExternalSourceRegistryTest.java +++ b/prometeu-lsp/prometeu-lsp-v1/src/test/java/p/studio/lsp/services/compiler/ExternalSourceRegistryTest.java @@ -65,6 +65,18 @@ class ExternalSourceRegistryTest { assertThrows(IllegalStateException.class, () -> registry.read(next, uri)); } + @Test void generatedOriginMetadataSerializesWithoutFilesystemInternals() { + var base=source("fn generated() {}"); + var generated=new FrontendSourceDocument(base.path(),base.text(),"generated",base.name(),"pbs",true,base.context(), + java.util.List.of(new FrontendSourceDocument.OriginSpan(0,10,Path.of("/project/assets/bank/animations.studio.json"),"/animators/0/id","12345678-1234-1234-1234-123456789abc")),"generator-revision"); + try(var registry=new ExternalSourceRegistry()){ + String consumer=registry.connect(null,false);String uri=registry.register(consumer,generated); + String json=new com.google.gson.Gson().toJson(registry.read(consumer,uri)); + assertTrue(json.contains("file:///project/assets/bank/animations.studio.json")); + assertTrue(json.contains("/animators/0/id")); + } + } + @Test void cancelledOrUnopenedNavigationDoesNotRetainASnapshot() { try (var registry = new ExternalSourceRegistry()) { final String consumer = registry.connect(null, true); diff --git a/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/PackerWorkspaceService.java b/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/PackerWorkspaceService.java index 00148d44..d364e64b 100644 --- a/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/PackerWorkspaceService.java +++ b/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/PackerWorkspaceService.java @@ -3,6 +3,14 @@ package p.packer; import p.packer.messages.*; public interface PackerWorkspaceService { + default p.packer.dtos.PackerGlyphBankLayoutDTO getGlyphBankLayout(GetGlyphBankLayoutRequest request) { + throw new UnsupportedOperationException("Glyph bank layout resolver is not configured"); + } + + default T withGlyphBankLayout(GetGlyphBankLayoutRequest request, java.util.function.Function work) { + throw new UnsupportedOperationException("Project-exclusive layout access is not configured"); + } + InitWorkspaceResult initWorkspace(InitWorkspaceRequest request); ListAssetsResult listAssets(ListAssetsRequest request); diff --git a/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/dtos/PackerGlyphBankLayoutDTO.java b/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/dtos/PackerGlyphBankLayoutDTO.java new file mode 100644 index 00000000..d8c7b07b --- /dev/null +++ b/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/dtos/PackerGlyphBankLayoutDTO.java @@ -0,0 +1,13 @@ +package p.packer.dtos; +import java.nio.file.Path; +import java.util.*; +/** Immutable effective composition and pixels from the same packing helpers. */ +public record PackerGlyphBankLayoutDTO(UUID assetUuid, String revision, Path assetRoot, + List glyphs, byte[] rgbaPalettes) { + public PackerGlyphBankLayoutDTO { glyphs=List.copyOf(glyphs);rgbaPalettes=rgbaPalettes.clone(); } + @Override public byte[] rgbaPalettes(){return rgbaPalettes.clone();} + public record Glyph(String artifactId,int glyphId,String fingerprint,Path imagePath,int width,int height,byte[] indices) { + public Glyph { indices=indices.clone(); } + @Override public byte[] indices(){return indices.clone();} + } +} diff --git a/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/messages/GetGlyphBankLayoutRequest.java b/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/messages/GetGlyphBankLayoutRequest.java new file mode 100644 index 00000000..0418ec41 --- /dev/null +++ b/prometeu-packer/prometeu-packer-api/src/main/java/p/packer/messages/GetGlyphBankLayoutRequest.java @@ -0,0 +1,6 @@ +package p.packer.messages; +import java.util.UUID; +import java.util.Objects; +public record GetGlyphBankLayoutRequest(PackerProjectContext project, UUID assetUuid) { + public GetGlyphBankLayoutRequest { Objects.requireNonNull(project); Objects.requireNonNull(assetUuid); } +} diff --git a/prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerAbstractBankWalker.java b/prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerAbstractBankWalker.java index c4cd373f..177f9994 100644 --- a/prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerAbstractBankWalker.java +++ b/prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/repositories/PackerAbstractBankWalker.java @@ -47,7 +47,8 @@ public abstract class PackerAbstractBankWalker { private List retrieveValidPaths(final Path assetRoot) throws IOException { try (final var paths = Files.list(assetRoot) .filter(Files::isRegularFile) - .filter(path -> !isAssetManifest(path))) { + .filter(path -> !isAssetManifest(path)) + .filter(path -> !path.getFileName().toString().equals("animations.studio.json"))) { return paths.toList(); } } diff --git a/prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java b/prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java index f1c5fe4b..dc9e89f5 100644 --- a/prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java +++ b/prometeu-packer/prometeu-packer-v1/src/main/java/p/packer/services/FileSystemPackerWorkspaceService.java @@ -150,6 +150,56 @@ public final class FileSystemPackerWorkspaceService implements PackerWorkspaceSe PackerReadMessageMapper.toDiagnosticDTOs(diagnostics)); } + @Override + public p.packer.dtos.PackerGlyphBankLayoutDTO getGlyphBankLayout(GetGlyphBankLayoutRequest request) { + return withGlyphBankLayout(request, java.util.function.Function.identity()); + } + + @Override + public T withGlyphBankLayout(GetGlyphBankLayoutRequest request, java.util.function.Function work) { + Objects.requireNonNull(request); Objects.requireNonNull(work); + return writeCoordinator.execute(request.project(), () -> work.apply(readGlyphBankLayout(request))); + } + + private p.packer.dtos.PackerGlyphBankLayoutDTO readGlyphBankLayout(GetGlyphBankLayoutRequest request) { + // Refresh observes external composition/content changes without backfilling identities. + var snapshot = runtimeRegistry.refresh(request.project()).snapshot(); + var matching = snapshot.assets().stream().filter(a -> a.registryEntry().isPresent() + && request.assetUuid().toString().equals(a.registryEntry().get().assetUuid())).toList(); + if (matching.size()!=1) throw new IllegalArgumentException("Bank UUID must identify one registered asset"); + var asset=matching.getFirst(); var parsed=asset.parsedDeclaration(); + if (!parsed.valid() || parsed.declaration().assetFamily()!=AssetFamilyCatalog.GLYPH_BANK) + throw new IllegalArgumentException("Registered asset is not a valid glyph bank: "+parsed.diagnostics()); + var declaration=parsed.declaration(); + if (!request.assetUuid().toString().equals(declaration.assetUuid())) throw new IllegalArgumentException("Bank UUID mismatch"); + if (asset.walkDiagnostics().stream().anyMatch(PackerDiagnostic::blocking)) throw new IllegalArgumentException("Bank composition is invalid"); + var materialDiagnostics=glyphMaterialSupport.validate(asset); + if(materialDiagnostics.stream().anyMatch(PackerDiagnostic::blocking))throw new IllegalArgumentException("Bank material bindings are invalid: "+materialDiagnostics); + var files=new HashMap(); + asset.walkProjection().buildCandidateFiles().forEach(f->files.put(f.relativePath(),f)); + var ids=new HashSet();var indices=new HashSet(); + var glyphs=new ArrayList(); + var revision=new StringBuilder(request.assetUuid().toString()); + var material=declaredPaletteIndexByRgba(declaration); + for(var artifact:declaration.artifacts().stream().sorted(Comparator.comparingInt(PackerAssetArtifactSelection::index)).toList()) { + var file=files.get(artifact.file()); + if(artifact.artifactId()==null||!ids.add(artifact.artifactId())||!indices.add(artifact.index()) + ||file==null||file.fingerprint()==null||file.diagnostics().stream().anyMatch(PackerDiagnostic::blocking)) + throw new IllegalArgumentException("Missing, removed or duplicate glyph identity"); + if(!(file.metadata().get("tile") instanceof PackerTileIndexedV1 tile))throw new IllegalArgumentException("Missing glyph pixels"); + byte[] pixels=remapTilePaletteIndices(tile,file.metadata().get("palette"),artifact.file(),material); + glyphs.add(new p.packer.dtos.PackerGlyphBankLayoutDTO.Glyph(artifact.artifactId(),artifact.index(),file.fingerprint(), + asset.assetRoot().resolve(artifact.file()),tile.width(),tile.height(),pixels)); + revision.append('\n').append(artifact.artifactId()).append(':').append(artifact.index()).append(':').append(file.fingerprint()); + } + byte[] palettes=emitGlyphBankPalettes(declaration,runtimeGlyphPaletteCount(declaration)); + revision.append('\n').append(HexFormat.of().formatHex(palettes)); + final String hash; + try { hash=HexFormat.of().formatHex(java.security.MessageDigest.getInstance("SHA-256").digest(revision.toString().getBytes(java.nio.charset.StandardCharsets.UTF_8))); } + catch(java.security.NoSuchAlgorithmException impossible){throw new AssertionError(impossible);} + return new p.packer.dtos.PackerGlyphBankLayoutDTO(request.assetUuid(),hash,asset.assetRoot(),glyphs,palettes); + } + @Override public GetAssetDetailsResult getAssetDetails(GetAssetDetailsRequest request) { final GetAssetDetailsRequest safeRequest = Objects.requireNonNull(request, "request"); diff --git a/prometeu-studio-api/build.gradle.kts b/prometeu-studio-api/build.gradle.kts index a6775d6e..8a5dd685 100644 --- a/prometeu-studio-api/build.gradle.kts +++ b/prometeu-studio-api/build.gradle.kts @@ -1,3 +1,5 @@ plugins { id("gradle.java-library-conventions") } + +dependencies { api(project(":prometeu-animation")) } diff --git a/prometeu-studio-api/src/main/java/p/studio/api/assets/AssetSummary.java b/prometeu-studio-api/src/main/java/p/studio/api/assets/AssetSummary.java index 841cd251..19eb4765 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/assets/AssetSummary.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/assets/AssetSummary.java @@ -12,8 +12,11 @@ public record AssetSummary( AssetFamily family, Path root, boolean preload, - boolean hasDiagnostics) { + boolean hasDiagnostics, String assetUuid) { + public AssetSummary(AssetReference reference,String name,AssetRegistrationState registrationState,AssetBuildParticipation buildParticipation,Integer assetId,AssetFamily family,Path root,boolean preload,boolean hasDiagnostics) { + this(reference,name,registrationState,buildParticipation,assetId,family,root,preload,hasDiagnostics,null); + } public AssetSummary { Objects.requireNonNull(reference, "reference"); name = Objects.requireNonNull(name, "name").trim(); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationService.java b/prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationService.java new file mode 100644 index 00000000..2c1b7488 --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationService.java @@ -0,0 +1,26 @@ +package p.studio.api.assets.animation; + +import p.animation.*; +import p.studio.api.project.ProjectReference; +import p.studio.api.automation.CanonicalCapture; +import java.util.*; + +public interface AnimationService { + enum Operation { LIST, GET, VALIDATE, PREVIEW, SAVE, DELETE, PREPARE_REBIND, APPLY_REBIND } + record Request(Operation operation,ProjectReference project,UUID assetUuid,String animatorId,String clipName, + Long elapsedTicks,Integer paletteId,String expectedRevision,AnimationDocument document,String proposalHash,String expectedBankRevision) { + public Request { Objects.requireNonNull(operation);Objects.requireNonNull(project); } + public static Request get(ProjectReference project,UUID bank){return new Request(Operation.GET,project,bank,null,null,null,null,null,null,null,null);} + public static Request save(ProjectReference project,UUID bank,String revision,AnimationDocument document){return new Request(Operation.SAVE,project,bank,null,null,null,null,revision,document,null,null);} + } + record View(UUID assetUuid,String revision,String json,AnimationDocument document,List availableBindings, + String bankRevision,List diagnostics) { + public View { availableBindings=List.copyOf(availableBindings);diagnostics=List.copyOf(diagnostics); } + } + record Preview(UUID assetUuid,String documentRevision,AnimationTimeline.Observation observation,long elapsedTicks,int paletteId,CanonicalCapture image) {} + record Response(View view,List definitions,Preview preview,AnimationRebind.Proposal proposal,List diagnostics) { + public Response { definitions=List.copyOf(definitions);diagnostics=List.copyOf(diagnostics); } + public static Response of(View view){return new Response(view,List.of(),null,null,view.diagnostics());} + } + Response execute(Request request); +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationTasks.java b/prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationTasks.java new file mode 100644 index 00000000..b0bc4c2e --- /dev/null +++ b/prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationTasks.java @@ -0,0 +1,8 @@ +package p.studio.api.assets.animation; +import java.nio.file.Path; +import java.util.function.Function; +import p.studio.api.project.ProjectReference; +/** Task adapter resolves the project only after existing session authority admission. */ +public interface AnimationTasks { + AnimationService.Response execute(Path root,String taskId,Function request); +} diff --git a/prometeu-studio-api/src/main/java/p/studio/api/assets/workspace/AssetWorkspaceAssetSummary.java b/prometeu-studio-api/src/main/java/p/studio/api/assets/workspace/AssetWorkspaceAssetSummary.java index c8ae3286..6d2081ef 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/assets/workspace/AssetWorkspaceAssetSummary.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/assets/workspace/AssetWorkspaceAssetSummary.java @@ -17,8 +17,11 @@ public record AssetWorkspaceAssetSummary( AssetStudioGlyphSpecialization glyphSpecialization, Path assetRoot, boolean preload, - boolean hasDiagnostics) { + boolean hasDiagnostics, String assetUuid) { + public AssetWorkspaceAssetSummary(AssetReference assetReference,String assetName,AssetWorkspaceAssetState state,AssetWorkspaceBuildParticipation buildParticipation,Integer assetId,AssetFamily assetFamily,AssetStudioGlyphSpecialization glyphSpecialization,Path assetRoot,boolean preload,boolean hasDiagnostics) { + this(assetReference,assetName,state,buildParticipation,assetId,assetFamily,glyphSpecialization,assetRoot,preload,hasDiagnostics,null); + } public AssetWorkspaceAssetSummary { Objects.requireNonNull(assetReference, "assetReference"); assetName = Objects.requireNonNull(assetName, "assetName").trim(); diff --git a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java index 32e332cd..1ab266a4 100644 --- a/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java +++ b/prometeu-studio-api/src/main/java/p/studio/api/automation/AutomationFailure.java @@ -14,7 +14,7 @@ public record AutomationFailure(Code code, String message, Map r UNSUPPORTED_LANGUAGE, UNSUPPORTED_CAPABILITY, REFERENCE_NOT_FOUND, DOCUMENTATION_UNAVAILABLE, OUTSIDE_PROJECT_SCOPE, READ_ONLY_SCOPE, OPERATION_NOT_FOUND, CLIENT_REQUEST_CONFLICT, RUNTIME_UNAVAILABLE, RUNTIME_INCOMPATIBLE, SESSION_NOT_FOUND, BUILD_NOT_FOUND, - NO_FRAME_AVAILABLE, LIMIT_EXCEEDED, NOT_CANCELABLE, MEMCARD_ERROR, INFRASTRUCTURE_FAILURE + ANIMATION_INVALID, ANIMATION_CONFLICT, NO_FRAME_AVAILABLE, LIMIT_EXCEEDED, NOT_CANCELABLE, MEMCARD_ERROR, INFRASTRUCTURE_FAILURE } public AutomationFailure { Objects.requireNonNull(code); Objects.requireNonNull(message); diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/AnimationOperations.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/AnimationOperations.java new file mode 100644 index 00000000..1ca38361 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/AnimationOperations.java @@ -0,0 +1,10 @@ +package p.studio.core.assets; + +import p.studio.api.assets.animation.AnimationService; +import java.util.function.Consumer; + +/** Exported assets-module seam; the session module supplies existing authority and publication gates. */ +@FunctionalInterface +public interface AnimationOperations { + AnimationService.Response execute(AnimationService.Request request, Runnable authority, Consumer publication); +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java index dc9ff473..5d7d3472 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetCatalog.java @@ -42,7 +42,7 @@ public final class PackerAssetCatalog implements AssetCatalog { AssetFamily.valueOf(summary.assetFamily().name()), summary.identity().assetRoot(), summary.preloadEnabled(), - summary.hasDiagnostics())) + summary.hasDiagnostics(), summary.identity().assetUuid())) .toList(); } } diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetDetails.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetDetails.java index de714013..ff92fe61 100644 --- a/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetDetails.java +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/PackerAssetDetails.java @@ -69,7 +69,7 @@ public final class PackerAssetDetails implements AssetDetails { AssetFamily.valueOf(summary.assetFamily().name()), summary.identity().assetRoot(), summary.preloadEnabled(), - summary.hasDiagnostics()); + summary.hasDiagnostics(), summary.identity().assetUuid()); } private static AssetConfigurationField field(PackerCodecConfigurationFieldDTO field) { diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/animation/AnimationPreviewRenderer.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/animation/AnimationPreviewRenderer.java new file mode 100644 index 00000000..463d198a --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/animation/AnimationPreviewRenderer.java @@ -0,0 +1,29 @@ +package p.studio.core.assets.animation; + +import p.animation.*; +import p.studio.api.automation.CanonicalCapture; +import java.awt.image.BufferedImage; +import java.io.ByteArrayOutputStream; +import javax.imageio.ImageIO; + +/** Toolkit-neutral rendering consumes the exact Packer material indices/palette bytes. */ +public final class AnimationPreviewRenderer { + public CanonicalCapture render(GlyphBankLayout bank,AnimationTimeline.Observation frame,int paletteId,String revision) { + byte[] palettes=bank.rgbaPalettes(); + if(paletteId<0||paletteId>=palettes.length/64)throw new IllegalArgumentException("invalid_palette"); + var glyph=bank.glyphs().stream().filter(g->g.glyphId()==frame.glyphId()&&g.artifactId().equals(frame.artifactId())).findFirst().orElseThrow(()->new IllegalArgumentException("unknown_glyph")); + byte[] indices=glyph.indices(); + if(glyph.width()<=0||glyph.height()<=0||indices.length!=glyph.width()*glyph.height())throw new IllegalArgumentException("invalid_glyph_pixels"); + var image=new BufferedImage(glyph.width(),glyph.height(),BufferedImage.TYPE_INT_ARGB); + for(int y=0;y=16)throw new IllegalArgumentException("invalid_material_index"); + int offset=paletteId*64+index*4; + int rgba=(Byte.toUnsignedInt(palettes[offset])<<24)|(Byte.toUnsignedInt(palettes[offset+1])<<16)|(Byte.toUnsignedInt(palettes[offset+2])<<8)|Byte.toUnsignedInt(palettes[offset+3]); + image.setRGB(x,y,(rgba>>>8)|((rgba&255)<<24)); + } + try(var out=new ByteArrayOutputStream()){ + if(!ImageIO.write(image,"png",out))throw new IllegalStateException("PNG encoder unavailable"); + return new CanonicalCapture("animation:"+bank.assetUuid(),revision,frame.phase(),frame.phase(),glyph.width(),glyph.height(),glyph.width(),out.toByteArray()); + }catch(java.io.IOException error){throw new IllegalStateException("Preview encoding failed",error);} + } +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/animation/DefaultAnimationService.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/animation/DefaultAnimationService.java new file mode 100644 index 00000000..48c5d62e --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/animation/DefaultAnimationService.java @@ -0,0 +1,111 @@ +package p.studio.core.assets.animation; + +import p.animation.*; +import p.studio.api.assets.*; +import p.studio.api.assets.animation.AnimationService; +import java.nio.file.*; +import java.nio.charset.StandardCharsets; +import java.util.*; +import java.util.function.Consumer; + +/** Shared application service. Manual/task adapters supply existing authority before entry. */ +public final class DefaultAnimationService implements p.studio.core.assets.AnimationOperations { + private final GlyphBankLayoutSource layouts;private final AssetCatalog assets; + private final AnimationCodec codec=new AnimationCodec();private final AnimationValidator validator=new AnimationValidator(); + private final AnimationPreviewRenderer renderer=new AnimationPreviewRenderer(); + public DefaultAnimationService(GlyphBankLayoutSource layouts,AssetCatalog assets){this.layouts=Objects.requireNonNull(layouts);this.assets=Objects.requireNonNull(assets);} + public AnimationService.Response execute(AnimationService.Request request,Runnable authority,Consumer publication) { + authority.run();checkCancellation(); + if(request.operation()==AnimationService.Operation.LIST){ + var views=new ArrayList(); + for(var asset:assets.list(request.project(),false)){ + if(asset.family()!=AssetFamily.GLYPH_BANK||asset.registrationState()!=AssetRegistrationState.REGISTERED)continue; + try { + var node=new com.fasterxml.jackson.databind.ObjectMapper().readTree(asset.root().resolve("asset.json").toFile()); + var uuid=UUID.fromString(node.path("asset_uuid").asText()); + if(request.assetUuid()==null||request.assetUuid().equals(uuid))views.add(execute(AnimationService.Request.get(request.project(),uuid),authority,publication).view()); + } catch(java.io.IOException|IllegalArgumentException failure){ + // Report malformed registered definitions rather than returning a stale cached catalog. + views.add(new AnimationService.View(null,null,"",null,List.of(),"",List.of(new AnimationDiagnostic("bank_read","",failure.getMessage())))); + } + } + authority.run();return new AnimationService.Response(null,views,null,null,views.stream().flatMap(v->v.diagnostics().stream()).toList()); + } + Objects.requireNonNull(request.assetUuid(),"assetUuid"); + return layouts.withLayout(request.project().rootPath(),request.assetUuid(),bank->{ + authority.run();checkCancellation();Path file=definitionPath(request,bank); + var current=read(file,bank);var candidate=request.document()==null?current.document():request.document(); + return switch(request.operation()) { + case GET -> AnimationService.Response.of(current); + case VALIDATE -> candidate==null?AnimationService.Response.of(current):AnimationService.Response.of(view(bank,current.revision(),codec.encode(candidate),candidate)); + case PREVIEW -> { + if(candidate==null)throw new IllegalArgumentException("No valid animation document");validator.requireValid(candidate,bank); + if(request.elapsedTicks()==null||request.paletteId()==null)throw new IllegalArgumentException("elapsedTicks and paletteId are required"); + var observation=AnimationTimeline.sample(candidate,Objects.requireNonNull(request.animatorId()),Objects.requireNonNull(request.clipName()),request.elapsedTicks()); + String revision=request.document()==null?current.revision():AnimationRevision.of(codec.encode(candidate)); + var preview=new AnimationService.Preview(bank.assetUuid(),revision,observation,request.elapsedTicks(),request.paletteId(),renderer.render(bank,observation,request.paletteId(),revision)); + authority.run();yield new AnimationService.Response(current,List.of(),preview,null,List.of()); + } + case SAVE -> { + Objects.requireNonNull(request.document(),"document");validator.requireValid(request.document(),bank); + write(file,request.expectedRevision(),request.document(),publication);yield AnimationService.Response.of(read(file,bank)); + } + case DELETE -> { + requireRevision(request.expectedRevision(),current.revision()); + if(current.document()==null)throw new IllegalArgumentException("Repair the malformed document before deleting a definition"); + var remaining=current.document().animators().stream().filter(a->!a.id().equals(request.animatorId())).toList(); + if(remaining.size()==current.document().animators().size())throw new IllegalArgumentException("unknown_animator"); + var next=new AnimationDocument(1,current.document().bankAssetUuid(),current.document().bindings(),remaining);validator.requireValid(next,bank); + write(file,request.expectedRevision(),next,publication);yield AnimationService.Response.of(read(file,bank)); + } + case PREPARE_REBIND -> { + requireRevision(request.expectedRevision(),current.revision()); + if(current.document()==null)throw new IllegalArgumentException("Repair malformed JSON before rebind"); + var proposal=new AnimationRebind().prepare(current.document(),current.revision(),bank); + yield new AnimationService.Response(current,List.of(),null,proposal,validator.validate(proposal.document(),bank)); + } + case APPLY_REBIND -> { + requireRevision(request.expectedRevision(),current.revision()); + if(current.document()==null)throw new IllegalArgumentException("Repair malformed JSON before rebind"); + var proposal=new AnimationRebind().prepare(current.document(),current.revision(),bank); + if(!Objects.equals(bank.revision(),request.expectedBankRevision())||!Objects.equals(proposal.proposalHash(),request.proposalHash())||!Objects.equals(proposal.document(),request.document())) + throw new IllegalStateException("Animation rebind conflict: proposal or bank revision changed"); + validator.requireValid(proposal.document(),bank);write(file,request.expectedRevision(),proposal.document(),publication); + yield AnimationService.Response.of(read(file,bank)); + } + case LIST -> throw new AssertionError(); + }; + }); + } + private Path definitionPath(AnimationService.Request request,GlyphBankLayout bank){ + try { + Path assets=request.project().rootPath().resolve("assets").toRealPath();Path root=bank.assetRoot().toRealPath(); + if(!root.startsWith(assets)||!bank.assetUuid().equals(request.assetUuid()))throw new IllegalArgumentException("Bank lies outside project asset scope"); + Path file=root.resolve(AnimationDocument.FILE_NAME);if(Files.isSymbolicLink(file))throw new IllegalArgumentException("Animation sidecar must not be a symbolic link");return file; + }catch(java.io.IOException failure){throw new IllegalStateException("Cannot resolve registered bank",failure);} + } + private AnimationService.View read(Path file,GlyphBankLayout bank){ + try { + if(!Files.exists(file))return view(bank,null,"",null); + String text=Files.readString(file,StandardCharsets.UTF_8);String revision=AnimationRevision.of(text); + try{return view(bank,revision,text,codec.decode(text));} + catch(IllegalArgumentException error){return new AnimationService.View(bank.assetUuid(),revision,text,null,available(bank),bank.revision(),List.of(new AnimationDiagnostic("invalid_json","",error.getMessage())));} + }catch(java.io.IOException failure){throw new IllegalStateException("Cannot read animation definition",failure);} + } + private AnimationService.View view(GlyphBankLayout bank,String revision,String json,AnimationDocument doc){return new AnimationService.View(bank.assetUuid(),revision,json,doc,available(bank),bank.revision(),doc==null?List.of():validator.validate(doc,bank));} + private static List available(GlyphBankLayout bank){return bank.glyphs().stream().map(g->new AnimationDocument.Binding(g.artifactId(),g.glyphId(),g.fingerprint())).toList();} + private void write(Path file,String expected,AnimationDocument candidate,Consumer publication){ + byte[] encoded=codec.encode(candidate).getBytes(StandardCharsets.UTF_8); + publication.accept(()->{ + checkCancellation(); + try { + String actual=Files.exists(file)?AnimationRevision.of(Files.readAllBytes(file)):null;requireRevision(expected,actual); + Path temporary=Files.createTempFile(file.getParent(),".animation-",".tmp"); + try{Files.write(temporary,encoded);checkCancellation();Files.move(temporary,file,StandardCopyOption.ATOMIC_MOVE,StandardCopyOption.REPLACE_EXISTING);} + finally{Files.deleteIfExists(temporary);} + }catch(java.io.IOException failure){throw new IllegalStateException("Atomic animation save failed",failure);} + }); + } + private static void requireRevision(String expected,String actual){if(!Objects.equals(expected,actual))throw new IllegalStateException("Animation revision conflict");} + private static void checkCancellation(){if(Thread.currentThread().isInterrupted())throw new java.util.concurrent.CancellationException("Animation operation cancelled");} +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/assets/animation/ManualAnimationService.java b/prometeu-studio-core/src/main/java/p/studio/core/assets/animation/ManualAnimationService.java new file mode 100644 index 00000000..35939a6c --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/assets/animation/ManualAnimationService.java @@ -0,0 +1,17 @@ +package p.studio.core.assets.animation; +import p.studio.api.assets.animation.AnimationService; +import p.studio.api.automation.ProjectAccess; +import java.util.concurrent.CancellationException; +/** UI adapter holds the existing manual lease for the full operation. */ +public final class ManualAnimationService implements AnimationService { + private final DefaultAnimationService service;private final ProjectAccess access; + public ManualAnimationService(DefaultAnimationService service,ProjectAccess access){this.service=service;this.access=access;} + @Override public Response execute(Request request){ + try(var lease=access.enterManual(request.project().rootPath())){ + Object lock=new Object();boolean[] cancelled={false}; + lease.onProjectClose(()->{synchronized(lock){cancelled[0]=true;}}); + Runnable check=()->{synchronized(lock){if(cancelled[0])throw new CancellationException("Project closed");}}; + return service.execute(request,check,work->{synchronized(lock){check.run();work.run();}}); + } + } +} diff --git a/prometeu-studio-core/src/main/java/p/studio/core/session/TaskAnimationService.java b/prometeu-studio-core/src/main/java/p/studio/core/session/TaskAnimationService.java new file mode 100644 index 00000000..04dabc68 --- /dev/null +++ b/prometeu-studio-core/src/main/java/p/studio/core/session/TaskAnimationService.java @@ -0,0 +1,43 @@ +package p.studio.core.session; +import p.studio.api.assets.animation.*; +import p.studio.api.automation.*; +import p.studio.api.project.*; +import p.studio.core.assets.AnimationOperations; +import p.studio.core.project.ProjectAccessRegistry; +import java.nio.file.Path; +import java.util.*; +import java.util.concurrent.*; +import java.util.concurrent.atomic.AtomicReference; +import java.util.function.Function; + +/** Existing task lifecycle owns admission, cancellation and atomic publication. */ +public final class TaskAnimationService implements AnimationTasks { + private final ProjectAccessRegistry projects;private final ProjectCatalog catalog;private final AnimationOperations service; + public TaskAnimationService(ProjectAccessRegistry projects,ProjectCatalog catalog,AnimationOperations service){this.projects=projects;this.catalog=catalog;this.service=service;} + @Override public AnimationService.Response execute(Path root,String id,Function factory){ + var session=projects.requireAutomation(root);var task=requireTask(session,id); + var result=new AtomicReference(); + var cancelled=new java.util.concurrent.atomic.AtomicBoolean(); + var handle=session.submit(task,"Animation authoring",()->{ + requireTask(session,id);var request=factory.apply(catalog.openProject(root)); + if(!request.project().rootPath().equals(task.projectRoot()))throw new AutomationException(AutomationFailure.Code.OUTSIDE_PROJECT_SCOPE,"Animation request changed project scope"); + Thread owner=Thread.currentThread(); + Runnable admitted=()->{requireTask(session,id);if(cancelled.get()||owner.isInterrupted())throw new CancellationException();}; + try { result.set(service.execute(request,admitted,work->{synchronized(session){admitted.run();work.run();}})); } + finally { if(owner.isInterrupted())cancelled.set(true); } + return new AutomationOutcome(AutomationOutcome.Kind.SUCCEEDED,0,0,List.of(),null); + }); + var cancellation=handle.subscribe(snapshot->{if(snapshot.state()==p.studio.api.operation.OperationState.CANCELLED)cancelled.set(true);}); + try { + handle.completion().handle((value,error)->null).thenCompose(ignored->handle.termination()).toCompletableFuture().get(12,TimeUnit.SECONDS); + handle.completion().toCompletableFuture().get();requireTask(session,id);return Objects.requireNonNull(result.get()); + }catch(ExecutionException error){if(error.getCause() instanceof RuntimeException cause)throw cause;throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE,"Animation operation failed");} + catch(InterruptedException error){handle.cancel();Thread.currentThread().interrupt();throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE,"Animation operation interrupted");} + catch(TimeoutException|CancellationException error){cancelled.set(true);handle.cancel();throw new AutomationException(AutomationFailure.Code.INFRASTRUCTURE_FAILURE,"Animation operation cancelled or timed out");} + finally { cancellation.unsubscribe(); } + } + private static TaskIdentity requireTask(AutomationSession session,String id){var snapshot=session.snapshot(); + if(snapshot.closed()||snapshot.state()!=ControlState.AGENT_WORKING||snapshot.task()==null||!snapshot.task().value().equals(id))throw new ControlDeniedException(ControlResult.Status.INVALID_TASK); + return snapshot.task(); + } +} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/events/StudioAnimationOriginRequestedEvent.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/events/StudioAnimationOriginRequestedEvent.java new file mode 100644 index 00000000..13be03ad --- /dev/null +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/events/StudioAnimationOriginRequestedEvent.java @@ -0,0 +1,4 @@ +package p.studio.ui.javafx.events; +import java.nio.file.Path; +import java.util.UUID; +public record StudioAnimationOriginRequestedEvent(Path projectRoot,UUID assetUuid,String jsonPointer) implements StudioEvent {} diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java index 867bc98a..664d5fb9 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/MainView.java @@ -46,8 +46,11 @@ public final class MainView extends BorderPane { private boolean workspaceLifecycleInitialized; private p.studio.api.operation.OperationSubscription controlSubscription; private p.studio.api.operation.OperationSubscription documentRegistration; + private p.studio.ui.javafx.events.StudioEventSubscription animationOrigins; private boolean closed; + public void setAnimationService(p.studio.api.assets.animation.AnimationService service){assetWorkspace.setAnimationService(service);} + public MainView(final ProjectSession projectSession, final Shipper shipper, final ExecutionControllerFactory executionControllerFactory, final I18nService i18n, @@ -92,6 +95,10 @@ public final class MainView extends BorderPane { assetCatalog, assetCommands, assetPacking, assetDetails, assetCreationCatalog, assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow); + animationOrigins=eventBus.subscribe(p.studio.ui.javafx.events.StudioAnimationOriginRequestedEvent.class,event->{ + if(!event.projectRoot().toAbsolutePath().normalize().equals(projectReference.rootPath()))return; + javafx.application.Platform.runLater(()->{if(!closed){selectWorkspace(WorkspaceId.ASSETS);assetWorkspace.openAnimationOrigin(event.assetUuid(),event.jsonPointer());}}); + }); host.register(assetWorkspace); assetWorkspace.restoreProjectLocalState(persistedState); assetWorkspace.setStateChangedAction(this::persistProjectLocalState); @@ -164,6 +171,7 @@ public final class MainView extends BorderPane { if (closed) return; closed = true; controlSubscription.unsubscribe(); + if(animationOrigins!=null)animationOrigins.unsubscribe(); documentRegistration.unsubscribe(); playStopCoordinator.shutdown(); persistProjectLocalState(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java index c48966db..f462cd52 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/window/StudioWindowCoordinator.java @@ -77,6 +77,8 @@ public final class StudioWindowCoordinator implements AutoCloseable { private Stage loadingStage; private Stage projectStage; private MainView mainView; + private p.studio.api.assets.animation.AnimationService animationService; + public void setAnimationService(p.studio.api.assets.animation.AnimationService service){this.animationService=service;} private ProjectSession projectSession; public StudioWindowCoordinator( @@ -266,6 +268,7 @@ public final class StudioWindowCoordinator implements AutoCloseable { assetMetadataService, assetWorkspaceStorage, assetCapacityPolicy, bankCompositionSessionFactory, assetColorSchemaFactory, tiledAssetService, sceneBankWorkflow, activityHistoryStore, connectionGuide); + if(animationService!=null)mainView.setAnimationService(animationService); this.projectSession = projectSession; final Scene scene = new Scene(mainView, PROJECT_WIDTH, PROJECT_HEIGHT); scene.getStylesheets().add(theme.getDefaultTheme()); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java index d4d8cb3b..614fa598 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/AssetWorkspace.java @@ -126,6 +126,9 @@ public final class AssetWorkspace extends Workspace { this.stateChangedAction = java.util.Objects.requireNonNull(stateChangedAction, "stateChangedAction"); } + public void openAnimationOrigin(java.util.UUID bank,String pointer){detailsControl.openAnimationOrigin(bank,pointer);} + public void setAnimationService(p.studio.api.assets.animation.AnimationService service){detailsControl.setAnimationService(service);} + public p.studio.api.automation.DocumentHandoff documentHandoff() { return detailsControl.documentHandoff(); } public void restoreProjectLocalState(final ProjectLocalStudioState projectLocalStudioState) { diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java index 533fff0d..8391b6f0 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetDetailsControl.java @@ -78,29 +78,45 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware private final p.studio.ui.javafx.utilities.i18n.I18nService i18n; private final p.studio.ui.javafx.utilities.ThemeService theme; private final AssetCommands assetCommands; + private AssetCatalog animationCatalog; + private java.util.UUID originBank;private String originPointer; private final AssetDetails assetDetails; private AssetWorkspaceDetailsViewState viewState = AssetDetailsViewStateFactory.empty(); + private p.studio.ui.javafx.workspaces.assets.details.animation.AnimationEditorControl animationEditor; private boolean readyMounted; private boolean actionRunning; private String actionFeedbackMessage; + public void openAnimationOrigin(java.util.UUID bank,String pointer){ + originBank=bank;originPointer=pointer; + executor.execute(()->{var asset=animationCatalog.list(projectReference,false).stream().filter(a->bank.toString().equals(a.assetUuid())).findFirst(); + Platform.runLater(()->asset.ifPresent(a->{loadSelection(a.reference());detailsScroll.setVvalue(1.0);}));}); + } + public void setAnimationService(p.studio.api.assets.animation.AnimationService service) { + if(animationEditor!=null)animationEditor.close(); + animationEditor=new p.studio.ui.javafx.workspaces.assets.details.animation.AnimationEditorControl(projectReference,service,executor); + readyMounted=false;render(); + } public p.studio.api.automation.DocumentHandoff documentHandoff() { return new p.studio.api.automation.DocumentHandoff() { private volatile boolean disposed; private final java.util.Set> pending = java.util.concurrent.ConcurrentHashMap.newKeySet(); @Override public void close() { disposed = true; + if(animationEditor!=null)onFx(()->{animationEditor.close();return null;}); pending.forEach(future -> future.complete(null)); pending.clear(); } @Override public java.util.concurrent.CompletionStage hasUnsavedChanges() { - return onFx(() -> handoffForms().stream().anyMatch(p.studio.ui.javafx.controls.forms.StudioFormSection::hasUnsavedDraft)); + return onFx(() -> handoffForms().stream().anyMatch(p.studio.ui.javafx.controls.forms.StudioFormSection::hasUnsavedDraft)) + .thenCompose(formsDirty->animationEditor==null?java.util.concurrent.CompletableFuture.completedFuture(formsDirty):animationEditor.hasUnsavedChanges().thenApply(animationDirty->formsDirty||animationDirty)); } @Override public java.util.concurrent.CompletionStage saveAll() { return onFx(() -> { java.util.concurrent.CompletionStage saved = java.util.concurrent.CompletableFuture.completedFuture(null); for (var form : handoffForms()) saved = saved.thenCompose(v -> form.saveForHandoff()); + if(animationEditor!=null)saved=saved.thenCompose(v->animationEditor.saveAll()); return saved; }).thenCompose(saved -> saved); } @@ -112,13 +128,14 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware onFx(() -> { if (disposed) { refreshed.complete(null); return null; } handoffForms().forEach(p.studio.ui.javafx.controls.forms.StudioFormSection::discardDraftForHandoff); + var animationRefresh = animationEditor == null ? java.util.concurrent.CompletableFuture.completedFuture(null) : animationEditor.refreshFromDisk(); var selected = viewState.selectedAssetReference(); - if (selected == null) { refreshed.complete(null); return refreshed; } + if (selected == null) { animationRefresh.whenComplete((v,f)->{if(f==null)refreshed.complete(null);else refreshed.completeExceptionally(f);}); return refreshed; } long generation = loadGeneration.incrementAndGet(); executor.execute(() -> { try { var details = mapDetails(assetDetails.get(projectReference, selected)); - Platform.runLater(() -> { if (!disposed) applyLoadedDetails(generation, selected, details); refreshed.complete(null); }); + Platform.runLater(() -> { if (!disposed) applyLoadedDetails(generation, selected, details); animationRefresh.whenComplete((v,f)->{if(f==null)refreshed.complete(null);else refreshed.completeExceptionally(f);}); }); } catch (RuntimeException failure) { Platform.runLater(() -> { if (!disposed) applyLoadFailure(generation, selected, failure); refreshed.completeExceptionally(failure); }); } @@ -162,7 +179,7 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware this.executor = Objects.requireNonNull(executor, "executor"); this.i18n = Objects.requireNonNull(i18n, "i18n"); this.theme = Objects.requireNonNull(theme, "theme"); - this.assetCommands = Objects.requireNonNull(assetCommands, "assetCommands"); + this.assetCommands = Objects.requireNonNull(assetCommands, "assetCommands");this.animationCatalog=assetCatalog; this.assetDetails = Objects.requireNonNull(assetDetails, "assetDetails"); this.studioMetadataService = Objects.requireNonNull(assetMetadataService, "assetMetadataService"); this.tiledGenerationService = Objects.requireNonNull(tiledAssetService, "tiledAssetService"); @@ -365,6 +382,11 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware sections.add(colorSchemaGroupsControl); } sections.add(paletteOverhaulingControl); + if(animationEditor!=null&&viewState.selectedAssetDetails().summary().assetFamily()==AssetFamily.GLYPH_BANK) { + var uuid=viewState.selectedAssetDetails().summary().assetUuid(); + boolean bound=animationEditor.bind(uuid==null?null:java.util.UUID.fromString(uuid));sections.add(animationEditor); + if(bound&&uuid!=null&&originBank!=null&&uuid.equals(originBank.toString())){animationEditor.openOrigin(originPointer);originBank=null;originPointer=null;} + } return sections.toArray(Node[]::new); } @@ -778,7 +800,7 @@ public final class AssetDetailsControl extends VBox implements StudioEventAware studioMetadata.glyphSpecialization(), baseSummary.assetRoot(), baseSummary.preload(), - baseSummary.hasDiagnostics()); + baseSummary.hasDiagnostics(), baseSummary.assetUuid()); final AssetWorkspaceBankCompositionDetails bankComposition = mapBankComposition(details.bankComposition()); final var availableCodecs = details.availableOutputCodecs(); final var codecFields = details.codecConfigurationFieldsByCodec(); diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetListMappings.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetListMappings.java index 5e406dda..a46cb4b0 100644 --- a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetListMappings.java +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/AssetListMappings.java @@ -21,6 +21,6 @@ public final class AssetListMappings { AssetStudioGlyphSpecialization.NONE, summary.root(), summary.preload(), - summary.hasDiagnostics()); + summary.hasDiagnostics(), summary.assetUuid()); } } diff --git a/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/animation/AnimationEditorControl.java b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/animation/AnimationEditorControl.java new file mode 100644 index 00000000..110f6c7b --- /dev/null +++ b/prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/animation/AnimationEditorControl.java @@ -0,0 +1,127 @@ +package p.studio.ui.javafx.workspaces.assets.details.animation; + +import javafx.application.Platform; +import javafx.animation.*; +import javafx.util.Duration; +import javafx.scene.control.*; +import javafx.scene.image.*; +import javafx.scene.layout.*; +import p.animation.*; +import p.studio.api.assets.animation.AnimationService; +import p.studio.api.automation.DocumentHandoff; +import p.studio.api.project.ProjectReference; +import java.util.*; +import java.util.concurrent.*; +import java.util.function.*; +import static p.animation.AnimationDocument.*; + +/** Draft editing only. Validation, preview, revision conflicts and writes belong to shared services. */ +public final class AnimationEditorControl extends VBox implements DocumentHandoff { + private final ProjectReference project; private final AnimationService service;private final Executor executor; + private final ComboBox animators=new ComboBox<>(),clips=new ComboBox<>(),mode=new ComboBox<>(); + private final TextField animatorName=new TextField(),clipName=new TextField(),duration=new TextField("1"),ticks=new TextField("0"),palette=new TextField("0"); + private final ComboBox glyphs=new ComboBox<>();private final ListView frames=new ListView<>(); + private final TextArea json=new TextArea(),diagnostics=new TextArea(),rebindDiff=new TextArea(); + private final Label status=new Label("Choose a registered glyph bank");private final ImageView image=new ImageView(); + private final Spinner rate=new Spinner<>(1,60,10);private final ToggleButton play=new ToggleButton("Play"); + private final Timeline clock=new Timeline();private final Button save=new Button("Save"),applyRebind=new Button("Apply rebind"); + private UUID bank;private AnimationService.View saved;private AnimationDocument draft;private AnimationRebind.Proposal proposal; + private boolean projecting,closed,busy;private long generation;private String cleanText="";private String pendingOrigin; + private CompletionStage pending=CompletableFuture.completedFuture(null); + + public AnimationEditorControl(ProjectReference project,AnimationService service,Executor executor){ + super(8);this.project=project;this.service=service;this.executor=executor; + getStyleClass().add("studio-section");setId("animation-editor"); + animatorName.setId("animation-id");clipName.setId("animation-clip-name");duration.setId("animation-duration");ticks.setId("animation-ticks");palette.setId("animation-palette");glyphs.setId("animation-glyph");mode.setId("animation-mode");status.setId("animation-status");image.setId("animation-image");json.setId("animation-json"); + var title=new Label("Animations");title.getStyleClass().add("assets-workspace-pane-title"); + animatorName.setPromptText("Animator ID");clipName.setPromptText("Clip name");mode.getItems().setAll("once","loop");mode.setValue("loop"); + animators.setPromptText("Animator");clips.setPromptText("Clip");glyphs.setPromptText("Glyph from this bank"); + glyphs.setConverter(new javafx.util.StringConverter<>(){ + @Override public String toString(Binding b){return b==null?"":"#"+b.glyphId()+" · "+b.artifactId();} + @Override public Binding fromString(String s){return null;} + }); + frames.setPrefHeight(130);frames.setCellFactory(ignored->new ListCell<>(){@Override protected void updateItem(Frame f,boolean empty){super.updateItem(f,empty);setText(empty||f==null?null:f.artifactId()+" · "+f.durationTicks()+" ticks");}}); + frames.getSelectionModel().selectedItemProperty().addListener((o,b,f)->{if(f!=null){duration.setText(Long.toString(f.durationTicks()));glyphs.getItems().stream().filter(g->g.artifactId().equals(f.artifactId())).findFirst().ifPresent(glyphs::setValue);}}); + animators.valueProperty().addListener((o,b,a)->{if(!projecting)showAnimator();});clips.valueProperty().addListener((o,b,c)->{if(!projecting)showClip();}); + mode.valueProperty().addListener((o,b,m)->{if(!projecting&&selectedClip()!=null)editClip(c->new Clip(c.name(),m,c.frames()));}); + json.setPrefRowCount(6);json.setWrapText(false);diagnostics.setPrefRowCount(3);diagnostics.setEditable(false);diagnostics.setWrapText(true); + rebindDiff.setPrefRowCount(3);rebindDiff.setEditable(false); + image.setFitWidth(160);image.setFitHeight(160);image.setPreserveRatio(true);image.setSmooth(false); + var animRow=row(animators,animatorName,button("New animator",this::addAnimator),button("Rename",this::renameAnimator),button("Delete",this::deleteAnimator)); + var clipRow=row(clips,clipName,mode,button("New clip",this::addClip),button("Rename",this::renameClip),button("Delete",this::deleteClip),button("Use as initial",this::setInitial)); + var frameRow=row(glyphs,new Label("Ticks"),duration,button("Add frame",()->putFrame(false)),button("Update",()->putFrame(true)),button("Remove",this::removeFrame),button("Up",()->moveFrame(-1)),button("Down",()->moveFrame(1))); + save.setOnAction(e->saveAll().exceptionally(failure->{Platform.runLater(()->report(failure));return null;}));applyRebind.setOnAction(e->applyRebind());applyRebind.setDisable(true); + var documentRow=row(save,button("Validate draft",this::validateDraft),button("Reload",this::refreshFromDisk),button("Read JSON draft",this::readJsonDraft),status); + var previewRow=row(play,button("Step",()->step(1)),new Label("Elapsed ticks"),ticks,new Label("Palette"),palette,new Label("Preview ticks/s"),rate,button("Preview",this::preview)); + play.setOnAction(e->{if(play.isSelected()){clock.getKeyFrames().setAll(new KeyFrame(Duration.millis(1000.0/rate.getValue()),event->step(1)));clock.setCycleCount(Animation.INDEFINITE);clock.play();}else clock.stop();}); + disabledProperty().addListener((o,b,disabled)->{if(disabled){clock.stop();play.setSelected(false);}}); + getChildren().setAll(title,animRow,clipRow,frames,frameRow,previewRow,image,documentRow,diagnostics,new TitledPane("Canonical JSON / repair",json),row(button("Prepare rebind",this::prepareRebind),applyRebind),rebindDiff); + setDisable(true); + } + private static FlowPane row(javafx.scene.Node... nodes) { + var row = new FlowPane(6, 6, nodes); + for (var node : nodes) { + if (node instanceof TextField field) field.setPrefColumnCount(10); + if (node instanceof ComboBox combo) combo.setPrefWidth(180); + } + return row; + } + private Button button(String text,Runnable action){var b=new Button(text);b.setOnAction(e->{try{if(!busy)action.run();}catch(RuntimeException failure){report(failure);}});return b;} + public boolean bind(UUID next){ + if(Objects.equals(bank,next)&&saved!=null)return true; + if(busy){status.setText("Wait for the current bank operation before changing banks");return false;} + if(hasDraft()){status.setText("Save or reload the animation draft for "+bank+" before changing banks");return false;} + clock.stop();play.setSelected(false);generation++;bank=next;saved=null;draft=null;cleanText="";projecting=true;json.clear();projecting=false; + setDisable(next==null);if(next!=null)refreshFromDisk();return true; + } + private boolean hasDraft(){return !json.getText().equals(cleanText);} + private Animator selectedAnimator(){return draft==null?null:draft.animators().stream().filter(a->a.id().equals(animators.getValue())).findFirst().orElse(null);} + private Clip selectedClip(){var a=selectedAnimator();return a==null?null:a.clips().stream().filter(c->c.name().equals(clips.getValue())).findFirst().orElse(null);} + private void showAnimator(){var a=selectedAnimator();projecting=true;String old=clips.getValue();clips.getItems().setAll(a==null?List.of():a.clips().stream().map(Clip::name).toList());if(a!=null){animatorName.setText(a.id());clips.setValue(clips.getItems().contains(old)?old:a.initialClip());}projecting=false;showClip();} + private void showClip(){var c=selectedClip();projecting=true;frames.getItems().setAll(c==null?List.of():c.frames());if(c!=null){clipName.setText(c.name());mode.setValue(c.mode());}projecting=false;} + private void changed(){json.setText(new AnimationCodec().encode(draft));status.setText("Unsaved draft");proposal=null;applyRebind.setDisable(true);} + private void replaceAnimator(Animator before,Animator after){var values=new ArrayList<>(draft.animators());int i=values.indexOf(before);if(i>=0)values.set(i,after);else values.add(after);draft=new AnimationDocument(1,draft.bankAssetUuid(),draft.bindings(),values);projecting=true;animators.getItems().setAll(values.stream().map(Animator::id).toList());animators.setValue(after.id());projecting=false;changed();showAnimator();} + private void editClip(UnaryOperator edit){var a=selectedAnimator();var old=selectedClip();if(a==null||old==null)return;var next=edit.apply(old);var values=new ArrayList<>(a.clips());values.set(values.indexOf(old),next);String initial=a.initialClip().equals(old.name())?next.name():a.initialClip();replaceAnimator(a,new Animator(a.id(),initial,values));clips.setValue(next.name());} + private void addAnimator(){if(draft==null)return;replaceAnimator(null,new Animator(animatorName.getText(),"idle",List.of(new Clip("idle","loop",List.of()))));} + private void renameAnimator(){var a=selectedAnimator();if(a!=null)replaceAnimator(a,new Animator(animatorName.getText(),a.initialClip(),a.clips()));} + private void deleteAnimator(){var a=selectedAnimator();if(a==null)return;var values=new ArrayList<>(draft.animators());values.remove(a);draft=new AnimationDocument(1,draft.bankAssetUuid(),draft.bindings(),values);projecting=true;animators.getItems().setAll(values.stream().map(Animator::id).toList());animators.setValue(values.isEmpty()?null:values.getFirst().id());projecting=false;changed();showAnimator();} + private void addClip(){var a=selectedAnimator();if(a==null)return;var values=new ArrayList<>(a.clips());values.add(new Clip(clipName.getText(),mode.getValue(),List.of()));replaceAnimator(a,new Animator(a.id(),a.initialClip(),values));clips.setValue(clipName.getText());} + private void renameClip(){editClip(c->new Clip(clipName.getText(),c.mode(),c.frames()));} + private void deleteClip(){var a=selectedAnimator();var c=selectedClip();if(a==null||c==null)return;var values=new ArrayList<>(a.clips());values.remove(c);replaceAnimator(a,new Animator(a.id(),a.initialClip(),values));} + private void setInitial(){var a=selectedAnimator();if(a!=null&&clips.getValue()!=null)replaceAnimator(a,new Animator(a.id(),clips.getValue(),a.clips()));} + private void putFrame(boolean update){var glyph=glyphs.getValue();if(glyph==null)return;long value=Long.parseLong(duration.getText());int index=frames.getSelectionModel().getSelectedIndex();editClip(c->{var values=new ArrayList<>(c.frames());var next=new Frame(glyph.artifactId(),value);if(update&&index>=0)values.set(index,next);else values.add(next);return new Clip(c.name(),c.mode(),values);});} + private void removeFrame(){int index=frames.getSelectionModel().getSelectedIndex();if(index>=0)editClip(c->{var values=new ArrayList<>(c.frames());values.remove(index);return new Clip(c.name(),c.mode(),values);});} + private void moveFrame(int delta){int index=frames.getSelectionModel().getSelectedIndex();var c=selectedClip();if(c==null||index<0||index+delta<0||index+delta>=c.frames().size())return;editClip(old->{var values=new ArrayList<>(old.frames());Collections.swap(values,index,index+delta);return new Clip(old.name(),old.mode(),values);});frames.getSelectionModel().select(index+delta);} + private void readJsonDraft(){draft=new AnimationCodec().decode(json.getText());String selected=animators.getValue();projecting=true;animators.getItems().setAll(draft.animators().stream().map(Animator::id).toList());animators.setValue(animators.getItems().contains(selected)?selected:animators.getItems().stream().findFirst().orElse(null));projecting=false;showAnimator();validateDraft();} + private AnimationService.Request request(AnimationService.Operation operation,AnimationDocument doc){return new AnimationService.Request(operation,project,bank,animators.getValue(),clips.getValue(),operation==AnimationService.Operation.PREVIEW?Long.parseLong(ticks.getText()):null,operation==AnimationService.Operation.PREVIEW?Integer.parseInt(palette.getText()):null,saved==null?null:saved.revision(),doc,proposal==null?null:proposal.proposalHash(),proposal==null?null:proposal.bankRevision());} + private void validateDraft(){call(request(AnimationService.Operation.VALIDATE,new AnimationCodec().decode(json.getText())),response->showDiagnostics(response.diagnostics()));} + private void preview(){if(bank==null||busy)return;call(request(AnimationService.Operation.PREVIEW,new AnimationCodec().decode(json.getText())),response->{if(response.preview()!=null){image.setImage(new Image(new java.io.ByteArrayInputStream(response.preview().image().png())));status.setText(response.preview().observation().state()+" · glyph "+response.preview().observation().glyphId()+" · phase "+response.preview().observation().phase());}showDiagnostics(response.diagnostics());});} + private void step(int value){if(busy)return;try{ticks.setText(Long.toString(Math.addExact(Long.parseLong(ticks.getText()),value)));preview();}catch(RuntimeException failure){clock.stop();play.setSelected(false);report(failure);}} + private void prepareRebind(){if(hasDraft()){status.setText("Save or reload the draft before preparing rebind");return;}call(request(AnimationService.Operation.PREPARE_REBIND,null),response->{proposal=response.proposal();rebindDiff.setText(proposal==null?"":proposal.differences().toString());applyRebind.setDisable(proposal==null||!response.diagnostics().isEmpty());showDiagnostics(response.diagnostics());});} + private void applyRebind(){if(proposal!=null)call(request(AnimationService.Operation.APPLY_REBIND,proposal.document()),response->loaded(response.view()));} + private void loaded(AnimationService.View view){ + if(view==null)return;saved=view;draft=view.document();glyphs.getItems().setAll(view.availableBindings()); + if(draft==null&&view.revision()==null)draft=new AnimationDocument(1,bank.toString(),view.availableBindings(),List.of()); + String source=view.document()==null&&view.revision()!=null?view.json():new AnimationCodec().encode(draft); + json.setText(source);cleanText=source;projecting=true;animators.getItems().setAll(draft==null?List.of():draft.animators().stream().map(Animator::id).toList());animators.getSelectionModel().selectFirst();projecting=false;showAnimator();showDiagnostics(view.diagnostics());status.setText(view.revision()==null?"New definition":"Saved definition");if(pendingOrigin!=null){String pointer=pendingOrigin;pendingOrigin=null;openOrigin(pointer);} + } + private void showDiagnostics(List values){diagnostics.setText(values.stream().map(d->d.pointer()+" · "+d.message()).collect(java.util.stream.Collectors.joining("\n")));} + private void report(Throwable failure){diagnostics.setText(failure.getMessage());status.setText("Draft retained; operation failed");} + private CompletionStage call(AnimationService.Request request,Consumer apply){ + long version=generation;busy=true;save.setDisable(true);var done=new CompletableFuture();pending=done; + CompletableFuture.supplyAsync(()->service.execute(request),executor).whenComplete((response,failure)->Platform.runLater(()->{ + if(closed||version!=generation){done.complete(null);return;}busy=false;save.setDisable(false); + if(failure!=null){var cause=failure instanceof CompletionException?failure.getCause():failure;report(cause);done.completeExceptionally(cause);} + else{try{apply.accept(response);done.complete(null);}catch(RuntimeException error){report(error);done.completeExceptionally(error);}} + }));return done; + } + private static CompletionStage fx(Supplier action){var result=new CompletableFuture();Runnable run=()->{try{result.complete(action.get());}catch(Throwable error){result.completeExceptionally(error);}};if(Platform.isFxApplicationThread())run.run();else Platform.runLater(run);return result;} + @Override public CompletionStage hasUnsavedChanges(){return fx(this::hasDraft);} + @Override public CompletionStage saveAll(){if(busy)return pending.thenCompose(v->saveAll());return fx(()->{if(bank==null||!hasDraft())return CompletableFuture.completedFuture(null);var doc=new AnimationCodec().decode(json.getText());String submitted=json.getText();return call(AnimationService.Request.save(project,bank,saved==null?null:saved.revision(),doc),response->{ + if(json.getText().equals(submitted))loaded(response.view()); + else{saved=response.view();cleanText=saved.json();status.setText("Saved earlier draft; current edits retained");} + });}).thenCompose(v->v);} + @Override public CompletionStage refreshFromDisk(){return fx(()->{if(busy)return pending.thenCompose(v->refreshFromDisk());if(bank==null)return CompletableFuture.completedFuture(null);clock.stop();play.setSelected(false);return call(AnimationService.Request.get(project,bank),response->loaded(response.view()));}).thenCompose(v->v);} + public void openOrigin(String pointer){if(draft==null){pendingOrigin=pointer;return;}String[] parts=pointer.split("/");try{if(parts.length>2){animators.setValue(draft.animators().get(Integer.parseInt(parts[2])).id());if(parts.length>4){clips.setValue(selectedAnimator().clips().get(Integer.parseInt(parts[4])).name());if(parts.length>6)frames.getSelectionModel().select(Integer.parseInt(parts[6]));}}json.requestFocus();}catch(IndexOutOfBoundsException|NumberFormatException ignored){status.setText("Source changed; choose the current definition");}} + @Override public void close(){closed=true;generation++;clock.stop();play.setSelected(false);pending.toCompletableFuture().complete(null);} +} diff --git a/settings.gradle.kts b/settings.gradle.kts index e3a666c8..dfa9a555 100644 --- a/settings.gradle.kts +++ b/settings.gradle.kts @@ -5,6 +5,7 @@ plugins { rootProject.name = "prometeu-studio" include("prometeu-infra") +include("prometeu-animation") include("prometeu-packer:prometeu-packer-api") include("prometeu-packer:prometeu-packer-v1") diff --git a/tools/pbx-conformance/README.md b/tools/pbx-conformance/README.md index 2d571779..6aad86aa 100644 --- a/tools/pbx-conformance/README.md +++ b/tools/pbx-conformance/README.md @@ -505,3 +505,41 @@ GC fixtures require actual advancing collection counters. Snapshots release sour backings and observe 1,200 → 1 → 1 → 0 nodes/payloads. Collection fixtures observe 64 → 61 → 0 → 1 → 0 payloads and only one retained backing until its final owner is dropped. Temporary Cargo projects/targets stay outside the runtime checkout. + + +## PBS Result, Sprite and Animation qualification + +Generate the source corpora with `:prometeu-architecture-tests:test` and +`:prometeu-app:installedKnowledgeTest`. Focused native gates are `--result-only` +and `--animation-only`; add `--release` for the runtime release profile. Before +animation qualification, generate the Composer pixel corpus with +`:prometeu-app:headlessProcessTest --tests '*AnimationInstalledRuntimeTest'` +and `-PstudioRuntimeInstall=`. The desktop gate +is `:prometeu-app:animationDesktopTest`. Each native gate +requires both ordinary and optimized producer variants and fails on missing fixtures. + +Result executes status plus complete payload groups, once-only propagation and +handling, error remapping, reference/Fn/trait/builtin payloads and uncaught traps. +Animation executes the public core, reusable independent backing, state/reset/time +boundaries, every domain error, exact long limits and a test-only near-limit state. +The isolated count/phase setup is never shipped as a public mutation hook. + +`animation.rs` single-steps actual instructions between post-construction markers. +Sprite and successful, negative and overflow advance paths must execute zero +StructNew/ArrayNew/MakeClosure instructions. Large jumps must remain below the +bounded instruction gate. Zero guest/handle quotas trap during construction and +are distinct from recoverable domain errors. A test-only safepoint marker observes +live private rings followed by complete reclamation after their last owner clears. + +The installed-JAR producer saves a real Packer-bound canonical sidecar, compiles +virtual factories with read-only JSON origins and supplies both producer variants +for production firmware execution. `AnimationInstalledRuntimeTest` separately boots +the configured extracted runtime and compares every pixel of direct/generated +Composer sprites with the shared preview across tick boundaries and alternating +palettes. That saved-project corpus is replayed by production firmware in native +dev/release with both producers, comparing the exact same canonical pixels. The public Composer +facade retains int status and nine arguments; its private host carrier is narrowed +from the existing native Int64 status. No runtime source write is required. + +Keep Cargo targets in `/tmp` and retain source hashes, provider revision, profiles, +allocation counts and GC observations with the completed discussion's evidence. diff --git a/tools/pbx-conformance/animation.rs b/tools/pbx-conformance/animation.rs new file mode 100644 index 00000000..e974b209 --- /dev/null +++ b/tools/pbx-conformance/animation.rs @@ -0,0 +1,118 @@ +//! Real core playback and executed allocation evidence, including error paths. +use super::*; +use prometeu_vm::LogicalFrameEndingReason as End; +use prometeu_bytecode::{decode_next, isa::core::CoreOpCode as Op}; + +pub fn verify(root: &std::path::Path) { + let manifest = std::fs::read_to_string(root.join("pbs-animation-manifest.txt")).expect("mandatory animation manifest"); + let names: Vec<_> = manifest.lines().collect(); + assert_eq!(names, ["basic", "loop", "once", "negative", "overflow", "draft", "limits", "matrix", "errors"]); + for name in names { for suffix in ["", "-optimized"] { + let bytes = std::fs::read(root.join(format!("pbs-animation-{name}{suffix}.pbx"))).expect("mandatory animation fixture"); + let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) + .unwrap_or_else(|e| panic!("animation/{name}{suffix}: load {e:?}")); + let mut vm = VirtualMachine::from_image(image.clone(), Default::default()); + vm.prepare_boot_call().unwrap(); + let mut watching = false; let mut started = 0; let mut ended = 0; let mut allocations = 0; let mut measured_steps=0; + for step in 0..2_000_000 { + let instruction = decode_next(vm.pc(), image.code()).unwrap(); + if instruction.opcode == Op::PushI32 { + if instruction.imm_i32().unwrap() == 162000001 { watching = true; started += 1; } + if instruction.imm_i32().unwrap() == 162000002 { watching = false; ended += 1; } + } + if watching { measured_steps+=1; } + if watching && matches!(instruction.opcode, Op::StructNew | Op::ArrayNew | Op::MakeClosure) { allocations += 1; } + let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None)) + .unwrap_or_else(|e| panic!("animation/{name}{suffix}: run {e:?}")); + if matches!(report.reason, End::Halted | End::EndOfRom) { break; } + assert!(matches!(report.reason, End::BudgetExhausted), "animation/{name}{suffix}: {report:?}"); + assert!(step < 1_999_999, "animation failed to terminate"); + } + assert_eq!(vm.operand_stack_top(2), vec![Value::Int32(42), Value::Int32(0)], "animation/{name}{suffix}"); + if !matches!(name, "basic" | "draft" | "limits" | "matrix") { assert_eq!((started, ended), (1, 1)); } + assert!(measured_steps<50000,"bounded frame traversal: {measured_steps}"); + assert_eq!(allocations, 0, "animation/{name}{suffix}: executed advance/sprite heap allocations"); + if name=="basic" { + use prometeu_vm::resource_budget::{RuntimeLimits,RuntimeResource}; + for resource in [RuntimeResource::GuestBytes,RuntimeResource::HandleSlots] { + let mut refused=VirtualMachine::from_image(image.clone(),RuntimeLimits::default().lowered(resource,0).unwrap()); + refused.prepare_boot_call().unwrap();let report=refused.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); + assert!(matches!(report.reason,End::Trap(ref fault) if fault.code==prometeu_bytecode::TRAP_RESOURCE_LIMIT)); + assert_eq!(refused.heap().len(),0);println!("ANIMATION QUOTA TRAP PASS {suffix} {resource:?}"); + } + } + println!("ANIMATION PASS {name}{suffix} watched={started} executed_allocations={allocations}"); + } } + verify_gc(root); + verify_installed(root); + verify_composer(root); +} + +fn verify_gc(root: &std::path::Path) { + for suffix in ["", "-optimized"] { + let bytes=std::fs::read(root.join(format!("pbs-animation-gc{suffix}.pbx"))).unwrap(); + let image=ValidatedProgramImage::load(&bytes,&mut LoadBudget::new(LoadLimits::default()),caps::NONE).unwrap(); + let mut vm=VirtualMachine::from_image(image.clone(),Default::default());vm.prepare_boot_call().unwrap(); + for round in 0..2 { + let report=vm.run_budget(30_000_000,&mut NoNative,&mut HostContext::new(None)).unwrap(); + assert!(matches!(report.reason,End::FrameSync),"animation GC: {report:?}"); + let objects=vm.heap().diagnostic_typed_storage(); + for name in ["Animator","_AnimationClip","_AnimationFrame"] { + let count=objects.iter().filter(|o|image.registry().declarations().types[o.type_id.0 as usize].name.as_deref()==Some(name)).count(); + if round==0 {assert!(count>0,"live animation root {name}");} else {assert_eq!(count,0,"unowned cycle {name}");} + } + assert!(vm.resource_snapshot().gc.reclaimed>1000); + println!("ANIMATION GC PASS {suffix} round={round} collections={} reclaimed={}",vm.resource_snapshot().gc.collections,vm.resource_snapshot().gc.reclaimed); + } + } +} + +fn verify_installed(root: &std::path::Path) { + use prometeu_drivers::TestPlatform; + use prometeu_firmware::firmware::Firmware; + use prometeu_hal::{InputSignals,app_mode::AppMode,cartridge::{Cartridge,AssetsPayloadSource}}; + for suffix in ["", "-optimized"] { + let name=format!("pbs-animation-installed{suffix}"); + let mut fw=Firmware::new(None);let mut platform=TestPlatform::new(); + fw.load_cartridge(Cartridge{app_id:84,title:"Studio animation".into(),app_version:"1.0.0".into(),app_mode:AppMode::Game,capabilities:caps::NONE,memcard_slots:None,program:std::fs::read(root.join(format!("{name}.pbx"))).unwrap(),assets:AssetsPayloadSource::empty(),asset_table:vec![],preload:vec![]}); + for _ in 0..5 {fw.tick(&InputSignals::default(),&mut platform);assert!(fw.os.vm().last_crash_report().is_none());} + let task=fw.os.lifecycle().resident_game_task().unwrap();let mut sessions=fw.os.sessions();let session=sessions.vm_session_for_task_mut(task).unwrap(); + let id=std::fs::read_to_string(root.join(format!("{name}.probe"))).unwrap();session.vm.prepare_call(id.trim()).unwrap(); + let report=session.vm.run_budget(100_000,&mut NoNative,&mut HostContext::new(None)).unwrap();assert!(matches!(report.reason,End::Halted|End::EndOfRom));assert_eq!(session.vm.operand_stack_top(1),vec![Value::Int32(42)]); + println!("ANIMATION INSTALLED GENERATED/FIRMWARE PASS {suffix}"); + } +} + +fn verify_composer(root: &std::path::Path) { + use prometeu_drivers::TestPlatform; + use prometeu_firmware::firmware::Firmware; + use prometeu_hal::{InputSignals,app_mode::AppMode,cartridge::{Cartridge,AssetsPayloadSource,AssetsPackPrelude}}; + for suffix in ["", "-optimized"] { + let prefix=format!("pbs-animation-composer{suffix}"); + let manifest:serde_json::Value=serde_json::from_slice(&std::fs::read(root.join(format!("{prefix}.manifest.json"))).unwrap()).unwrap(); + let oracle:serde_json::Value=serde_json::from_slice(&std::fs::read(root.join(format!("{prefix}.oracle.json"))).unwrap()).unwrap(); + let packed=std::fs::read(root.join(format!("{prefix}.assets.pa"))).unwrap();let prelude=AssetsPackPrelude::from_bytes(&packed).unwrap(); + let mut fw=Firmware::new(None);let mut platform=TestPlatform::new(); + fw.load_cartridge(Cartridge{app_id:84,title:"Studio animation Composer".into(),app_version:"1.0.0".into(),app_mode:AppMode::Game, + capabilities:caps::COMPOSER,memcard_slots:None, + program:std::fs::read(root.join(format!("{prefix}.pbx"))).unwrap(),assets:AssetsPayloadSource::from_bytes(packed[prelude.payload_offset as usize..].to_vec()), + asset_table:serde_json::from_value(manifest["asset_table"].clone()).unwrap(),preload:serde_json::from_value(manifest["preload"].clone()).unwrap()}); + let mut observed=0; + for _ in 0..50000 { + fw.tick(&InputSignals::default(),&mut platform); + assert!(fw.os.vm().last_crash_report().is_none(),"Composer {suffix}: {:?}",fw.os.vm().last_crash_report()); + if let Some(task)=fw.os.lifecycle().resident_game_task() { + let completed={let sessions=fw.os.sessions();sessions.vm_session_for_task(task).map(|s|s.runtime.atomic_telemetry.completed_logical_frames.load(std::sync::atomic::Ordering::Relaxed)).unwrap_or(0)}; + if completed>observed { + assert_eq!(completed,observed+1,"one native frame per observation"); + let sample=&oracle[observed as usize];let pixels=sample["rgba"].as_array().unwrap();let front=platform.local_hardware().gfx.front_buffer();let width=platform.local_hardware().gfx.size().0; + for x in [32,64] {for y in 0..16 {for dx in 0..16 {assert_eq!(front[(32+y)*width+x+dx],pixels[y*16+dx].as_u64().unwrap() as u32,"{prefix} tick={observed} x={x} pixel={dx},{y}");}}} + println!("ANIMATION COMPOSER PIXELS PASS {suffix} tick={observed} glyph={} palette={}",sample["glyph"],sample["palette"]); + observed=completed;if observed==8 {break;} + } + } + std::thread::yield_now(); + } + assert_eq!(observed,8,"native Composer did not produce all frames"); + } +} diff --git a/tools/pbx-conformance/main.rs b/tools/pbx-conformance/main.rs index 922cc325..a049e298 100644 --- a/tools/pbx-conformance/main.rs +++ b/tools/pbx-conformance/main.rs @@ -2,6 +2,8 @@ use prometeu_bytecode::Value; mod stack_queue; mod lifecycle; mod memcard; +mod result; +mod animation; use prometeu_bytecode::load_limits::{LoadBudget, LoadLimits}; use prometeu_hal::syscalls::caps; use prometeu_vm::{ @@ -44,6 +46,8 @@ fn main() { for resource in [Q::GuestBytes,Q::HandleSlots,Q::AuxiliaryBytes,Q::TemporaryBytes,Q::StringBytes,Q::StringAllocations,Q::IndividualStringBytes,Q::CallDepth] { println!("DEFAULT VM LIMIT {resource:?}={}",limits.get(resource)); } + if std::env::args().any(|arg| arg == "--animation-only") { animation::verify(&root); return; } + if std::env::args().any(|arg| arg == "--result-only") { result::verify(&root); return; } if std::env::args().any(|arg| arg == "--memcard-only") { memcard::verify(&root); return; } if std::env::args().any(|arg| arg == "--lifecycle-only") { lifecycle::verify(&root); return; } if std::env::args().any(|arg| arg == "--stack-queue-only") { stack_queue::verify(&root); return; } @@ -57,6 +61,8 @@ fn main() { if std::env::args().any(|arg| arg == "--random-only") { verify_pbs_random_fixtures(&root); return; } verify_pbs_math_fixtures(&root); if std::env::args().any(|arg| arg == "--math-only") { return; } + result::verify(&root); + animation::verify(&root); verify_pbs_random_fixtures(&root); verify_identity_hashing_fixtures(&root); verify_catalog_fixtures(&root); diff --git a/tools/pbx-conformance/result.rs b/tools/pbx-conformance/result.rs new file mode 100644 index 00000000..363539d4 --- /dev/null +++ b/tools/pbx-conformance/result.rs @@ -0,0 +1,56 @@ +//! PBS result groups execute on the unchanged production loader and VM. +use super::*; +use prometeu_vm::LogicalFrameEndingReason as End; +use prometeu_bytecode::{decode_next, isa::core::CoreOpCode as Op}; + +pub fn verify(root: &std::path::Path) { + let cases = [ + ("unit-ok", vec![Value::Int32(0)]), + ("unit-err", vec![Value::Int32(2)]), + ("scalar", vec![Value::Int32(0), Value::Int32(42)]), + ("error", vec![Value::Int32(1), Value::Int64(0)]), + ("tuple", vec![Value::Int32(0), Value::Int64(9_007_199_254_740_993), Value::Int32(42)]), + ("reference", vec![Value::Int32(2), Value::Null]), + ("propagate", vec![Value::Int32(2), Value::Int64(0), Value::Null]), + ("nested", vec![Value::Int32(2), Value::Int32(0)]), + ("recover", vec![Value::Int32(0), Value::Int32(42)]), + ("remap", vec![Value::Int32(2), Value::Int32(0)]), + ("success", vec![Value::Int32(0), Value::Int32(42)]), + ("trait", vec![Value::Int32(1), Value::Null, Value::Null]), + ("fn", vec![Value::Int32(1), Value::Null]), + ("once", vec![Value::Int32(0), Value::Int32(42)]), + ("block-remap", vec![Value::Int32(2), Value::Int32(0)]), + ("reference-ok", vec![Value::Int32(0), Value::Int32(42)]), + ("fn-ok", vec![Value::Int32(0), Value::Int32(42)]), + ("trait-ok", vec![Value::Int32(0), Value::Int32(42)]), + ("color-ok", vec![Value::Int32(0), Value::Int64(42)]), + ("color-err", vec![Value::Int32(1), Value::Int64(0)]), + ("trap", vec![]), + ]; + let manifest = std::fs::read_to_string(root.join("pbs-result-manifest.txt")).expect("mandatory result manifest"); + assert_eq!(manifest.lines().count(), cases.len() * 2); + for (name, expected) in cases { for suffix in ["", "-optimized"] { + let bytes = std::fs::read(root.join(format!("pbs-result-{name}{suffix}.pbx"))).expect("mandatory result fixture"); + let image = ValidatedProgramImage::load(&bytes, &mut LoadBudget::new(LoadLimits::default()), caps::NONE) + .unwrap_or_else(|e| panic!("result/{name}{suffix}: load {e:?}")); + let mut vm = VirtualMachine::from_image(image.clone(), Default::default()); + vm.prepare_boot_call().unwrap(); + let mut allocations = 0; + let mut trapped=false; + for step in 0..100_000 { + let instruction = decode_next(vm.pc(), image.code()).unwrap(); + if matches!(instruction.opcode, Op::StructNew | Op::ArrayNew | Op::MakeClosure) { allocations += 1; } + let report = vm.run_budget(1, &mut NoNative, &mut HostContext::new(None)) + .unwrap_or_else(|e| panic!("result/{name}{suffix}: run {e:?}")); + if matches!(report.reason, End::Trap(_)) && name=="trap" { trapped=true;break; } + if matches!(report.reason, End::Halted | End::EndOfRom) { break; } + assert!(matches!(report.reason, End::BudgetExhausted), "result/{name}{suffix}: {report:?}"); + assert!(step < 99_999, "result failed to terminate"); + } + if name=="trap" { assert!(trapped,"handle must not recover a VM trap");println!("RESULT TRAP PASS {suffix}");continue; } + assert_eq!(vm.operand_stack_top(expected.len()).iter().rev().cloned().collect::>(), expected, "result/{name}{suffix}"); + if matches!(name,"reference-ok"|"fn-ok"|"trait-ok") { assert!(allocations>0,"successful payload is constructed"); } + else { assert_eq!(allocations, 0, "result/{name}{suffix}: no holder or inactive payload allocations"); } + println!("RESULT PASS {name}{suffix} group={expected:?} executed_allocations={allocations}"); + } } +} diff --git a/tools/pbx-conformance/run.py b/tools/pbx-conformance/run.py index bef259a6..75b8d06d 100644 --- a/tools/pbx-conformance/run.py +++ b/tools/pbx-conformance/run.py @@ -11,6 +11,8 @@ parser = argparse.ArgumentParser() parser.add_argument("--runtime", type=pathlib.Path, default=pathlib.Path("../runtime")) parser.add_argument("--fixtures", type=pathlib.Path, default=pathlib.Path("prometeu-compiler/prometeu-build-pipeline/build/registry-conformance")) parser.add_argument("--online", action="store_true", help="Allow Cargo to fetch uncached dependencies") +parser.add_argument("--animation-only", action="store_true", help="Run mandatory PBS core animation corpus") +parser.add_argument("--result-only", action="store_true", help="Run mandatory PBS result return-group corpus") parser.add_argument("--memcard-only", action="store_true", help="Run PBS memcard through production Firmware/SystemOS (native, not installed process)") parser.add_argument("--lifecycle-only", action="store_true", help="Run PBS guest lifecycle VM and production firmware corpus") parser.add_argument("--release", action="store_true", help="Execute an optimized runtime harness") @@ -71,6 +73,8 @@ with tempfile.TemporaryDirectory(prefix="pbx-conformance-") as directory: (root / "src").mkdir() (root / "src/main.rs").write_text(pathlib.Path(__file__).with_name("main.rs").read_text()) (root / "src/stack_queue.rs").write_text(pathlib.Path(__file__).with_name("stack_queue.rs").read_text()) + (root / "src/animation.rs").write_text(pathlib.Path(__file__).with_name("animation.rs").read_text()) + (root / "src/result.rs").write_text(pathlib.Path(__file__).with_name("result.rs").read_text()) (root / "src/memcard.rs").write_text(pathlib.Path(__file__).with_name("memcard.rs").read_text()) (root / "src/lifecycle.rs").write_text(pathlib.Path(__file__).with_name("lifecycle.rs").read_text()) - subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--memcard-only"] if args.memcard_only else []), *(["--lifecycle-only"] if args.lifecycle_only else []), *(["--stack-queue-only"] if args.stack_queue_only else []), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True) + subprocess.run(["cargo", "run", *(["--release"] if args.release else []), *([] if args.online else ["--offline"]), "--manifest-path", str(root / "Cargo.toml"), "--", str(args.fixtures.resolve()), str(runtime / "devtools/headless-protocol/response.schema.json"), *(["--animation-only"] if args.animation_only else []), *(["--result-only"] if args.result_only else []), *(["--memcard-only"] if args.memcard_only else []), *(["--lifecycle-only"] if args.lifecycle_only else []), *(["--stack-queue-only"] if args.stack_queue_only else []), *(["--map-only"] if args.map_only else []), *(["--set-only"] if args.set_only else []), *(["--identity-hashing-only"] if args.identity_hashing_only else []), *(["--math-only"] if args.math_only else []), *(["--random-only"] if args.random_only else []), *(["--generic-contracts-only"] if args.generic_contracts_only else []), *(["--generic-structs-only"] if args.generic_structs_only else []), *(["--list-cursor-only"] if args.list_cursor_only else []), *(["--linked-only"] if args.linked_only else [])], check=True) diff --git a/tools/vscode-extension/out/extension.js b/tools/vscode-extension/out/extension.js index a221ffcd..9789160c 100644 --- a/tools/vscode-extension/out/extension.js +++ b/tools/vscode-extension/out/extension.js @@ -52,7 +52,16 @@ function activate(context) { reconnectContext = context; output = vscode.window.createOutputChannel("Prometeu LSP"); output.appendLine("Prometeu VS Code extension activated."); - context.subscriptions.push(externalSources, vscode.workspace.registerTextDocumentContentProvider(externalSources_1.externalScheme, externalSources), vscode.window.onDidChangeActiveTextEditor(() => externalSources.refreshStatus()), vscode.workspace.onDidOpenTextDocument(document => void externalSources.opened(document)), vscode.workspace.onDidCloseTextDocument(document => void externalSources.closeDocument(document))); + context.subscriptions.push(externalSources, vscode.languages.registerCodeLensProvider({ scheme: externalSources_1.externalScheme, language: "pbs" }, { + provideCodeLenses: document => externalSources.originLenses(document) + }), vscode.commands.registerCommand("prometeu.openAnimationOrigin", async (uri, byteOffset) => { + try { + await externalSources.openAnimationOrigin(uri, byteOffset); + } + catch (error) { + void vscode.window.showErrorMessage(String(error)); + } + }), vscode.workspace.registerTextDocumentContentProvider(externalSources_1.externalScheme, externalSources), vscode.window.onDidChangeActiveTextEditor(() => externalSources.refreshStatus()), vscode.workspace.onDidOpenTextDocument(document => void externalSources.opened(document)), vscode.workspace.onDidCloseTextDocument(document => void externalSources.closeDocument(document))); const connectCommand = vscode.commands.registerCommand("prometeu.connectStudioLsp", async () => { await startClient(context); }); diff --git a/tools/vscode-extension/out/externalSources.js b/tools/vscode-extension/out/externalSources.js index b6222897..f7d27eea 100644 --- a/tools/vscode-extension/out/externalSources.js +++ b/tools/vscode-extension/out/externalSources.js @@ -108,6 +108,25 @@ class ExternalSources { this.refreshStatus(); return content.text; } + originLenses(document) { + if (!this.canQuery(document)) + return []; + const content = this.documents.get(document.uri.toString()); + return (content?.descriptor.origins ?? []).map(origin => { + const offset = Buffer.from(document.getText(), "utf8").subarray(0, origin.startOffset).toString("utf8").length; + const position = document.positionAt(offset); + return new vscode.CodeLens(new vscode.Range(position, position), { + title: "Open animation definition in Studio", command: "prometeu.openAnimationOrigin", + arguments: [document.uri, origin.startOffset] + }); + }); + } + async openAnimationOrigin(uri, byteOffset) { + const document = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString()); + if (!document || !this.canQuery(document) || !this.client || !this.consumerId) + throw new Error("Animation source unavailable: navigate again to obtain the current revision."); + await this.client.sendRequest("prometeu/openAnimationOrigin", { consumerId: this.consumerId, uri: uri.toString(), offset: byteOffset }); + } async opened(document) { if (document.uri.scheme !== exports.externalScheme) return; diff --git a/tools/vscode-extension/package.json b/tools/vscode-extension/package.json index 823a02a4..357c4573 100644 --- a/tools/vscode-extension/package.json +++ b/tools/vscode-extension/package.json @@ -36,6 +36,10 @@ { "command": "prometeu.restartStudioLsp", "title": "Prometeu: Restart Studio LSP" + }, + { + "command": "prometeu.openAnimationOrigin", + "title": "Prometeu: Open Animation Definition in Studio" } ], "configuration": { diff --git a/tools/vscode-extension/src/extension.ts b/tools/vscode-extension/src/extension.ts index 4ead4bed..f09b347d 100644 --- a/tools/vscode-extension/src/extension.ts +++ b/tools/vscode-extension/src/extension.ts @@ -79,6 +79,13 @@ export function activate(context: vscode.ExtensionContext): void { output = vscode.window.createOutputChannel("Prometeu LSP"); output.appendLine("Prometeu VS Code extension activated."); context.subscriptions.push(externalSources, + vscode.languages.registerCodeLensProvider({ scheme: externalScheme, language: "pbs" }, { + provideCodeLenses: document => externalSources.originLenses(document) + }), + vscode.commands.registerCommand("prometeu.openAnimationOrigin", async (uri: vscode.Uri, byteOffset: number) => { + try { await externalSources.openAnimationOrigin(uri, byteOffset); } + catch (error) { void vscode.window.showErrorMessage(String(error)); } + }), vscode.workspace.registerTextDocumentContentProvider(externalScheme, externalSources), vscode.window.onDidChangeActiveTextEditor(() => externalSources.refreshStatus()), vscode.workspace.onDidOpenTextDocument(document => void externalSources.opened(document)), diff --git a/tools/vscode-extension/src/externalSources.ts b/tools/vscode-extension/src/externalSources.ts index 319bab23..ffc4bf6a 100644 --- a/tools/vscode-extension/src/externalSources.ts +++ b/tools/vscode-extension/src/externalSources.ts @@ -3,7 +3,7 @@ import { LanguageClient } from "vscode-languageclient/node"; export const externalScheme = "prometeu-source"; export type ExternalContent = { - descriptor: { uri: string; revision: string; origin: string; name: string; languageId: string; readOnly: true }; + descriptor: { uri: string; revision: string; origin: string; name: string; languageId: string; readOnly: true; origins?: { startOffset: number; endOffset: number; definitionPath: string; jsonPointer: string; assetUuid: string }[] }; text: string; }; @@ -74,6 +74,27 @@ export class ExternalSources implements vscode.TextDocumentContentProvider, vsco return content.text; } + originLenses(document: vscode.TextDocument): vscode.CodeLens[] { + if (!this.canQuery(document)) return []; + const content = this.documents.get(document.uri.toString()); + return (content?.descriptor.origins ?? []).map(origin => { + const offset = Buffer.from(document.getText(), "utf8").subarray(0, origin.startOffset).toString("utf8").length; + const position = document.positionAt(offset); + return new vscode.CodeLens(new vscode.Range(position, position), { + title: "Open animation definition in Studio", command: "prometeu.openAnimationOrigin", + arguments: [document.uri, origin.startOffset] + }); + }); + } + + async openAnimationOrigin(uri: vscode.Uri, byteOffset: number): Promise { + const document = vscode.workspace.textDocuments.find(doc => doc.uri.toString() === uri.toString()); + if (!document || !this.canQuery(document) || !this.client || !this.consumerId) + throw new Error("Animation source unavailable: navigate again to obtain the current revision."); + await this.client.sendRequest("prometeu/openAnimationOrigin", + { consumerId: this.consumerId, uri: uri.toString(), offset: byteOffset }); + } + async opened(document: vscode.TextDocument): Promise { if (document.uri.scheme !== externalScheme) return; const content = this.documents.get(document.uri.toString());