From bf31184d4d173a62c07999bef7a3ce583ea12a68 Mon Sep 17 00:00:00 2001 From: bQUARKz Date: Thu, 5 Nov 2026 15:16:07 +0000 Subject: [PATCH] feat(pbs): add sprite animation and shared Studio authoring Implement DEC-0084 with factory-only Sprite/Animator structs, complete result lowering, validated animation sidecars, generated PBS factories and JavaFX/MCP authoring through shared services. Qualify native dev/release with ordinary and optimized producers, zero-allocation playback, private-cycle reclamation, canonical Composer pixels, installed JARs and JavaFX lifecycle. Preserve the runtime checkout and existing host ABI. --- ...0-sprite-animation-and-shared-authoring.md | 211 ++++ .../evidence/README.md | 31 + .../evidence/SHA256SUMS | 21 + .../evidence/acceptance.md | 26 + .../evidence/animation-authoring.xml.gz | Bin 0 -> 1723 bytes .../evidence/animation-editor.png | Bin 0 -> 55242 bytes .../evidence/animation-native-dev.log.gz | Bin 0 -> 2282 bytes .../evidence/animation-native-release.log.gz | Bin 0 -> 2272 bytes .../evidence/animation-ui.xml.gz | Bin 0 -> 425 bytes .../evidence/authoring-final.log.gz | Bin 0 -> 747 bytes .../composer-installed-process.log.gz | Bin 0 -> 1066 bytes .../composer-installed-process.xml.gz | Bin 0 -> 555 bytes .../evidence/environment.json | 33 + .../evidence/fixtures.sha256.gz | Bin 0 -> 2648 bytes .../evidence/fn-effect-rejection.log.gz | Bin 0 -> 778 bytes .../evidence/installed-knowledge.xml.gz | Bin 0 -> 368 bytes .../evidence/regression.log.gz | Bin 0 -> 1538 bytes .../evidence/result-native-dev.log.gz | Bin 0 -> 2282 bytes .../evidence/result-native-release.log.gz | Bin 0 -> 2272 bytes .../evidence/results.json | 134 +++ .../evidence/source.sha256 | 129 +++ .../evidence/workflow.txt | 18 + .../10. Memory and Lifetime Specification.md | 7 + .../13. Lowering IRBackend Specification.md | 7 + ...Core Sprite and Animation Specification.md | 180 ++++ .../pbs/3. Core Syntax Specification.md | 7 + .../pbs/4. Static Semantics Specification.md | 7 + ...tdlib, and SDK Resolution Specification.md | 7 + ...ent Packaging and Loading Specification.md | 7 + .../pbs/9. Dynamic Semantics Specification.md | 7 + docs/specs/compiler-languages/pbs/README.md | 2 + ... Standard Library Surface Specification.md | 7 + ...RBackend to IRVM Lowering Specification.md | 7 + ...Typed Registry and PBX v0 Specification.md | 7 + ...istry, and Asset Identity Specification.md | 7 + ...nd Virtual Asset Contract Specification.md | 7 + ...and Deterministic Packing Specification.md | 7 + ...CP Tools and Project Knowledge Contract.md | 7 + .../12. Animation Authoring Specification.md | 142 +++ .../4. Assets Workspace Specification.md | 7 + ... and Adapter Architecture Specification.md | 7 + docs/specs/studio/README.md | 2 + prometeu-animation/build.gradle.kts | 2 + .../main/java/p/animation/AnimationCodec.java | 75 ++ .../java/p/animation/AnimationDiagnostic.java | 2 + .../java/p/animation/AnimationDocument.java | 24 + .../animation/AnimationOriginNavigation.java | 6 + .../java/p/animation/AnimationRebind.java | 28 + .../java/p/animation/AnimationRevision.java | 12 + .../java/p/animation/AnimationSource.java | 8 + .../java/p/animation/AnimationTimeline.java | 50 + .../java/p/animation/AnimationValidator.java | 57 ++ .../java/p/animation/GlyphBankLayout.java | 18 + .../p/animation/GlyphBankLayoutSource.java | 11 + .../p/animation/AnimationContractTest.java | 40 + prometeu-app/build.gradle.kts | 15 +- .../app/StudioApplicationConfiguration.java | 41 +- .../java/p/studio/app/StudioUiFactory.java | 7 +- .../app/assets/PackerGlyphBankLayouts.java | 22 + .../compiler/CompilerBuildGatewayAdapter.java | 6 +- .../compiler/CompilerProjectKnowledge.java | 6 +- .../java/p/studio/app/mcp/ContractSchema.java | 3 + .../p/studio/app/mcp/McpAnimationTools.java | 39 + .../main/resources/mcp/studio-tools-v1.json | 939 ++++++++++++++++++ .../StudioApplicationConfigurationTest.java | 2 +- .../app/animation/AnimationDesktopTest.java | 54 + .../animation/AnimationInstalledProbe.java | 55 + .../AnimationInstalledRuntimeTest.java | 96 ++ .../animation/AnimationIntegrationTest.java | 197 ++++ .../animation/AnimationProjectFixture.java | 47 + .../app/compiler/InstalledKnowledgeProbe.java | 7 +- .../app/compiler/InstalledKnowledgeTest.java | 2 + .../p/studio/app/mcp/McpContractTest.java | 2 +- .../app/mcp/stdio/StudioMcpStdioTest.java | 2 +- .../architecture/StudioBoundaryArchTest.java | 9 +- .../compiler/backend/irvm/PbsResultTest.java | 57 ++ .../backend/irvm/PbsRuntimeAlignmentTest.java | 5 +- .../backend/irvm/PbsSpriteAnimationTest.java | 269 +++++ .../compiler/PBSFrontendLanguageService.java | 13 +- .../compiler/pbs/PbsCallableSlotCounter.java | 2 +- .../compiler/pbs/PbsStdlibConstruction.java | 19 + .../p/studio/compiler/pbs/ast/PbsAst.java | 4 +- .../compiler/pbs/ast/PbsAstRewriter.java | 2 +- .../lowering/PbsExecutableBodyLowerer.java | 158 ++- .../PbsExecutableLoweringContext.java | 19 +- .../PbsExecutableLoweringService.java | 8 +- .../lowering/PbsExecutableStackAnalyzer.java | 27 +- .../pbs/lowering/PbsRuntimeTypes.java | 31 +- .../pbs/parser/PbsDeclarationParser.java | 2 +- .../semantics/PbsEditorialSupportService.java | 1 + .../pbs/semantics/PbsFlowSemanticSupport.java | 4 + .../PbsFlowStructuralExpressionAnalyzer.java | 7 + .../services/PbsAnimationProjection.java | 52 + .../PbsImportedSemanticContextService.java | 33 +- .../services/PbsModuleAssemblyService.java | 35 + .../game/stdlib/1/core/animation/main.pbs | 199 ++++ .../game/stdlib/1/core/animation/mod.barrel | 6 + .../game/stdlib/1/core/sprite/main.pbs | 24 + .../game/stdlib/1/core/sprite/mod.barrel | 4 + .../game/stdlib/1/sdk/composer/main.pbs | 12 +- .../examples/game/1/ANIMATION.md | 45 + .../examples/game/1/src/animation.pbs | 25 + .../prometeu-build-pipeline/build.gradle.kts | 1 + .../models/BuilderPipelineContext.java | 1 + .../workspaces/AssetSurfaceContextLoader.java | 27 +- .../stages/FrontendPhasePipelineStage.java | 13 +- .../prometeu-frontend-api/build.gradle.kts | 1 + .../compiler/messages/FESurfaceContext.java | 5 +- .../services/FrontendSourceDocument.java | 11 +- .../lsp/services/LspServerLifecycleImpl.java | 7 +- .../CompilerLanguageServiceBridge.java | 25 +- .../compiler/ExternalSourceRegistry.java | 13 +- .../ExternalSourceLanguageServer.java | 2 + .../protocol/PrometeuLanguageServer.java | 5 + .../compiler/ExternalSourceRegistryTest.java | 12 + .../java/p/packer/PackerWorkspaceService.java | 8 + .../packer/dtos/PackerGlyphBankLayoutDTO.java | 13 + .../messages/GetGlyphBankLayoutRequest.java | 6 + .../PackerAbstractBankWalker.java | 3 +- .../FileSystemPackerWorkspaceService.java | 50 + prometeu-studio-api/build.gradle.kts | 2 + .../p/studio/api/assets/AssetSummary.java | 5 +- .../assets/animation/AnimationService.java | 26 + .../api/assets/animation/AnimationTasks.java | 8 + .../workspace/AssetWorkspaceAssetSummary.java | 5 +- .../api/automation/AutomationFailure.java | 2 +- .../core/assets/AnimationOperations.java | 10 + .../core/assets/PackerAssetCatalog.java | 2 +- .../core/assets/PackerAssetDetails.java | 2 +- .../animation/AnimationPreviewRenderer.java | 29 + .../animation/DefaultAnimationService.java | 111 +++ .../animation/ManualAnimationService.java | 17 + .../core/session/TaskAnimationService.java | 43 + .../StudioAnimationOriginRequestedEvent.java | 4 + .../p/studio/ui/javafx/window/MainView.java | 8 + .../window/StudioWindowCoordinator.java | 3 + .../workspaces/assets/AssetWorkspace.java | 3 + .../assets/details/AssetDetailsControl.java | 32 +- .../assets/details/AssetListMappings.java | 2 +- .../animation/AnimationEditorControl.java | 127 +++ settings.gradle.kts | 1 + tools/pbx-conformance/README.md | 38 + tools/pbx-conformance/animation.rs | 118 +++ tools/pbx-conformance/main.rs | 6 + tools/pbx-conformance/result.rs | 56 ++ tools/pbx-conformance/run.py | 6 +- tools/vscode-extension/out/extension.js | 11 +- tools/vscode-extension/out/externalSources.js | 19 + tools/vscode-extension/package.json | 4 + tools/vscode-extension/src/extension.ts | 7 + tools/vscode-extension/src/externalSources.ts | 23 +- 151 files changed, 4823 insertions(+), 98 deletions(-) create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/LSN-0100-sprite-animation-and-shared-authoring.md create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/README.md create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/SHA256SUMS create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/acceptance.md create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-authoring.xml.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-editor.png create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-native-dev.log.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-native-release.log.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/animation-ui.xml.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/authoring-final.log.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/composer-installed-process.log.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/composer-installed-process.xml.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/environment.json create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/fixtures.sha256.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/fn-effect-rejection.log.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/installed-knowledge.xml.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/regression.log.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/result-native-dev.log.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/result-native-release.log.gz create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/results.json create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/source.sha256 create mode 100644 discussion/lessons/DSC-0098-pbs-core-sprite-animation/evidence/workflow.txt create mode 100644 docs/specs/compiler-languages/pbs/27. Core Sprite and Animation Specification.md create mode 100644 docs/specs/studio/12. Animation Authoring Specification.md create mode 100644 prometeu-animation/build.gradle.kts create mode 100644 prometeu-animation/src/main/java/p/animation/AnimationCodec.java create mode 100644 prometeu-animation/src/main/java/p/animation/AnimationDiagnostic.java create mode 100644 prometeu-animation/src/main/java/p/animation/AnimationDocument.java create mode 100644 prometeu-animation/src/main/java/p/animation/AnimationOriginNavigation.java create mode 100644 prometeu-animation/src/main/java/p/animation/AnimationRebind.java create mode 100644 prometeu-animation/src/main/java/p/animation/AnimationRevision.java create mode 100644 prometeu-animation/src/main/java/p/animation/AnimationSource.java create mode 100644 prometeu-animation/src/main/java/p/animation/AnimationTimeline.java create mode 100644 prometeu-animation/src/main/java/p/animation/AnimationValidator.java create mode 100644 prometeu-animation/src/main/java/p/animation/GlyphBankLayout.java create mode 100644 prometeu-animation/src/main/java/p/animation/GlyphBankLayoutSource.java create mode 100644 prometeu-animation/src/test/java/p/animation/AnimationContractTest.java create mode 100644 prometeu-app/src/main/java/p/studio/app/assets/PackerGlyphBankLayouts.java create mode 100644 prometeu-app/src/main/java/p/studio/app/mcp/McpAnimationTools.java create mode 100644 prometeu-app/src/test/java/p/studio/app/animation/AnimationDesktopTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledProbe.java create mode 100644 prometeu-app/src/test/java/p/studio/app/animation/AnimationInstalledRuntimeTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/animation/AnimationIntegrationTest.java create mode 100644 prometeu-app/src/test/java/p/studio/app/animation/AnimationProjectFixture.java create mode 100644 prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsResultTest.java create mode 100644 prometeu-architecture-tests/src/test/java/p/studio/compiler/backend/irvm/PbsSpriteAnimationTest.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsStdlibConstruction.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsAnimationProjection.java create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/main.pbs create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/animation/mod.barrel create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/main.pbs create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/game/stdlib/1/core/sprite/mod.barrel create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/ANIMATION.md create mode 100644 prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/resources/pbs-knowledge/examples/game/1/src/animation.pbs create mode 100644 prometeu-packer/prometeu-packer-api/src/main/java/p/packer/dtos/PackerGlyphBankLayoutDTO.java create mode 100644 prometeu-packer/prometeu-packer-api/src/main/java/p/packer/messages/GetGlyphBankLayoutRequest.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationService.java create mode 100644 prometeu-studio-api/src/main/java/p/studio/api/assets/animation/AnimationTasks.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/assets/AnimationOperations.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/assets/animation/AnimationPreviewRenderer.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/assets/animation/DefaultAnimationService.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/assets/animation/ManualAnimationService.java create mode 100644 prometeu-studio-core/src/main/java/p/studio/core/session/TaskAnimationService.java create mode 100644 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/events/StudioAnimationOriginRequestedEvent.java create mode 100644 prometeu-studio-ui-javafx/src/main/java/p/studio/ui/javafx/workspaces/assets/details/animation/AnimationEditorControl.java create mode 100644 tools/pbx-conformance/animation.rs create mode 100644 tools/pbx-conformance/result.rs 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 0000000000000000000000000000000000000000..608810bec98435c385d8c4c71e003b48add266a6 GIT binary patch literal 1723 zcmV;s21NNEiwFP!00002|Lt09Zz9JM{m!rG@MUd@$GpG{G0yT_kzlZR>?*MkX=V!C z>z?V^?jGAD%70JwuwasSSG$gNwf9~uSO{?^sT?Xxl}rGPT{h>(@QI zRIw|+l1iHm^ptrL8{C+XBZfj>NfD+2Of==tqk$F@y`7xqNx-R6&y7t6 z)GGO&n|~6Srs{So1Xq(ADxo8SG=f;GD+zZD?h$YIfhmnCYo_`JA?eLaL2^9%X-I2` z0Uv;HB-xt9Y7Flo&{%KcF9qn#I(r%r?z7@7(5fTZN@p=i@Sf>0 zELj|4tQ5#QXwz844C|w{(Jz-d+pay0O3}N+B5I|KhpIUS%HQk)xGkd%BK`>=Q7slz zyi*Fan#I8ljn@#q6i&}_p2nH#RSj#~ZqM}Ik#rb#F?M`#ryuR)ad!sqI?sTsv^EwG3fjC4B-H<>;3C9?QM5RFhO081P zHzb!s+t%#OoP3Npxh4pS%!v}I41jP!jsBKOr32e{l;7gw&PEDho+~Gk-C-=scT|>F zf`_Q&WlNX!N__}y?|tQdxxVplJmrNOeZREK&-z1oT7I8mMHXw8U-7Lo-|-#K_3Vme zmz4|<3GUk+kCD|%3Jgme&dEu4(H!l4Qifru+iBP0V4#f|tz!OCaf?6*%Sux;Ymh>E<$ZnERt&?%L z(`-+>9dh#PL}Lj=*gs(pO979LQh(SU%sSo0WHcMMyNmvCF&MQokiU|UDT@1qr{5FK zV)SGeFeyBZ;yQ6MlH1%ZOb@EfBSd^$nnK z^!BS(fvmY$Ql4GH0|coy`FXT(`~r#agynFB$6dq2bYX8Bn+aRTS;DtQxUIxfhXt7( zrqv7sD4iyhnRk;?EVbz-fy4VY?xM2=2_I4>jd&z<$v87(fm!El1;HlZ&Rg z4UDNSDu`%|7YgO#-D1+cT=d@zN7%oMx6Q!}<>Ikm3u;Q#!R)a#_bj)f^W6l9Dw z-%47doMW-_V4D$Zv)o46jOn$y>jRuR^aNM1Y25-Baf588gq2VyuL`%WRs{;OqHJ>hnN2(4|^$U)*qw3WC zqGSEv%@kF~ue!ElSvBAHy^2%yE60)ID@KZcF$UPyS;4NH{e29e9987mbAapHe|PvB z=x6$KeYb#rum3L$7PeC<*q-$$Y`9Rwh50uK)w8fJss~U#tB4E78R#g4M` zc_Ez7FV4#c?-~zYJ%W@6uO7{NN^&pcEyy`ByO8}$PU9SD%aZvT%MksSI(tQ(;Be1S z{EA<$wz;p}t+nNQ^^xx5mR}f%+>zdq-jUvs-Zwz+7|$cUBfVohztMOe4vc0(%$=9_ R|FLtC`xB^oItt|@007o6VFv&J literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..728db615e47bbeaedcc73ee441d2744773d73c13 GIT binary patch literal 55242 zcmeFZby$^e+a*kQib{uqAWDOD3Ic+Fl%O<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(8np_<=rD!BjPPj06RxSgy*{uu5uCy(%`c+5tmI(2M^ z1k{?&XSPl5;UL6)Mid}_Dzg<<1Fw}+)8&Ok}% zbvIfYc-#H0Lm_sahN&q+Ii|oL8pJ4~{>fxJ(iX`t{v6Vv;x##W*2I6VA``44{dwbB zy7)k)Tm(lP4*eHv0;(<~(zdfaBO}EWI&kg;U1|Yc+}=WkXwuQVI=S{$GR~!5t~K40 z5bDyyR-X`AK;((N2Ed--h-dWUdX=JoYp6)glhLy(q7)E0yXSX_aNHB6Dw?In*87IQ zOd!4X(`M)uqc>{#1%B=65d=M|L1o^bPzC#l>-+tM3=D2{sd;AqQ(d)zNd^IjbxbIf z(bNc(DU@F)_+gZbiu-<0MWrNbWrxGgeu(!-(*V`Cl>NM)kC*CyY)h?`&fVfq(w(JS z$JwN+Y>NW_xCQ9mP$`mGpmWSr;#pI(pl+cQ^xsplA^W9_pGm0P0nY#cY~&aSMw$Z6 zX|i0T58rFXpZ9n920--Sf>9l;U9nPKGpq(D}C7L ze{3mWlLE^jDsMM?{15HBfbjtt3CmC^)23bQtJg)-98O;02DgH&*Qy%;YS#c%&)OTn zXkeeZiRqEIJp1I0yD!Pb{s7(1nm0c~b~6AVtFVt0Q%6hX_S+r%pmW7$046=Q|E*2` wFUCMu%$%;+R!FvEPkszb?Nqh0gZ(}r2qf` literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..7fe6621072446a18be61b414508d7ee9cad24981 GIT binary patch literal 2282 zcmV*`ad4!c!9#DdSfoAKf&X1j-161tY;}l%Y{i0viCk( zEi_9$QKKaLktHvnYGz$uXdVKFK)1rI3t1&6r9t76)TpF`0Ln*Y6Oxh4IV7!}_Vf*o zMJ2_LteIlQkMDk8;R?sngEUb_$GNpaNGdsUX^b^mi5w7()d@8yB^-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0+z7Babf$l6}K`AL{xQ zE{97xvrv=0~!&aRy$qXG28qWps!-_2?n~o z^pX|$8RKfe^bU58#l91KdOLRaDrU$2|CP04`hWsA{&m|fZ=Co8oW7CszV7Wfc#m;< zLe2&+Hazuc$ETckja{zWPmgwdLhjT-9v+N}jn`99wUJ$qbbCTxV$!bq{7APaO>1j{JU(;)^4HXhwO*@tzsgV>9Y6j^d#i z&11W2AKuj+=sosEzYf8lUd1DB`RfpmxbLq+sHa!)2n>83!aV&(zJ-hb0R^&$?$jFq E02kkTkN^Mx literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..ffc248065b60e6d0838c9146a8558e07c33d12d0 GIT binary patch literal 2272 zcmV<62p{(!iwFP!00002|Gih+a@$4{eb-muF?k>{_lv9ipvX#=Rk}D5y}MOgTXxS( zkAxTm7yy*5eEl{^T^P&pN>pS&kTTepGd54u%9#DY(~oATlZ_-ZTo z-eubluL^)JUK%xl<+4UH>ONJ?UWYY8Pv#qRdq+qAJT9)V>#Me*7-Gt&Zm+)tp-oY~ z>*#DzQPm6`E~`{7yLN#CuF8H`rK&B5 zwypbe89q-aRBpQkG!e^g)l8Syh45gEkVypKIm;xG2gbMskt1g@1nXJK(Q;uDgzUYK zRtwFNPgE$$z9-}bRL!*O3(Z5o5a?Ezbs?+dq%$KCP0|LHkVHe#c*2NGNF_5U4VuMd(*uxqsdLvh1Lf}T zDmS@(G+BlX^l_@n4*Pc1MeNH9Sd3kp>ME4H?9<1woSV@jkAm7aYa0MvQrs)ArH(OY z&9W8*$I*C6Yl$wCRa)7glZF(~F+ojl5MH97zpTjk=(bz8>zX|cPM~WiL^e1r_?jjJ zSQ{bn41r@(^eH5DiZhuDVO5rhDZI?(pO1X->qrOpIB8ZCqw495Ch#O9m6kXl0%(jW z0d;V|9BH6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L6Gb#<_A#MZ*VzW(wT+Y z+dr8d@6TtaC&jPtPUri@{A~Yi@pk|Gyx6MZx2(3RxMjBfEkIwz;u8#Xd+9YR@H58M zfayJK9gBS<_~dTb9tUR2{{O++GJOKTwSV2V%R49j1gEd$e5`vr4&E+K&&b)}#hR&h zc6`oxudvH?`)Oy#XXH*DQyJO}D5gv_UHpv*Um5pB-*uKgswW$d=o|>G9js^TV^^?d;!&N9Q-iBIW;) zPI^&aFE8nP2{jG_{^>%#;m992^2a%f8%O@sjPilwBQvU9GwK^h@zjiF*Q(m5S9PoP ucD>OrL-6OL*x{DH46(y~e;GnOAH@zm@MQ?|{2TdNU;Gb0HdW&n4HwpO(Mm0R6yU4Z=^W|F8@r1%20b~7GoUAFEjAU4-|U4{!6Eev zI%nK4dZ{B`Xj`!&D`sh)r`dFuj~7M0C^9~t%zrX?G~@>-x9h8Py}7!*oMb;{6Ru1x z)F2Z1d@`Q0WdcxIXDm7|kw*P~@Kg(W%_D+;j0Uz2JBiQqRdh(#XoYmNYMV1<2b2b>D-{euJCirFf=I-o#wOifY-!IG2(Zdlg7W5CdF&$*n_i*S3 z@}U^m@-G}}qdA3^{}P?pzZ|S7Sr5jxO8C8T`a)X;v0&$eO}?$JHy4}F3%F@1SZkce z1}-Cc{XJ^6d-)JtPhSktk>D8}f-<6s$h|WfPC|QVqycT3pb$RIru7F=OpBA`IM5+M TQjY#!(lYr2{3BR=eF6XgUjfD> literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..901274664f48e2caf4c89c9efbfcb9f02b52ffd3 GIT binary patch literal 747 zcmV1#LIGryLBMcVi(okqCb!FJoep~~ zG0_VNgue)yKok;5g)U@@pX~}IuY`^gPPXlYH^*nzyd?yb;?hl|!i=!c?*gCoTRx=| z=&jz~LI}=NstpCT)KwW1eIn%%*uj~hzH@0dJ6l-+}UlL-fw0!NM z6@lnuCI8q3f(kJ0#=X{w5|tNT6|RwYANp=?4+SiQ7uKc0RmEM}#nHqPl+KK_uAYJ1 z9cY6d7cS2AAD>QGb}WZj1=7|5PkNe;N=AFXejSC9UK*1%H2|qcl2~@r(XN8 z-i+Pt9Z5Ei)^_6M+1{KSGFV0YGgVI`pZ#Gy**XQPYWU~LPmF#sibJQ9`<&`;x^k5F zGhdwwI)$i6^ayh}|1Xs2I8XG8b$w%dS%^A>u?0G=gp8Th)}cPPK}HQ?~&!&=Q4|C>M*!)27aou1Zfi%)B?iCHh} zgUCFI!9SxMC}C?8003<6Y0Cfr literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..18cc708724b377c11e28cf5175306e3f853a0e09 GIT binary patch literal 1066 zcmV+_1l9W=iwFP!00002|Fu|4a^p4--SZT^bEax2&Ny~uN{dw4k}~Cy6RSp2HmOt! z0$UO+2w(xAWuGGZta6N;XD*N{1O)Y?MUjN$Z1f>sKfDJv8%^}3;Y>g*QG<{MUeJI} zlSC>5m)G#6+Xq9`49$C(5^kY0m=L-EBcY#%e);w1KQ6DbuQf9G5k^EWpgl<$kB5r3 z=^W`IhksTi<~ZQ#jERmEQ#MN#F-(e{Qc`Ic_U{IRUiXk=h5{`Td(Q@yAUvlSCP;5H z2-?{3ARIk}-J4PGFdUzaBGe2NQn^eR$9PB;OH59ae^xVW1nkG%#3V6wQzs7EMePD* z9a>3>T7N|?Q)Pcug4bTw@^87M3w>Pq5%V`RoA8ycqjTlAG3fsfd9!N6x4-`W_n$xE zPEaW{(*}ich>=4;$7-6^!Og!-{bZlWcL(LIJZ>1}h{_cKFo#&1m5+0nT%iEc;H!cNm-BAPjl=<#V8nGGtqN1_BQrLyx) zWLog|L^z8{K2;T&Lx($baQvRT1^(qB96pS{c8;gvXC>v+OC^vKt!r}nk*MuO`!Fo+ z4N5~I*fRIDFR6s4B;w$SIuuwo&vB_GXe+uB$;4EV#@e+>VbeC*|YOS6gAC4|XDzlAP^Gh3C^%NblT zCg(_T&svzU1Z^d2zSdkPg+E>^d=UKf@!aJ0U?552g>AA67s;EHi=BuOYLf}6oIL|I zS70otX?yOB?R)b4C287gx4`*AzQc{cJ*=Opzm)L(RA zD?d+su`4*qM1kTAGu!?DjU4UziSul2dFs5C_5nU-${UFW>PrK?<=VdCEVWtRaf(O=hYL3}Sh1P>zD;xyB-3gjb>>Ib3{SJ0y!f~lVIT~OZ zYy-nMu~&hZHcYLVb`(WpjY>y?aUZfFdTO}z2Weu@qKnC^zlju*B^k;?A*X< kb*D~k_yO=4X=*Tj4_DtqnuJD%vCXmIKLf%!+@uu%02S2(k^lez literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..a32e2fa27e1f6dc6afaaf196c6e9c125deec6d4a GIT binary patch literal 555 zcmV+`0@VED6Ae`GvGZS5;oqc`#X;(_FUviFipfnRj4+pM~5frJQtl0MO{bKC2@pZqE z7|=$S%m6A#4m~VgZA!|7OQdv3!E$130C#XYO$u!Y=Rkjyg<&}?tUpGFC^id5`iV&i zw1;iJ4Pm@gpbr8lCDid)``IYD?BUQ4n@$ioe!K|6?p3oJx7{eZ`i)U0v^he07*Cz? z-Spu$@_#iWmy49}W01P8R=bJ&4TKV@gal<6Xzw7`m{Ouog{2~wLIWKuE9!5=q}e

c9yg^yQLI@JAq>|1%x`m3Qg|D-_aRbT_NM3+`UjwT9OpBI|2y>wHIH_LG4%y z$U)1|&1}BvB6`-L+LeO=igcM;KfNhAuNr@oaab}=LCu&1&I))-yFMzAeAT@Br1r+Q zcKfO9^b9KlcDP_*8*oEXb4F6z)SM6RC)1H7eXoR_we_nxBCqzy2;@n{cEo_UBg)%| z8n^a*;4C=d-*!o&v7I1&VOdV@dqei`*3Fm006!s26g}d literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..5308cca20836d24e4f1ba4ca8201aaccca3ad12c GIT binary patch literal 2648 zcmV-e3a9lSiwFP!00002|Gk-8Ze2$XMgKjDOu#|CAH!j>$Uq%gG9)=2^yqt)ZqjJo zD+B(pV%WyDEs=FtBs&yxcuLd|vW=r=K6czTADe`;YBkzpg(&r4jqk?z<&b5*63IiZ|6d zEbLTT3AJ{qZ73Ldd(x`Fjt#9wAO}{xd^>t*siwH)Dd>K zTw|Ez+@th7wpEvW9a$g0e0_Yjr~i8Zd49H+=U>0dr<`{#Q*f|pZ>6LkNcM$)b$fpK^)Vw5q?{j9D8f^B$G7x zV7@&@uXXg6hLy3}{(*EKd1wE?P5ndn^X67^%cAaU?-iS7mDX}f8Y5L>1VhbzmK-9_ zzy!CHHO-W}dgEHE_;-_>yU0cJh&rN3b7npI3PVftmfcHZRCDt(w}&)JOfDwoSv<)| zLH*_l_LKO_)qRI(X`vUETNpiP+OhFBT*OYbH<`08#@vh7$l<$1PhpoetsoXHyqn`S zvb8!}>}pnK%(PKj#`oveg`2U_bkSrXQMEF7P)%j&>7r3|(gfF$?dj?9>G|sTH8)Aa z>sr0;O{ZH3OIwJu=9P3=)jGM|%&ZJ8&EpQT22B^z@EPq|w9Zl;fYj=xSH zCSBoqN6MVW+9Q-ARjklV>oipu4BkKqV?nFNENt#29?@W??B?|M)aK=S4l*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TrJtYR@>&q9F(N}1kNYap zSwrlkatLgL_h-U7@ri_^Xl`IJj9h`Xz~$SUu+J*@a`WQx=V!PSq-3Blt@D0SVso$4 zX6*x<$s#p^jS~|dJzIBywHFPU(Q6K3rCi1RrfSdE=39~69!>P@>tG`k8bUpHJWU?tK(efyovv} zo9}TJ)M^>6I56lOETX990Vz0ss0X%(p=C7tPMW;ofdi&2PJJ8o+t>RWRs87*F4j&` z9v$43*I%bGb(BFZRDE){fHE=f&U9Ixc9?d G8~^}zm0J-2 literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..8a147eb071ef8d50dfba4187798873397c9d6163 GIT binary patch literal 778 zcmV+l1NHnLiwFP!00002|Fu}#Qrj>Pea~0u1Mou`+D>`s3?wN7p(TTpzIGIOV?>Ol zS;;i~edP-w#urI8eR1OCoTIZVd$rO+=!B;v5}-&bGt zBHi*hL#nw*=ZFFo2^ZJP<$TuEh#>`og!x_rrZg!fLJ90Lhk)U(m%-{Tm|d*qO*-r~ zQl^&(Ogu@RKom0MQkOF2wO^s)RnW^suw6gl)p5s|7mR^Y0^LMv%!o?;F5phT)hr!B z7yn_(JBPoa&y@VS3&Okg{j@u)S182uOCL}cq0c}SiLj+jqR6v*4@zWczV**+LY1;$ z9x1l{Z^n574Ou`_{!~22wZPpN4YSQOw2jm4x&>|X&(keZXYWd95f=fK+?gWHBLw*V z-bTFS@8q&xs_JhnTTeS$vjrs^*2r*Y0Uq)y} zAjeoKUb{eY38vh*=Q>fccH@=d2Ko8Z*oWIgflBFxbt!OlahGyoaMnVH?15`wIztFF zD6K4|zK`iu`C0~ciK)}?%G~6heVpbT$DB7c^6Rv;+*N>m5>l0Hha8kh+sqynbsrnY zYk`B8Bej% zw$?_-Cz$q5%E5gr(c7+RoJP6L8?PZ|4bSGaXCLEZxojK9!yoHg!c+1^P0qd%%JM@9x=Da&Gk`iLrv&!EG7ZrQIr~a78E6qiX1*r>08@j4 Iev%Xb0QWI@y8r+H literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..1fb71b5d05f4da7d3258b0dfb35cfa5fa21ba67f GIT binary patch literal 368 zcmV-$0gwJ4iwFP!00002|E-eGPr@)1fbaYjwI@BSY!eqG+suNJh(wJ}5;Y#0?Ewwl z+Vpj(|Gi}c!@+nkp8Df`ul?R@4M7FSdXd z8)1Reyn=*khPEk%Vq9xhs7eb7hF#Zaxs*`e)au<0OUPXwC2e*>LrQQhw1zUF?w$n~ zvN3?|0*q0nn_5vho>$ss_+jJ)f#;v)!RaUrMnS})Abg=@rOoGUx(@8u! zXbwg!gd?~k)$$*Fd={J!cRu)u7Ansbn#M=3-s=?Hy*}W{N`eGvy(o~xX^`hM31Yil6h%Qx zw9S|n1(M3oDc-)T9;4^!1$u>2lr3A9EDj}ilOJj3<2N5iLvo}cSB%Ce;zXjDEA&AW zl4+7~q0rd{`Z^dQg~gnxFKC9DHl3p>4wp!AG|XMU{_^u5XXn|kwWaqX8e_Rc{b@>B zG!kJyT##^?o8Jl?G4jOHIgPJ*JfrheU`2U+BLo)`jfQtmPd9@q#+<}NTauf1MMR8Q z4lzndc$JwD?K^q$$B+Kta(q*DC+|w&P(29}@>N0^iAJHIiOON}pUnsx0=s^f5l)nC z=){-~h%}DeW-WL~q)=@VGop%EYP*)ptEI48C4(Xil{e2G!lNr2*=R|IU_E;eGESz z1%)Myh$s>&5}_Fvnum5opVpCPu%FO(XBVFh_@|Np*^TqhJ#W0A61`Ez&@>a5Xj4S8 zR7RRep6uxR-bv3Jah7Iz-q%5BS~_7-Dl=J3c$~9vfvLW`P%4rAAXw^QdNdB^1|xWR zT?J}m<=qo3VzlByk2mFMDZW?CXoT~jn!t>;zqR%b&$$u!;n5#GPM)t1r{S&O{Pm;J zkYOn;IsJk~aZx`ED?LG}k7K&ZW7?%u15@Ksd7`QW>&7`uwZ>YL23oH9kBL<7F=Sqj zaVYI_?G#Jq0S-IlAR047s;3|@lFb!8SG9k3#jbfIGEji1nj z=xPqvn#rW}kCVa`=hxG&$?brElf=muvJ)wTL&}V{vlh!O(M_3bWLU0>Hsqaxc&J9X ztQhO61_(X3v<1IY_grY~mP-Ja9djTdQ;}LQ$}1V1lCcMJ+Lm0WT&)&tIK8ctjia^X zIB~WYFhC4e5cinME0#-sSXaMR0hKY_<1wpBw=nXBsTF(U>Q1_}+;<~i-Z``iq6E<) zm|~A`q=>eAj&5NUIJVeo_X;k-)NeKb>}wsJ>FT{jC$`z%qzzf^XXDzi)pw!XbYcK7 zZ*XrJfTQFMo5J?=0rG>73PtN_Du*$DVXMgASsW;M$8@f$7$G zIF8u+Zz{SfzTee2hU^9A5wtI19ic_yFbhrZRtni&+a<0t*MdNGJ?QK_BK$DX@KOns zs|{_R_M&Nw)|#z-Tl9<^a?Sp(7?N@JHWXOG1}LbK7KoOk!!yzPiV~EM*3KAwPkR`u zqoj}&ZR)PIS(<=v<=xgNV3)1MF~WxIyi`E|kJYzxn4kQGcG?0Q&_7O^B~ced5l@`#>G=^^q$80OVcszyJUM literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..f42169a4e84217e9dc0e3405ca6467d1e67be2f0 GIT binary patch literal 2282 zcmVV^TY|`uihQd0?2#E>(nN1KF3UspNL| zZBURUN0LdHUq4s&7}yvRoIrRmAh(WA-#+);qi)#`vEVcBX1sW!90=hfLLrziQ|70P zKb?fCf$s8I(T!^-v7OJWVR{Dr*|Xy62Fyu$r=w=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5uZl!nG-rh<_cBm`k2#UTM%apV%oM`}MBIFd0d zxNwvLEE;+1Gk$%0aCmZX^ltyv(ecUN(aHKzWNQ|c<&FzW#*EnpN)9xAgCh4$&ZOk6 z7nF~!q&dUE60=~0qwx}%^qWV0MI7r!&ei8toy%r9$F7PubJuJjCR$SzNA7660*wHq z-TA;MEojB*JtA{(isCtfCw*8pS}MhaNFjpay3DvcleOn>5n&Xkc}&zxG}USRj}C|E zqJ=1ZqSrf3gOz;WGZ*Pah6<*XjDe|4jzVdCQWVAh$|XiyUK`f*i=)J1$khk^DV(19Gu5kfIeen#r=Qc0<;jJ!$)Wu@U+o%cfmW6IXxHSN|g2hvjKS7=IQ6DI13;{nMgq3N>T0U*Qxq#ha1- z`*N6XTz3jhHHXoxrVahNAdg<%U9RxTJ9hf8xqaJ*udak;Rg?8r3#>=~S^Z1qdrFh5 zyL=2v8)KwWuU{w55K@hOKcyu@OWr}J|B)et# zKGgMZxERi8&q7V!yf_}ee!X{mTr3+J0quEl+O^BY^FI!nL5e5r>7NCD#<(0Xy@MNk z*lqVtue;>CQLyX&|7Nk<&3AFQCrlrqhVD!HzZC1g)J`aOmt$8v+E@DpDZU0V>b})o zVcbP&XS89tAY;63TZG|ho^tO64H(6|mpkuwh5n85J;ZZ5%-G@RXbN)~` z566t&1;*@hepe8*Rb1HuJI>-180%E549Zt E0H8x_F8}}l literal 0 HcmV?d00001 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 0000000000000000000000000000000000000000..d1fa0290be442fa825e13e58d514f4456cfa48f8 GIT binary patch literal 2272 zcmV<62p{(!iwFP!00002|GigTa}&7|efO`JN2pqR^!-5<4=l^xo2n4FB;1#+Eoe!t zWXO2N%#01$Uw?aSoaEvJVo1n?lgQFht9APHQMc@eSn!#5GhRGW4utR#p%6@%Df3gt zA5TKnKzH$^=*GE|*v{wG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rJes#s336=CX9dwj>U{u?Opx9}rZ)EF zYQE-ud2n>{=HTe~;Q8?^_N&519;Km{nJH<+2MIygNR~)IRvfuR()pyM<&jE|nvP`5 z3N9Qu0gFc7xX15r4-QWbj@~_gb##34?C4~(6-k>#Wx3lQSuK z>jimaE2-CTuoPJ^!cmKfO#1Cs-yq1Qm~-`co#(Py&atcFb?-GBC=#v7jw5%}Vu9KK z(&>C)k;E5xajj~EsA(D|G%PuqSAIV1dcLHH#sd-FPPt@7T0*oq$ z=%R%veWE9xrshi8@0pAAn4yFzC1YSJld6y-pA<#$e619tG;c&}`jy)(R*ar*tawze zfaIjD(^#!+D2LpCj9h)tpTg;xKU2L*7sDqK0Qx!oSe|@sTc;~qD{=ZUJ|4F%{;Zm+ zKf_eK|HAM0#g_1YwF@fc>K{yh7X$Gbhe!S6qG}2~GrnK1E~tMuW6?*`d7Ug!k*&cQyEOBrL0%WVc#iJ!;STUkdJ&x>k4b5Fu?vG2v?S zlsH33HTM0KrVK6V`l$O0!pB)3&u|X24}?`rr!-8eG;N#u;{D{07k@r`dw5dNi~jK7 z<-tj@cBH>w5KEs5L!MYGZFXnu%3!}RA+*MHz*IHNNQ zHF@*mc>MbHv*Y7p*^vCV=f!E)E*DS#I%ozd9L1eevjA?N>qZ4Tw>9&F&iGwvhHl8 zy}KCO`}q;HZ^iZlxD6@nEl_ta_YKH*BD*_Whp}DZPnYf&nER{UjvCkEr_V+h_m-)C zNrtQMe_G@=F!z_Kp@VAJ)uoY@dvJ4&@-3a)6E8P6L)>xk_aeCyOuHjd`)9ZPhD7a; z7RFcH^gg(K4e1`W;8K&%_dlt+73*j6r*??(1EKL 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());