From 0119b1a5ee94aa4df15322bf3fd6726ecf2d1158 Mon Sep 17 00:00:00 2001 From: lyeepedro Date: Wed, 18 Nov 2026 19:37:26 +0000 Subject: [PATCH 1/6] Scripting: Dryad time/input/world natives, Lua 3D math, roadmaps Shared key/axis/action name lookup, Dryad runtime natives, DryadHost::setInput, caffeine.math 3D and scalar helpers, plus photoreal-world and graphics roadmaps. Co-Authored-By: Claude Sonnet 5.5 --- CMakeLists.txt | 1 + caffeine-website | 2 +- doppio/docs/graphics-roadmap.md | 206 +++++++++++++++++++ doppio/docs/material-pipeline.md | 2 + doppio/docs/nature-generator-guide.md | 2 + doppio/docs/photoreal-world-roadmap.md | 187 +++++++++++++++++ doppio/docs/terrain-generator-guide.md | 2 + src/caffeine/script/DryadHost.cpp | 6 + src/caffeine/script/DryadHost.hpp | 3 + src/caffeine/script/DryadRuntimeBindings.cpp | 144 +++++++++++++ src/caffeine/script/ScriptEngine.cpp | 183 +++++++++++----- src/caffeine/script/ScriptEngine.hpp | 1 + src/caffeine/script/ScriptInputNames.hpp | 17 ++ src/caffeine/script/ScriptSystem.cpp | 1 + tests/test_dryad_host.cpp | 40 ++++ tests/test_script.cpp | 31 +++ 16 files changed, 777 insertions(+), 51 deletions(-) create mode 100644 doppio/docs/graphics-roadmap.md create mode 100644 doppio/docs/photoreal-world-roadmap.md create mode 100644 src/caffeine/script/DryadRuntimeBindings.cpp create mode 100644 src/caffeine/script/ScriptInputNames.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index fc1d08d8..d23300ee 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -467,6 +467,7 @@ if(CAFFEINE_ENABLE_SCRIPTING) target_sources(caffeine-core PRIVATE src/caffeine/script/DryadHost.cpp src/caffeine/script/DryadComponentBindings.cpp + src/caffeine/script/DryadRuntimeBindings.cpp src/caffeine/script/nodes/NodeGraph.cpp src/caffeine/script/nodes/NodeCatalog.cpp src/caffeine/script/nodes/NodeEmitter.cpp diff --git a/caffeine-website b/caffeine-website index efd4718c..1efa6aa0 160000 --- a/caffeine-website +++ b/caffeine-website @@ -1 +1 @@ -Subproject commit efd4718c3f81150f84a8f5320a54afbe69db2752 +Subproject commit 1efa6aa0f392797c9ff013ef5fab4c20d0b9f18b diff --git a/doppio/docs/graphics-roadmap.md b/doppio/docs/graphics-roadmap.md new file mode 100644 index 00000000..ecd645c0 --- /dev/null +++ b/doppio/docs/graphics-roadmap.md @@ -0,0 +1,206 @@ +# Graphics improvement — Micromeshes and Photon roadmap + +
+ Reference + Engine + Last updated: + Source: graphics-roadmap.md +
+ +

How to take the renderer from "good forward PBR with a screen-space GI" to dense, +virtualised geometry (Micromeshes) and world-space dynamic global illumination +(Photon), using only what SDL3 GPU can do on Vulkan, D3D12 and Metal.

+ +Names: the geometry system is called **Micromeshes** and the GI system **Photon**. Both are our own designs. +No code, shader text or data layout is taken from other engines; the public literature (cluster hierarchies, +radiance cascades, voxel clipmaps, visibility buffers) is the only reference. This page is the graphics +companion of [`photoreal-world-roadmap.md`](photoreal-world-roadmap.md), which feeds it with terrain, nature and +materials. + +## 1. Verdict + +**Photon: already under way, finish it.** The engine has a compute radiance-cascade GI with a four-level voxel +far field and multi-bounce feedback (`PhotonCascades.hpp`). The proposal to "build a GI" is mostly +done; the work left is quality, validation and the world-space accuracy items its own header lists. + +**Micromeshes: not started, feasible in stages, with one hard limit.** There are no clusters, GPU culling or +indirect draws today. SDL3 GPU has indirect draw calls, storage buffers and compute passes, but **no mesh +shaders and no portable 64-bit atomics**. So the plan is a hardware-raster cluster renderer first (large +win, low risk) and a compute software rasteriser only for sub-pixel triangles later, using 32-bit atomics. + +**Dropped as written:** an SDF-based GI (Photon already uses radiance cascades plus voxels; a second GI +would double the maintenance), and "trillions of triangles". The realistic target is **tens of millions of +source triangles in view with a frame-bound cost**, which is what clusters deliver. + +## 2. What exists (verified in the tree) + +| Area | Status | Where | +|---|---|---| +| GI near field | **Done**: world-aligned cascades K-1..0, fused trace+merge, SH-L1 resolve | `PhotonCascades.cpp`, `photon_cascade.comp` | +| GI far field | **Done (fallback fill)**: four clipmap levels 0.25/0.5/1/2 m, probes with SH, Chebyshev queries | `PhotonCascades.hpp`, `PhotonFarField.hpp` | +| Multi-bounce | **Done**: previous irradiance fed back with a cap and reprojected history | header notes P5 | +| Baked AO | **Done**: BVH/GPU AO bake | `PhotonAOBake.cpp`, `PhotonGpuBake.cpp` | +| Direct light into GI | **Gap**: injection uses a hemispherical sky term, not the real lights and shadows | header "KNOWN GAPS" | +| Voxelisation | **Gap**: screen depth-accumulation fallback, so off-screen and back faces are missing | header "KNOWN GAPS" | +| Motion vectors | **Gap**: history reprojects with the previous matrix only | header P5 | +| Geometry LOD | **Partial**: 3 clustered-vertex LODs per mesh, terrain chunk LODs, CPU frustum cull | `MeshLOD.cpp`, `TerrainLodSystem.cpp` | +| Occlusion | **Partial**: coarse CPU AABB occluders (max 16), Min-Z pyramid for GI only | `CoarseOcclusion.hpp`, `MinZPyramid.cpp` | +| Instancing | **Done, CPU-grouped**: batches of up to 256 by key | `InstanceBatch.hpp` | +| Shadows | **Done**: 4 directional cascades at 2048, point and spot maps | `GpuDirectionalShadowMap.hpp` | +| Post | **Done**: TAA, ACES, bloom, DOF, SSAO, motion blur, auto exposure | `PostProcessStack.cpp` | +| Compute and indirect in the RHI | **Compute yes, indirect no**: SDL3 exposes it, `CommandBuffer` does not wrap it | `rhi/CommandBuffer.hpp` | +| Website page for Photon | **Stale**: says v0.1, no probe field, single bounce; the code is past that | `caffeine-website/.../editor/photon.md` | + +## 3. Review of the proposal + +* **"Cluster in Rust on a background thread."** Wrong place. Clustering must be an **engine core** module + (`src/caffeine/micromesh`) behind the C ABI, because the renderer, the `.caf` packer and the runtime (no + Rust) all need it. The Rust editor only triggers a bake and shows stats. Generators produce plain meshes; + the cluster build is the last step of the asset pipeline and is cached, never run at game time. +* **"128-256 triangles per cluster, bounds plus geometric error."** Correct. Use 128 triangles and at most + 128 vertices per cluster, a bounding sphere, a normal cone for back-face culling and a **simplification + error** per cluster group, with the parent's error never smaller than its children's (monotonic), so the + cut through the hierarchy is crack-free and view-independent. +* **"Compute shaders choose visible clusters and detail."** Correct, and it is the core: two-phase GPU + culling (previous-frame survivors first, then the rest against a fresh Min-Z pyramid) writing an indirect + argument buffer. We already have the Min-Z pyramid code for GI to reuse. +* **"Software rasterisation in compute."** Only for triangles that cover under about 4 pixels, and only after + the hardware path works. It needs a visibility buffer with atomic min on a packed value. Without 64-bit + atomics, pack 24-bit depth plus 8-bit cluster-local id into 32 bits and resolve the rest in a second pass, + or skip the software path. Treat it as optional. +* **"Eliminates LOD pop-in."** Only with crack-free simplification plus TAA-friendly dithered transitions. + It does not remove material or shadow cost: shadow cascades must use the same cluster cut (coarser). +* **"Trillions of polygons."** No. Memory (cluster data streaming) and the per-pixel cost bound it. Plan for + a fixed budget (visible clusters, rasterised pixels) and measure. +* **"Foliage and alpha."** Cluster rendering suits opaque geometry. Alpha-tested leaves and grass stay on + the instanced path (with impostors) until a cutout-aware cluster path is justified. +* **GI "route A, SDF".** Not adopted: Photon already covers it with probes plus voxels. What the SDF idea + adds that we lack is **accurate occlusion from off-screen and back-face geometry**, which the conservative + triangle voxeliser (below) provides inside the existing design. +* **GI "route B, POM GI".** Only as a **micro-contact** term: the height maps already give POM + self-shadow and a cavity term (`material-pipeline.md`). Extending that to a small indirect bounce in cavities + is cheap and local, but it is a detail layer on top of Photon, not a GI. +* **"Anisotropic filtering, ACES, sRGB."** Already in (ACES fitted, sRGB, mip chains). Only the explicit + anisotropic sampler setting is worth checking. + +## 4. Roadmap — Photon (GI) + +Photon first: it is closest to done, benefits every scene now, and Micromeshes will need its voxels. + +### Phase P-A — Make it correct + +- [ ] Inject **real direct light** (sun, point, spot, with the shadow term) into the voxel/probe radiance + instead of the hemispherical sky term. Test: a red wall lit by the sun tints a nearby white floor. +- [ ] **Motion vectors** pass (per object matrices, previous frame), used by Photon history, TAA and motion + blur. Remove the "no motion vectors" gap; invalidate history on disocclusion by depth/normal test. +- [ ] Conservative **triangle voxeliser** with dirty-region updates (static geometry once, dynamic per + frame), replacing the G-buffer fallback. Keep the fallback behind a quality tier. +- [ ] Headless regression scenes: Cornell box, light-through-door, thin wall leak. Fixed seeds, image + thresholds in `doppio/tests/ui-flows`. + +### Phase P-B — Quality and stability + +- [ ] Normal-aware spatial-temporal denoise of the SH resolve; clamp fireflies; ghosting metrics in tests. +- [ ] Emissive surfaces as lights (materials already have emissive maps). +- [ ] Sky as a proper source: feed the prefiltered environment (split-sum) to Photon far field and to + specular IBL, one source of truth. +- [ ] Glossy reflections from the probe field when screen-space tracing misses (replaces the per-object + probe cubemaps as the fallback, so off-screen reflections stay stable). +- [ ] Per-view scratch resources (the header notes one shared scratch instance); needed for editor + previews and split view. + +### Phase P-C — Scale and cost + +- [ ] Quality tiers with measured GPU budgets (Eco/Low/Balanced/High) and a frame-time governor. +- [ ] Clipmap far field following the camera with toroidal updates; larger worlds without re-fill spikes. +- [ ] Feed terrain and vegetation chunks (from the world roadmap) into the voxel volume as they stream in. +- [ ] Update the website Photon page to the real state and add the new knobs to the editor UI with `UiId`s. + +## 5. Roadmap — Micromeshes (virtual geometry) + +Each phase ships alone and keeps the old path as a fallback behind a flag. + +### Phase M-0 — RHI and tooling prerequisites + +- [ ] Wrap `SDL_DrawGPUIndexedPrimitivesIndirect` and graphics/compute **storage buffers** in + `rhi/CommandBuffer` with device capability checks and a fallback when unsupported. +- [ ] GPU timestamp or CPU-side pass timers per stage, visible in the Profiler; a stats overlay + (clusters in, culled, drawn, triangles, pixels). +- [ ] A reproducible benchmark set (dense rock field, forest, terrain) using `assets/benchmarks`. + +### Phase M-1 — Cluster build (offline, core) + +- [ ] `micromesh` module: split a mesh into clusters of at most 128 triangles (spatial locality, meshopt-style + greedy, our own implementation), with bounding sphere, normal cone and local vertex remap. +- [ ] Build a **hierarchy**: group clusters, simplify groups by edge collapse with a quadric error and + locked boundaries, split again, repeat to a single root. Store per-group error and monotonic + parent error. +- [ ] `.micromesh` section in `.caf` (versioned, POD) and a CLI in `caf-pack`; deterministic output. +- [ ] Tests: crack-free cuts at random error thresholds, watertightness preserved, triangle count per + level, byte-identical rebuilds. + +### Phase M-2 — GPU culling and hardware draw + +- [ ] Upload cluster pages to GPU buffers; per-instance transform buffer (reuse the instance path). +- [ ] Compute pass 1: frustum + normal-cone + screen-space error test against the hierarchy, writing an + indirect draw list. Compute pass 2: Min-Z occlusion against the pyramid built from pass 1's depth. +- [ ] Draw visible clusters through indirect indexed draws into the existing G-buffer targets, so + Photon, SSAO, TAA and post keep working unchanged. +- [ ] Shadow cascades draw their own coarser cut; no cracks between the two (same hierarchy). +- [ ] Terrain tiles and Nature rocks/trunks are first adopters; foliage stays instanced. + +### Phase M-3 — Streaming and memory + +- [ ] Page cluster data in and out by distance and error with a fixed memory budget and an async + upload queue; never stall a frame. +- [ ] Geometry compression (quantised positions and octahedral normals) and an LRU of pages. +- [ ] Hook the world chunks: a chunk's baked meshes are clustered when first cached and reused afterwards. + +### Phase M-4 — Small-triangle path (optional, measure first) + +- [ ] Compute rasteriser for clusters whose triangles are under ~4 pixels, writing a visibility buffer + with 32-bit atomics and a resolve pass that fetches attributes. Gate on a measured win over the + hardware path on dense rock/bark scenes. +- [ ] Material resolve in screen tiles to avoid one pass per material. + +### Phase M-5 — Editor integration + +- [ ] Inspector toggle "Micromesh" on a Mesh Filter, a stats panel and a debug view (cluster colours, + error cut, culled clusters), `UiId` catalogue entries and MCP actions. +- [ ] Nature, Terrain and Water generators export through the cluster build; Nature gets a + **cluster LOD** option replacing the old billboard-only plan for non-foliage parts. +- [ ] Docs and headless captures (cluster debug view) in the site. + +## 6. Shared items + +- [ ] **One visibility source**: the cluster cull and Photon voxelisation read the same instance data. +- [ ] **Frame graph light**: explicit pass list with resource lifetimes so culling, G-buffer, Photon, + shadows and post are ordered and memory is reused; today the order is hand-written. +- [ ] **Quality governor**: one setting maps to Photon tier, shadow resolution, cluster error threshold, + and runtime scalers (resolution, TAA upsampling). +- [ ] **Reference scenes** with fixed seeds rendered headless and compared as visual baselines. + +## 7. Risks + +| Risk | Mitigation | +|---|---| +| No mesh shaders, no 64-bit atomics in SDL3 GPU | hardware indirect draws first; software raster optional and 32-bit | +| Cracks between LOD groups | locked group boundaries, monotonic error, tests that cut at random thresholds | +| Photon history ghosts with moving objects | motion vectors, disocclusion tests, regression scenes | +| Voxeliser cost on dynamic geometry | static baked once, dynamic dirty-region updates only | +| Two geometry paths drift apart | flag-gated, same G-buffer output, shared tests | +| Scope | Photon P-A and Micromeshes M-0/M-1 are independent and can run in parallel | + +## 8. Suggested order + +1. **P-A** (correct Photon: real lights, motion vectors, voxeliser) and **M-0** (RHI indirect, stats), in parallel. +2. **M-1** cluster build, then **M-2** GPU culling on terrain and rocks. +3. **P-B**, then **M-3** streaming tied to the world chunks. +4. **P-C**, **M-5**, and **M-4** only if profiling asks for it. + +## 9. Related + +- [`photoreal-world-roadmap.md`](photoreal-world-roadmap.md): the content generated for this renderer. +- [`material-pipeline.md`](material-pipeline.md): POM, displacement and height-derived AO. +- [`nature-generator-guide.md`](nature-generator-guide.md): vegetation LOD and instancing gaps. +- [`terrain-generator-guide.md`](terrain-generator-guide.md): tiled and large terrains. diff --git a/doppio/docs/material-pipeline.md b/doppio/docs/material-pipeline.md index b6b1b597..d5cbe446 100644 --- a/doppio/docs/material-pipeline.md +++ b/doppio/docs/material-pipeline.md @@ -272,6 +272,8 @@ User guide with rendered images: [materials-guide.md](materials-guide.md). own evaluated output, refreshed with the same debounced worker pass. - [ ] Preset parameters (seed / scale / wear) are not yet exposed in the UI. +World-scale plan (seed, scatter, streaming): [`photoreal-world-roadmap.md`](photoreal-world-roadmap.md). + ## Definition of done for "the base is complete" - Generator graph edit undo/redo and wire editing never lose work. diff --git a/doppio/docs/nature-generator-guide.md b/doppio/docs/nature-generator-guide.md index af11db57..e26d9243 100644 --- a/doppio/docs/nature-generator-guide.md +++ b/doppio/docs/nature-generator-guide.md @@ -249,6 +249,8 @@ oak crown with varied, curved leaves. * `.obj` only (no `.glb` writer yet). * Scattering over terrain, biomes and density maps belong to the terrain generator, which is separate. +Scatter, LOD and impostors are planned in [`photoreal-world-roadmap.md`](photoreal-world-roadmap.md). + ## 9. Regenerating the images ```bash diff --git a/doppio/docs/photoreal-world-roadmap.md b/doppio/docs/photoreal-world-roadmap.md new file mode 100644 index 00000000..a2547991 --- /dev/null +++ b/doppio/docs/photoreal-world-roadmap.md @@ -0,0 +1,187 @@ +# Photoreal procedural world — validation and roadmap + +
+ Reference + Doppio + Last updated: + Source: photoreal-world-roadmap.md +
+ +

One seed, rule files (.nature, .mat, terrain and water graphs) and +deterministic chunk streaming, so a whole photoreal world is generated on demand, always identical, and +mostly baked. This page checks the idea against the code and lists what to build, in order.

+ +## 1. Verdict + +**Implementable, with the current stack (Rust/Iced editor, C++ engine on SDL3 GPU, C ABI).** Nothing in the idea +needs a new renderer. The hard parts are not graphics: they are *determinism*, *chunk borders* and +*connecting the generators*. Most of the rendering features a "photoreal" pass asks for already exist; the +missing piece is the **world layer** that connects terrain, nature, materials and water. + +The idea has four parts. Their status in the repository: + +| Idea | Status | Evidence | +|---|---|---| +| Procedural materials, multi-frequency, anti-tiling | **Done**, tune with recipes | ~123 procedural ops, 78 presets, Variation class (`material-pipeline.md`) | +| Depth: parallax, micro-shadows, AO, IBL | **Done** | POM with self-shadow, geometric displacement, height-derived AO, env map + probe IBL (`scene_lit.frag`) | +| Rules as files (`.nature`, `.mat`, terrain/water graphs) | **Done per tool**, not linked | each generator saves its own graph and places assets | +| Seed → deterministic world, streamed by chunk | **Partial** | `ProceduralStreamer` + `hash01(cx, cz, seed)` exist, but use a built-in fbm terrain and props, not the generators | +| Vegetation/rocks adapted to terrain, scattered by masks | **Missing** | "Scatter over terrain" is listed as not done in both guides | +| Instancing, LOD, impostors for mass vegetation | **Partial** | instanced draws and `MeshLOD` exist; vegetation is merged meshes, no impostors | + +## 2. Review of the claims in the original discussion + +Kept as true, with caveats that matter for the design. + +* **"Stable by derived seeds."** True, and already how the streamer works (`hash01(cx, cz, seed, salt)`). + Caveats: (1) use an **integer hash** (xxHash or SplitMix) per cell, never floating-point sums; + (2) never let a parallel reduction decide the order of results, sort by cell id; (3) pin the noise and + `libm` calls (or avoid `sin`/`pow` in anything that decides *placement*), otherwise two platforms place + a tree a metre apart; (4) version the algorithm: a change to a `.nature` op changes every tree, so each rule + file carries a `generator_version` and old worlds keep the old behaviour or are re-baked on purpose. +* **"Save only rule + position + sub-seed."** True for *generated* content. Anything the user *edits* (sculpted + terrain, a moved tree, a deleted rock) must be stored as a sparse **delta layer** over the generated + world, or editing breaks determinism. Add this from the start. +* **"Generate once per chunk, freeze the result."** Right, and it fixes the performance worry. Cache by + `(world_seed, chunk, rule hashes, generator_version)`, on disk as well as in RAM (this is the "pre-compiled" + part of the idea). +* **Chunk borders are the real trap.** A tree whose crown crosses a chunk edge must not be duplicated or + cut. Use **cell ownership**: placement runs on a global jittered grid (or blue-noise/Poisson cells); a cell + belongs to exactly one chunk, and a chunk generates its own cells *plus a margin read-only* to resolve + collisions with neighbours' cells, using the same deterministic order. +* **"Trees do not cross rocks or each other."** Solve it at *placement*, not at mesh time: priority classes + (rocks, then trees, then bushes, then grass), exclusion radius per class, and a density mask. This is cheap + and deterministic. Per-vertex raycasts are only for the trunk base. +* **Ground conforming.** Sample `terrain_height(x, z)` (exists in the C ABI) and the terrain normal. Trees + take a *blend* of up and the normal (small factor), rocks sink by the lowest height under their footprint, + grass follows the normal. Root flare and rock skirts need a deformed base mesh and vertex colour (not done, + see phase 3). +* **Contact blending.** Correct: vertex colour on the base plus a ground blend in the shader. Needs the + **vertex colour** channel that the Nature Generator does not have yet. +* **The pasted Height-to-AO code** (Rust, 8 directions): the idea is right, and we already ship an AO from + height. If it is reused: the parallel version has a typo, the direction `(0, 2)` should be `(0, -1)`, and + the slope term `height_diff / distance` ignores the world scale of the texel, so AO strength changes with + resolution. Compare with ours before replacing anything. +* **"Photorealism is only the graph."** Partly. Photoreal also depends on **scale and variety**: + one bark texture on every trunk looks fake at any quality. Per-instance tint, wetness, wind and + seasonal variation matter as much as extra noise octaves. + +Corrections specific to this project: + +* The original text speaks of `SDL_CreateTexture`, a 2D API. The engine uses **SDL3 GPU**; mips are already + generated (`createMippedTexture`, box filter). Better filtering (Kaiser) and an explicit anisotropic + sampler setting are optional improvements, not a gap. +* Normal blending (whiteout) already exists as a graph node; the preview material path does not need a + new blend function. +* Specular IBL here uses an equirectangular sky and a probe; a **prefiltered cubemap with a BRDF LUT** is + the proper split-sum form and a possible quality upgrade, not a missing feature. + +## 3. Target architecture + +```text +world.cworld (seed, generator_version, layer list, edit deltas) + ├─ terrain graph → height + masks (slope, wetness, flow, biome) [exists: terrain generator] + ├─ biome rules → density per class from the masks [new] + ├─ scatter rules → .nature / .rock / grass refs + placement rules [new] + ├─ water graph → water bodies from flow and sea level [partial] + └─ material layers→ splat/blend from the same masks [partial] + +per chunk (worker thread, deterministic): + masks → placement (cells, priority, exclusion) → instances (transform + sub-seed + variant) + → bake cache (RAM + disk) → GPU instance buffers per LOD → draw +``` + +Principles: (1) a chunk is a **pure function** of the world file and its coordinates; (2) generators produce +**data** (fields, instance lists, meshes), the renderer never runs a graph; (3) only commands via +`Message`s and MCP actions, as in the rest of Doppio; (4) `libcaffeine-capi` stays the only boundary. + +## 4. Roadmap + +Each phase ends with something visible and testable headless. Do them in order; phases 1 and 2 are +independent of renderer work. + +### Phase 0 — Determinism foundation + +- [ ] `core/Hash` with an integer hash and `derive_seed(parent, salt, x, z)`; a golden test that pins + outputs for fixed inputs on all supported platforms. +- [ ] Replace `hash01` use in the streamer with it; keep the old path under a `generator_version`. +- [ ] `generator_version` field in `.nature`, `.mat`, terrain and water graphs and in the world file. +- [ ] Test: generate the same chunk on 1 and on N threads and compare byte-for-byte. + +### Phase 1 — Terrain masks exported to the engine + +- [ ] Output node exposes named **masks** (slope, height band, wear, deposit, flow, wetness, curvature) as + engine-readable 8/16-bit fields, not only the four splat layers. +- [ ] C ABI: read a mask at `(x, z)` and over a rectangle; terrain normal at `(x, z)` (versioned, + POD structs, tests on both sides as the rules require). +- [ ] Biome layer: a small graph (or table) that turns masks into per-class density maps. + +### Phase 2 — Scatter engine (core, no UI) + +- [ ] `scatter` module in `src/caffeine`: jittered-grid / Poisson placement per class, density from + the biome maps, exclusion radii, priority order, cell ownership and margin for chunk borders. +- [ ] Output: instance list `(transform, variant id, sub-seed, tint)`; conform to height and normal with + per-class rules (tree: slight tilt; rock: sink by footprint minimum; grass: follow normal). +- [ ] Tests: no overlap inside and across chunk borders; same result for any chunk load order; density + matches the mask statistically. + +### Phase 3 — Nature assets that can be scattered + +- [ ] **Vertex colour** and a **wind mask** in the Nature mesh output (needs a C ABI version). +- [ ] **Material slots per submesh** (already the next engine step in the Nature guide). +- [ ] Base deformation: root flare and rock skirt from a ground height callback at bake time. +- [ ] Variants: N seeds per `.nature` rule baked into a variant set; per-instance tint and scale range. +- [ ] Ground-contact blend in the shader (rock/trunk to ground colour using vertex colour). + +### Phase 4 — Rendering at scale + +- [ ] GPU-instanced vegetation with per-chunk instance buffers (the instanced path exists, with a + 256-per-batch limit; lift it for scatter). +- [ ] LOD chain from the same graph (full, simplified, impostor), distance and screen-size switching with + dithered cross-fade; billboard impostor atlas baked per variant. +- [ ] Culling by chunk, then by instance, on the CPU first; GPU culling only if profiling asks for it. +- [ ] Wind (vertex stage), leaf translucency and a normal map on leaf cards (listed as missing in the Nature + guide). + +### Phase 5 — Streaming and caching + +- [ ] Chunk jobs on the engine thread pool with a priority queue and a per-frame time budget; never block the + viewport (same rule as the generator bakes). +- [ ] Persistent bake cache keyed by `(seed, chunk, rule hashes, generator_version)`; invalidation when a + rule file changes. +- [ ] Edit layer: sparse deltas for sculpt, moved or removed instances; applied after generation. +- [ ] Terrain tiling and bigger-than-513 heightfields (the terrain guide already lists a tiled or GPU path). + +### Phase 6 — Editor integration + +- [ ] A **World** tab: seed, layer list, biome table, rule files per class, region painting of overrides. +- [ ] Place and preview a chunk grid in the viewport; show cache hits and chunk build time in the HUD. +- [ ] `UiId` entries, undoable edits (`App::commit`), MCP actions and a headless flow for each step. +- [ ] Docs: update the Nature, Terrain and Water guides and the website pages; regenerate captures through + the headless driver. + +### Phase 7 — Visual quality pass (parallel track) + +- [ ] Prefiltered environment cubemap + BRDF LUT (split-sum); keep the current path as fallback. +- [ ] Per-instance wetness, dust and seasonal tint driven by the same masks. +- [ ] Bark, grass and soil surfaces from the Rock Surface bake (Nature guide). +- [ ] Reference scenes with fixed seeds, rendered headless, used as visual regression baselines. + +## 5. Risks + +| Risk | Mitigation | +|---|---| +| Float differences change placement across machines | integer hash, versioned algorithm, golden tests (phase 0) | +| Chunk-border duplicates or gaps | cell ownership and read-only margin (phase 2) | +| Generation hitches while moving | time-budgeted jobs, cache, prefetch ring (phase 5) | +| Many materials per tree break batching | slots per submesh, atlas variants, impostors (phases 3, 4) | +| User edits break determinism | sparse delta layer from day one (phase 5) | +| Scope: seven generators in one world | each phase ships alone and is useful without the next | + +## 6. Related + +- [`material-pipeline.md`](material-pipeline.md): materials, depth, variation. +- [`nature-generator-guide.md`](nature-generator-guide.md): recipes, LOD and instancing gaps. +- [`terrain-generator-guide.md`](terrain-generator-guide.md): masks, splat layers, limits. +- [`water-generator-guide.md`](water-generator-guide.md): water surface and `water_height`. +- [`graphics-roadmap.md`](graphics-roadmap.md): the renderer side (Micromeshes, Photon). diff --git a/doppio/docs/terrain-generator-guide.md b/doppio/docs/terrain-generator-guide.md index 90231583..1c428853 100644 --- a/doppio/docs/terrain-generator-guide.md +++ b/doppio/docs/terrain-generator-guide.md @@ -121,6 +121,8 @@ status: * **Tuning.** Preset relief and sea levels were tuned against the software preview and a single engine render; expect to adjust them (max height, sea, rock slope) per project. +World-level plan (masks to the engine, scatter, chunk streaming): see [`photoreal-world-roadmap.md`](photoreal-world-roadmap.md). + ## 6. Agents and scripting The tab is a pane like the others (`editor.pane.terrain_generator`, `terraingen.*` ids). Headless: fixture diff --git a/src/caffeine/script/DryadHost.cpp b/src/caffeine/script/DryadHost.cpp index 05a2fc11..d7da9040 100644 --- a/src/caffeine/script/DryadHost.cpp +++ b/src/caffeine/script/DryadHost.cpp @@ -19,6 +19,8 @@ namespace Caffeine::Script { void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr); +void bindRuntimeNatives(dryad::Interpreter& interp, ECS::World** worldPtr, + Input::InputManager** inputPtr); namespace { @@ -117,6 +119,7 @@ struct DryadHost::Impl { }; ECS::World* world = nullptr; + Input::InputManager* input = nullptr; std::string searchRoot; std::unordered_map sessions; @@ -195,6 +198,7 @@ struct DryadHost::Impl { return dryad::Value(); }); bindComponentNatives(interp, worldPtr); + bindRuntimeNatives(interp, worldPtr, &input); interp.set_network_allowed(false); if (const char* stdlib = std::getenv("DRYAD_STDLIB_DIR")) { interp.set_stdlib_root(stdlib); @@ -213,6 +217,8 @@ DryadHost::~DryadHost() { delete m_impl; } void DryadHost::setWorld(ECS::World* world) { m_impl->world = world; } +void DryadHost::setInput(Input::InputManager* input) { m_impl->input = input; } + void DryadHost::setSearchRoot(const std::string& root) { m_impl->searchRoot = root; } std::string DryadHost::searchRoot() const { return m_impl->searchRoot; } diff --git a/src/caffeine/script/DryadHost.hpp b/src/caffeine/script/DryadHost.hpp index 7fc2ba01..a6cebd74 100644 --- a/src/caffeine/script/DryadHost.hpp +++ b/src/caffeine/script/DryadHost.hpp @@ -6,6 +6,7 @@ #include namespace Caffeine::ECS { class World; } +namespace Caffeine::Input { class InputManager; } namespace Caffeine::Script { @@ -19,6 +20,8 @@ class DryadHost { DryadHost& operator=(const DryadHost&) = delete; void setWorld(ECS::World* world); + /// Optional; without it the `caffeine_input_*` natives report no input. + void setInput(Input::InputManager* input); /// Project root used to resolve relative script paths (for example /// `scripts/player.dyd`). Relative paths that already exist from the diff --git a/src/caffeine/script/DryadRuntimeBindings.cpp b/src/caffeine/script/DryadRuntimeBindings.cpp new file mode 100644 index 00000000..8a1e899b --- /dev/null +++ b/src/caffeine/script/DryadRuntimeBindings.cpp @@ -0,0 +1,144 @@ +// Dryad natives for time, input and world queries. They mirror Lua's `caffeine.time`, +// `caffeine.input` and `caffeine.world`, so a project can pick either language. +// +// caffeine_time_delta() / _unscaled_delta() / _total() / _fixed_delta() / _scale() / _frame() +// caffeine_time_set_scale(s) / caffeine_time_paused() / caffeine_time_set_paused(b) +// caffeine_input_key_down(name) "Space", "W", "LShift" ... +// caffeine_input_axis(name) "Horizontal", "Vertical", "LookX", "LookY" +// caffeine_input_action_down(name) / caffeine_input_action_pressed(name) +// caffeine_input_mouse_x() / _mouse_y() / _mouse_dx() / _mouse_dy() +// caffeine_input_mouse_down(button) 1 left, 2 middle, 3 right +// caffeine_world_create([name]) -> entity id (0 when there is no world) +// caffeine_world_destroy(entity) / caffeine_world_is_alive(entity) +// caffeine_world_distance(a, b) metres; 1e9 when either has no position + +#include "debug/LogSystem.hpp" +#include "ecs/Components.hpp" +#include "ecs/Components3D.hpp" +#include "ecs/World.hpp" +#include "input/InputManager.hpp" +#include "runtime/PlayClock.hpp" +#include "script/ScriptInputNames.hpp" + +#include "dryad/compiler/interpreter.h" +#include "dryad/runtime/value.h" + +#include + +namespace Caffeine::Script { +namespace { + +using Args = std::vector; + +double numberOf(const dryad::Value& v) { + if (v.is_integer()) return static_cast(v.as_integer()); + if (v.is_float()) return v.as_float(); + if (v.is_boolean()) return v.as_boolean() ? 1.0 : 0.0; + return 0.0; +} + +std::string textOf(const Args& args, size_t i) { + return i < args.size() && args[i].is_string() ? args[i].as_string() : std::string(); +} + +bool positionOf(ECS::World* world, u32 id, Vec3& out) { + if (!world) return false; + ECS::Entity e(id, world); + if (!e.isValid() || !world->isEntityAlive(e)) return false; + if (auto* p3 = e.get()) { out = p3->position; return true; } + if (auto* t = e.get()) { out = t->position; return true; } + return false; +} + +} // namespace + +void bindRuntimeNatives(dryad::Interpreter& interp, ECS::World** worldPtr, + Input::InputManager** inputPtr) { + interp.define_native("caffeine_time_delta", [](const Args&) { + return dryad::Value(static_cast(Runtime::PlayClock::instance().deltaTime())); }); + interp.define_native("caffeine_time_unscaled_delta", [](const Args&) { + return dryad::Value(static_cast(Runtime::PlayClock::instance().unscaledDeltaTime())); }); + interp.define_native("caffeine_time_total", [](const Args&) { + return dryad::Value(static_cast(Runtime::PlayClock::instance().time())); }); + interp.define_native("caffeine_time_fixed_delta", [](const Args&) { + return dryad::Value(static_cast(Runtime::PlayClock::instance().fixedDeltaTime())); }); + interp.define_native("caffeine_time_scale", [](const Args&) { + return dryad::Value(static_cast(Runtime::PlayClock::instance().timeScale())); }); + interp.define_native("caffeine_time_frame", [](const Args&) { + return dryad::Value(static_cast(Runtime::PlayClock::instance().frame())); }); + interp.define_native("caffeine_time_set_scale", [](const Args& a) { + if (!a.empty()) Runtime::PlayClock::instance().setTimeScale(static_cast(numberOf(a[0]))); + return dryad::Value(); }); + interp.define_native("caffeine_time_paused", [](const Args&) { + return dryad::Value(Runtime::PlayClock::instance().paused()); }); + interp.define_native("caffeine_time_set_paused", [](const Args& a) { + if (!a.empty()) Runtime::PlayClock::instance().setPaused(numberOf(a[0]) != 0.0); + return dryad::Value(); }); + + auto input = [inputPtr]() -> Input::InputManager* { return inputPtr ? *inputPtr : nullptr; }; + + interp.define_native("caffeine_input_key_down", [input](const Args& a) { + Input::Key key; + Input::InputManager* im = input(); + return dryad::Value(im && lookupScriptKey(textOf(a, 0), key) && im->isKeyDown(key)); }); + interp.define_native("caffeine_input_axis", [input](const Args& a) { + Input::Axis axis; + Input::InputManager* im = input(); + if (!im || !lookupScriptAxis(textOf(a, 0), axis)) return dryad::Value(0.0); + return dryad::Value(static_cast(im->axisState(axis).value)); }); + interp.define_native("caffeine_input_action_down", [input](const Args& a) { + Input::Action action; + Input::InputManager* im = input(); + return dryad::Value(im && lookupScriptAction(textOf(a, 0), action) && im->actionState(action).pressed); }); + interp.define_native("caffeine_input_action_pressed", [input](const Args& a) { + Input::Action action; + Input::InputManager* im = input(); + return dryad::Value(im && lookupScriptAction(textOf(a, 0), action) && im->actionState(action).justPressed); }); + interp.define_native("caffeine_input_mouse_x", [input](const Args&) { + Input::InputManager* im = input(); + return dryad::Value(im ? static_cast(im->mousePosition().x) : 0.0); }); + interp.define_native("caffeine_input_mouse_y", [input](const Args&) { + Input::InputManager* im = input(); + return dryad::Value(im ? static_cast(im->mousePosition().y) : 0.0); }); + interp.define_native("caffeine_input_mouse_dx", [input](const Args&) { + Input::InputManager* im = input(); + return dryad::Value(im ? static_cast(im->mouseDelta().x) : 0.0); }); + interp.define_native("caffeine_input_mouse_dy", [input](const Args&) { + Input::InputManager* im = input(); + return dryad::Value(im ? static_cast(im->mouseDelta().y) : 0.0); }); + interp.define_native("caffeine_input_mouse_down", [input](const Args& a) { + Input::MouseButton button; + Input::InputManager* im = input(); + const auto index = a.empty() ? 0u : static_cast(numberOf(a[0])); + return dryad::Value(im && lookupScriptMouseButton(index, button) && im->isMouseButtonDown(button)); }); + + interp.define_native("caffeine_world_create", [worldPtr](const Args& a) { + ECS::World* world = worldPtr ? *worldPtr : nullptr; + if (!world) return dryad::Value(static_cast(0)); + const std::string name = textOf(a, 0); + ECS::Entity e = world->create(name.empty() ? "DryadEntity" : name.c_str()); + return dryad::Value(static_cast(e.id())); }); + interp.define_native("caffeine_world_destroy", [worldPtr](const Args& a) { + ECS::World* world = worldPtr ? *worldPtr : nullptr; + if (world && !a.empty()) { + ECS::Entity e(static_cast(numberOf(a[0])), world); + if (e.isValid() && world->isEntityAlive(e)) world->destroy(e); + } + return dryad::Value(); }); + interp.define_native("caffeine_world_is_alive", [worldPtr](const Args& a) { + ECS::World* world = worldPtr ? *worldPtr : nullptr; + if (!world || a.empty()) return dryad::Value(false); + ECS::Entity e(static_cast(numberOf(a[0])), world); + return dryad::Value(e.isValid() && world->isEntityAlive(e)); }); + interp.define_native("caffeine_world_distance", [worldPtr](const Args& a) { + ECS::World* world = worldPtr ? *worldPtr : nullptr; + Vec3 p, q; + if (a.size() < 2 || !positionOf(world, static_cast(numberOf(a[0])), p) || + !positionOf(world, static_cast(numberOf(a[1])), q)) { + return dryad::Value(1.0e9); + } + const double dx = p.x - q.x, dy = p.y - q.y, dz = p.z - q.z; + return dryad::Value(std::sqrt(dx * dx + dy * dy + dz * dz)); }); +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/ScriptEngine.cpp b/src/caffeine/script/ScriptEngine.cpp index 8181bcdc..d53f061a 100644 --- a/src/caffeine/script/ScriptEngine.cpp +++ b/src/caffeine/script/ScriptEngine.cpp @@ -1,4 +1,5 @@ #include "script/ScriptEngine.hpp" +#include "script/ScriptInputNames.hpp" #include "script/NativeModuleHost.hpp" #include "events/Events.hpp" #include "script/ScriptTypes.hpp" @@ -496,73 +497,153 @@ void registerDebugBindings(sol::state& lua) { }; } +// Vectors are plain tables {x, y[, z]}. A result carries `z` only when an operand does, +// so the original 2D scripts keep getting {x, y}. +struct ScriptVec { + f32 x = 0.0f, y = 0.0f, z = 0.0f; + bool has3 = false; +}; + +ScriptVec readVec(const sol::table& t) { + ScriptVec v; + v.x = t["x"].get_or(0.0f); + v.y = t["y"].get_or(0.0f); + sol::object z = t["z"]; + v.has3 = z.valid() && z.get_type() == sol::type::number; + v.z = v.has3 ? z.as() : 0.0f; + return v; +} + +sol::table writeVec(sol::state_view lua, f32 x, f32 y, f32 z, bool has3) { + sol::table t = lua.create_table(); + t["x"] = x; + t["y"] = y; + if (has3) t["z"] = z; + return t; +} + void registerMathBindings(sol::state& lua) { sol::table mt = lua["caffeine"]["math"]; - mt["vec2"] = [&lua](f32 x, f32 y) -> sol::table { - sol::table t = lua.create_table(); - t["x"] = x; - t["y"] = y; - return t; - }; + mt["pi"] = 3.14159265358979323846; + mt["epsilon"] = 1.0e-5; - mt["add"] = [&lua](sol::table a, sol::table b) -> sol::table { - sol::table t = lua.create_table(); - t["x"] = a["x"].get_or(0.0f) + b["x"].get_or(0.0f); - t["y"] = a["y"].get_or(0.0f) + b["y"].get_or(0.0f); - return t; - }; + // --- Constructors --- + mt["vec2"] = [&lua](f32 x, f32 y) { return writeVec(lua, x, y, 0.0f, false); }; + mt["vec3"] = [&lua](f32 x, f32 y, f32 z) { return writeVec(lua, x, y, z, true); }; - mt["sub"] = [&lua](sol::table a, sol::table b) -> sol::table { - sol::table t = lua.create_table(); - t["x"] = a["x"].get_or(0.0f) - b["x"].get_or(0.0f); - t["y"] = a["y"].get_or(0.0f) - b["y"].get_or(0.0f); - return t; + // --- Vector algebra (2D and 3D) --- + mt["add"] = [&lua](sol::table a, sol::table b) { + const ScriptVec p = readVec(a), q = readVec(b); + return writeVec(lua, p.x + q.x, p.y + q.y, p.z + q.z, p.has3 || q.has3); }; - - mt["length"] = [](sol::table v) -> f32 { - f32 x = v["x"].get_or(0.0f); - f32 y = v["y"].get_or(0.0f); - return std::sqrt(x * x + y * y); + mt["sub"] = [&lua](sol::table a, sol::table b) { + const ScriptVec p = readVec(a), q = readVec(b); + return writeVec(lua, p.x - q.x, p.y - q.y, p.z - q.z, p.has3 || q.has3); }; - - mt["normalize"] = [&lua](sol::table v) -> sol::table { - f32 x = v["x"].get_or(0.0f); - f32 y = v["y"].get_or(0.0f); - f32 len = std::sqrt(x * x + y * y); - sol::table t = lua.create_table(); - if (len > 0.0001f) { - t["x"] = x / len; - t["y"] = y / len; - } else { - t["x"] = 0.0f; - t["y"] = 0.0f; - } - return t; + mt["mul"] = [&lua](sol::table a, sol::table b) { + const ScriptVec p = readVec(a), q = readVec(b); + return writeVec(lua, p.x * q.x, p.y * q.y, p.z * q.z, p.has3 || q.has3); + }; + mt["scale"] = [&lua](sol::table v, f32 s) { + const ScriptVec p = readVec(v); + return writeVec(lua, p.x * s, p.y * s, p.z * s, p.has3); }; - mt["dot"] = [](sol::table a, sol::table b) -> f32 { - return a["x"].get_or(0.0f) * b["x"].get_or(0.0f) - + a["y"].get_or(0.0f) * b["y"].get_or(0.0f); + const ScriptVec p = readVec(a), q = readVec(b); + return p.x * q.x + p.y * q.y + p.z * q.z; }; - - mt["mul"] = [&lua](sol::table a, sol::table b) -> sol::table { - sol::table t = lua.create_table(); - t["x"] = a["x"].get_or(0.0f) * b["x"].get_or(0.0f); - t["y"] = a["y"].get_or(0.0f) * b["y"].get_or(0.0f); - return t; + mt["cross"] = [&lua](sol::table a, sol::table b) { + const ScriptVec p = readVec(a), q = readVec(b); + return writeVec(lua, p.y * q.z - p.z * q.y, p.z * q.x - p.x * q.z, p.x * q.y - p.y * q.x, true); + }; + mt["length"] = [](sol::table v) -> f32 { + const ScriptVec p = readVec(v); + return std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z); + }; + mt["lengthSquared"] = [](sol::table v) -> f32 { + const ScriptVec p = readVec(v); + return p.x * p.x + p.y * p.y + p.z * p.z; + }; + mt["distance"] = [](sol::table a, sol::table b) -> f32 { + const ScriptVec p = readVec(a), q = readVec(b); + const f32 dx = p.x - q.x, dy = p.y - q.y, dz = p.z - q.z; + return std::sqrt(dx * dx + dy * dy + dz * dz); + }; + mt["normalize"] = [&lua](sol::table v) { + const ScriptVec p = readVec(v); + const f32 len = std::sqrt(p.x * p.x + p.y * p.y + p.z * p.z); + if (len <= 0.0001f) return writeVec(lua, 0.0f, 0.0f, 0.0f, p.has3); + return writeVec(lua, p.x / len, p.y / len, p.z / len, p.has3); + }; + mt["lerpVec"] = [&lua](sol::table a, sol::table b, f32 t) { + const ScriptVec p = readVec(a), q = readVec(b); + return writeVec(lua, p.x + (q.x - p.x) * t, p.y + (q.y - p.y) * t, p.z + (q.z - p.z) * t, + p.has3 || q.has3); }; - mt["scale"] = [&lua](sol::table v, f32 s) -> sol::table { - sol::table t = lua.create_table(); - t["x"] = v["x"].get_or(0.0f) * s; - t["y"] = v["y"].get_or(0.0f) * s; - return t; + // --- Scalar helpers --- + mt["clamp"] = [](f32 v, f32 lo, f32 hi) -> f32 { return lo > hi ? std::clamp(v, hi, lo) : std::clamp(v, lo, hi); }; + mt["clamp01"] = [](f32 v) -> f32 { return std::clamp(v, 0.0f, 1.0f); }; + mt["lerp"] = [](f32 a, f32 b, f32 t) -> f32 { return a + (b - a) * t; }; + mt["inverseLerp"] = [](f32 a, f32 b, f32 v) -> f32 { + return std::abs(b - a) < 1.0e-9f ? 0.0f : (v - a) / (b - a); + }; + mt["remap"] = [](f32 v, f32 inLo, f32 inHi, f32 outLo, f32 outHi) -> f32 { + const f32 t = std::abs(inHi - inLo) < 1.0e-9f ? 0.0f : (v - inLo) / (inHi - inLo); + return outLo + (outHi - outLo) * t; }; + mt["smoothstep"] = [](f32 e0, f32 e1, f32 v) -> f32 { + if (std::abs(e1 - e0) < 1.0e-9f) return v < e0 ? 0.0f : 1.0f; + const f32 t = std::clamp((v - e0) / (e1 - e0), 0.0f, 1.0f); + return t * t * (3.0f - 2.0f * t); + }; + mt["approach"] = [](f32 cur, f32 target, f32 step) -> f32 { + step = std::abs(step); + if (cur < target) return std::min(cur + step, target); + return std::max(cur - step, target); + }; + mt["sign"] = [](f32 v) -> f32 { return v > 0.0f ? 1.0f : (v < 0.0f ? -1.0f : 0.0f); }; + mt["radians"] = [](f32 deg) -> f32 { return deg * 3.14159265358979f / 180.0f; }; + mt["degrees"] = [](f32 rad) -> f32 { return rad * 180.0f / 3.14159265358979f; }; } + } // anonymous namespace +bool lookupScriptKey(const std::string& name, Input::Key& out) { + static const HashMap map = makeKeyMap(); + const auto* v = map.get(name); + if (!v) return false; + out = *v; + return true; +} + +bool lookupScriptAxis(const std::string& name, Input::Axis& out) { + static const HashMap map = makeAxisMap(); + const auto* v = map.get(name); + if (!v) return false; + out = *v; + return true; +} + +bool lookupScriptAction(const std::string& name, Input::Action& out) { + static const HashMap map = makeActionMap(); + const auto* v = map.get(name); + if (!v) return false; + out = *v; + return true; +} + +bool lookupScriptMouseButton(unsigned index, Input::MouseButton& out) { + switch (index) { + case 1: out = Input::MouseButton::Left; return true; + case 2: out = Input::MouseButton::Middle; return true; + case 3: out = Input::MouseButton::Right; return true; + default: return false; + } +} + // ============================================================================ // ScriptEngine implementation // ============================================================================ @@ -748,6 +829,8 @@ void ScriptEngine::setWorld(ECS::World* world) { m_impl->m_world = world; } +Input::InputManager* ScriptEngine::input() const { return m_impl->m_input; } + void ScriptEngine::setInput(Input::InputManager* input) { m_impl->m_input = input; } diff --git a/src/caffeine/script/ScriptEngine.hpp b/src/caffeine/script/ScriptEngine.hpp index 6795b8ce..feafbb6f 100644 --- a/src/caffeine/script/ScriptEngine.hpp +++ b/src/caffeine/script/ScriptEngine.hpp @@ -32,6 +32,7 @@ class ScriptEngine { void shutdown(); void setWorld(ECS::World* world); void setInput(Input::InputManager* input); + Input::InputManager* input() const; void setSearchRoot(const std::string& root); struct ExposedVar { diff --git a/src/caffeine/script/ScriptInputNames.hpp b/src/caffeine/script/ScriptInputNames.hpp new file mode 100644 index 00000000..0a2be9cb --- /dev/null +++ b/src/caffeine/script/ScriptInputNames.hpp @@ -0,0 +1,17 @@ +#pragma once + +#include "input/InputManager.hpp" + +#include + +namespace Caffeine::Script { + +/// Name tables shared by every scripting language, so Lua and Dryad accept the same +/// strings ("Space", "Horizontal", "Jump"). Each returns false for an unknown name. +bool lookupScriptKey(const std::string& name, Input::Key& out); +bool lookupScriptAxis(const std::string& name, Input::Axis& out); +bool lookupScriptAction(const std::string& name, Input::Action& out); +/// 1 = left, 2 = middle, 3 = right. +bool lookupScriptMouseButton(unsigned index, Input::MouseButton& out); + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/ScriptSystem.cpp b/src/caffeine/script/ScriptSystem.cpp index 7d73da6f..a8bc3ff2 100644 --- a/src/caffeine/script/ScriptSystem.cpp +++ b/src/caffeine/script/ScriptSystem.cpp @@ -123,6 +123,7 @@ void ScriptSystem::processLuaScripts(ECS::World& world, f32 dt) { void ScriptSystem::processDryadScripts(ECS::World& world, f32 dt) { if (!m_dryad) return; m_dryad->setWorld(&world); + if (m_engine) m_dryad->setInput(m_engine->input()); if (!m_projectRoot.empty()) m_dryad->setSearchRoot(m_projectRoot); ECS::ComponentQuery q; diff --git a/tests/test_dryad_host.cpp b/tests/test_dryad_host.cpp index 1959d422..510d3aaa 100644 --- a/tests/test_dryad_host.cpp +++ b/tests/test_dryad_host.cpp @@ -8,6 +8,8 @@ #include "../src/caffeine/ecs/MeshComponents.hpp" #include "../src/caffeine/ecs/World.hpp" #include "../src/caffeine/physics/PhysicsComponents3D.hpp" +#include "../src/caffeine/input/InputManager.hpp" +#include "../src/caffeine/runtime/PlayClock.hpp" #include #include @@ -189,4 +191,42 @@ TEST_CASE("Dryad reads and writes any reflected component", "[dryad][component]" std::remove(path.c_str()); } +TEST_CASE("Dryad natives read input, time and the world", "[dryad][runtime]") { + const std::string path = "dryad_host_runtime.dyd"; + { + std::ofstream out(path); + out << "function onUpdate(entity, dt) {\n" + << " let x = 0;\n" + << " if (caffeine_input_key_down(\"Space\")) { x = x + 1; }\n" + << " if (caffeine_input_key_down(\"Nope\")) { x = x + 100; }\n" + << " let spawned = caffeine_world_create(\"Spawned\");\n" + << " if (caffeine_world_is_alive(spawned)) { x = x + 10; }\n" + << " caffeine_world_destroy(spawned);\n" + << " if (!caffeine_world_is_alive(spawned)) { x = x + 20; }\n" + << " caffeine_set_position(entity, x, caffeine_world_distance(entity, entity), caffeine_time_scale());\n" + << "}\n"; + } + + ECS::World world; + Input::InputManager input; + DryadHost host; + host.setWorld(&world); + host.setInput(&input); + ECS::Entity entity = world.create("DryadRuntime"); + entity.getOrAdd().position = Vec3(0, 0, 0); + input.injectKeyDown(Input::Key::Space); + + Runtime::PlayClock::instance().setTimeScale(1.0f); + REQUIRE(host.load(path)); + std::string err; + REQUIRE(host.call(path, "onUpdate", entity, 0.016f, &err)); + + auto* pos = entity.get(); + REQUIRE(pos != nullptr); + REQUIRE(pos->position.x == 31.0f); // Space + alive + destroyed, unknown key ignored + REQUIRE(pos->position.y == 0.0f); + REQUIRE(pos->position.z == 1.0f); + std::remove(path.c_str()); +} + #endif diff --git a/tests/test_script.cpp b/tests/test_script.cpp index 8acfbeb6..3dafe8fc 100644 --- a/tests/test_script.cpp +++ b/tests/test_script.cpp @@ -337,6 +337,37 @@ TEST_CASE("Math vec2 length and normalize work", "[script]") { REQUIRE(pos->position.y == Approx(3.0f / 5.0f)); // 0.6 } +// ============================================================================ +// 10b. Math binding — 3D vectors and scalar helpers +// ============================================================================ + +TEST_CASE("Math supports 3D vectors and scalar helpers", "[script][math]") { + ScriptTestFixture fix; + + const char* code = R"( + function onCreate(eid) + local m = caffeine.math + local c = m.cross(m.vec3(1, 0, 0), m.vec3(0, 1, 0)) -- (0, 0, 1) + local d = m.distance(m.vec3(0, 0, 0), m.vec3(2, 3, 6)) -- 7 + local r = m.remap(5, 0, 10, 100, 200) -- 150 + local a = m.approach(0, 10, 3) -- 3 + local flat = m.add(m.vec2(1, 2), m.vec2(3, 4)) -- stays 2D + local keep2d = (flat.z == nil) and 1 or 0 + caffeine.world.setTransform(eid, {x = c.z + d, y = r + a, z = keep2d}) + end + )"; + REQUIRE(fix.engine.loadString(code, "math_3d.lua")); + + auto entity = fix.world.create("Test"); + REQUIRE(fix.engine.callOnCreate("math_3d.lua", entity)); + + auto* t = entity.get(); + REQUIRE(t != nullptr); + REQUIRE(t->position.x == Approx(8.0f)); + REQUIRE(t->position.y == Approx(153.0f)); + REQUIRE(t->position.z == Approx(1.0f)); +} + // ============================================================================ // 11. Math binding — add, sub, dot, scale // ============================================================================ From 78cda61dde697bdf72ff5e2539a944044e67e005 Mon Sep 17 00:00:00 2001 From: lyeepedro Date: Thu, 19 Nov 2026 17:18:10 +0000 Subject: [PATCH 2/6] Scripting: API registry, entity/hierarchy/random/physics3d, Script component, catalog - Single API registry (src/caffeine/script/api) with a coverage test and a docs generator - ScriptComponent: enabled, order, properties, isolated - Dryad natives through defineNative; time/input/world/entity/hierarchy/random/physics3d - PhysicsWorld3D raycast/forces/velocity; runtime now steps PhysicsSystem3D - ScriptCatalog: group/subgroup classification of scripts Co-Authored-By: Claude Sonnet 5.5 --- CMakeLists.txt | 4 + apps/runtime/main.cpp | 4 + caffeine-website | 2 +- scripts/generate-script-api-docs.py | 139 +++ src/caffeine/physics/PhysicsWorld3D.cpp | 58 ++ src/caffeine/physics/PhysicsWorld3D.hpp | 16 + src/caffeine/scene/ComponentReflection.cpp | 6 +- src/caffeine/scene/EditorSceneSerializer.cpp | 17 + .../script/DryadComponentBindings.cpp | 29 +- src/caffeine/script/DryadHost.cpp | 59 +- src/caffeine/script/DryadHost.hpp | 12 + src/caffeine/script/DryadNatives.hpp | 25 + .../script/DryadPhysics3DBindings.cpp | 70 ++ src/caffeine/script/DryadRuntimeBindings.cpp | 45 +- src/caffeine/script/DryadWorldBindings.cpp | 50 ++ src/caffeine/script/Physics3DBindings.cpp | 42 + src/caffeine/script/ScriptCatalog.hpp | 162 ++++ src/caffeine/script/ScriptEngine.cpp | 31 + src/caffeine/script/ScriptEngine.hpp | 9 + src/caffeine/script/ScriptProperties.hpp | 54 ++ src/caffeine/script/ScriptSystem.cpp | 42 +- src/caffeine/script/ScriptTypes.hpp | 10 + src/caffeine/script/ScriptWorldApi.hpp | 133 +++ src/caffeine/script/WorldApiBindings.cpp | 43 + src/caffeine/script/api/animation.json | 242 ++++++ src/caffeine/script/api/assets.json | 38 + src/caffeine/script/api/component.json | 483 +++++++++++ src/caffeine/script/api/core.json | 34 + src/caffeine/script/api/debug.json | 70 ++ src/caffeine/script/api/draw2d.json | 195 +++++ src/caffeine/script/api/effects.json | 232 +++++ src/caffeine/script/api/entity.json | 132 +++ src/caffeine/script/api/events.json | 86 ++ src/caffeine/script/api/forwardrender.json | 188 +++++ src/caffeine/script/api/gameState.json | 94 +++ src/caffeine/script/api/hierarchy.json | 154 ++++ src/caffeine/script/api/input.json | 216 +++++ src/caffeine/script/api/map.json | 38 + src/caffeine/script/api/math.json | 678 +++++++++++++++ src/caffeine/script/api/native.json | 72 ++ src/caffeine/script/api/navigation.json | 180 ++++ src/caffeine/script/api/particles.json | 40 + src/caffeine/script/api/physics3d.json | 237 ++++++ src/caffeine/script/api/pick.json | 211 +++++ src/caffeine/script/api/postprocess.json | 799 ++++++++++++++++++ src/caffeine/script/api/procedural.json | 467 ++++++++++ src/caffeine/script/api/random.json | 127 +++ src/caffeine/script/api/time.json | 190 +++++ src/caffeine/script/api/ui.json | 200 +++++ src/caffeine/script/api/world.json | 681 +++++++++++++++ tests/CMakeLists.txt | 1 + tests/test_dryad_host.cpp | 52 ++ tests/test_script.cpp | 261 ++++++ 53 files changed, 7404 insertions(+), 56 deletions(-) create mode 100644 scripts/generate-script-api-docs.py create mode 100644 src/caffeine/script/DryadNatives.hpp create mode 100644 src/caffeine/script/DryadPhysics3DBindings.cpp create mode 100644 src/caffeine/script/DryadWorldBindings.cpp create mode 100644 src/caffeine/script/Physics3DBindings.cpp create mode 100644 src/caffeine/script/ScriptCatalog.hpp create mode 100644 src/caffeine/script/ScriptProperties.hpp create mode 100644 src/caffeine/script/ScriptWorldApi.hpp create mode 100644 src/caffeine/script/WorldApiBindings.cpp create mode 100644 src/caffeine/script/api/animation.json create mode 100644 src/caffeine/script/api/assets.json create mode 100644 src/caffeine/script/api/component.json create mode 100644 src/caffeine/script/api/core.json create mode 100644 src/caffeine/script/api/debug.json create mode 100644 src/caffeine/script/api/draw2d.json create mode 100644 src/caffeine/script/api/effects.json create mode 100644 src/caffeine/script/api/entity.json create mode 100644 src/caffeine/script/api/events.json create mode 100644 src/caffeine/script/api/forwardrender.json create mode 100644 src/caffeine/script/api/gameState.json create mode 100644 src/caffeine/script/api/hierarchy.json create mode 100644 src/caffeine/script/api/input.json create mode 100644 src/caffeine/script/api/map.json create mode 100644 src/caffeine/script/api/math.json create mode 100644 src/caffeine/script/api/native.json create mode 100644 src/caffeine/script/api/navigation.json create mode 100644 src/caffeine/script/api/particles.json create mode 100644 src/caffeine/script/api/physics3d.json create mode 100644 src/caffeine/script/api/pick.json create mode 100644 src/caffeine/script/api/postprocess.json create mode 100644 src/caffeine/script/api/procedural.json create mode 100644 src/caffeine/script/api/random.json create mode 100644 src/caffeine/script/api/time.json create mode 100644 src/caffeine/script/api/ui.json create mode 100644 src/caffeine/script/api/world.json diff --git a/CMakeLists.txt b/CMakeLists.txt index d23300ee..48a26ff5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -462,12 +462,16 @@ if(CAFFEINE_ENABLE_SCRIPTING) src/caffeine/script/RuntimeScriptBindings.cpp src/caffeine/script/AssetTextLoader.cpp src/caffeine/script/NativeModuleHost.cpp + src/caffeine/script/WorldApiBindings.cpp + src/caffeine/script/Physics3DBindings.cpp ) if(DRYAD_AVAILABLE) target_sources(caffeine-core PRIVATE src/caffeine/script/DryadHost.cpp src/caffeine/script/DryadComponentBindings.cpp src/caffeine/script/DryadRuntimeBindings.cpp + src/caffeine/script/DryadWorldBindings.cpp + src/caffeine/script/DryadPhysics3DBindings.cpp src/caffeine/script/nodes/NodeGraph.cpp src/caffeine/script/nodes/NodeCatalog.cpp src/caffeine/script/nodes/NodeEmitter.cpp diff --git a/apps/runtime/main.cpp b/apps/runtime/main.cpp index 8d18a598..3dde95f7 100644 --- a/apps/runtime/main.cpp +++ b/apps/runtime/main.cpp @@ -6,6 +6,7 @@ #include "events/Events.hpp" #include "input/InputManager.hpp" #include "physics/PhysicsSystem2D.hpp" +#include "physics/PhysicsSystem3D.hpp" #include "script/ScriptEngine.hpp" #include "script/ScriptSystem.hpp" #include "scene/NaturalFluidSystem.hpp" @@ -461,6 +462,7 @@ int main(int argc, char** argv) { Caffeine::Input::InputManager input; Caffeine::Events::EventBus eventBus; Caffeine::Physics2D::PhysicsSystem2D physics(&eventBus); + Caffeine::Physics3D::PhysicsSystem3D physics3d; Caffeine::Animation::AnimationSystem animation; Caffeine::UI::UISystem uiSystem(&eventBus); Caffeine::Script::ScriptEngine scriptEngine; @@ -469,6 +471,7 @@ int main(int argc, char** argv) { scriptParams.input = &input; scriptParams.events = &eventBus; scriptParams.ui = &uiSystem; + scriptParams.physics3d = &physics3d.world(); const bool scriptsReady = scriptEngine.init(scriptParams); scriptEngine.setSearchRoot(buildRoot.string()); Caffeine::Script::ScriptSystem scriptSystem(scriptsReady ? &scriptEngine : nullptr, &eventBus); @@ -549,6 +552,7 @@ int main(int argc, char** argv) { Caffeine::Scene::tickNaturalFluids(world, dt, false); Caffeine::Navigation::updateNavigation(world, dt); physics.onUpdate(world, dt); + physics3d.onUpdate(world, dt); if (scriptsReady) { scriptEngine.setWorld(&world); scriptEngine.setInput(&input); diff --git a/caffeine-website b/caffeine-website index 1efa6aa0..84e4ec5b 160000 --- a/caffeine-website +++ b/caffeine-website @@ -1 +1 @@ -Subproject commit 1efa6aa0f392797c9ff013ef5fab4c20d0b9f18b +Subproject commit 84e4ec5bda7817b104136f82f30d502a92be4387 diff --git a/scripts/generate-script-api-docs.py b/scripts/generate-script-api-docs.py new file mode 100644 index 00000000..9cc0a1dc --- /dev/null +++ b/scripts/generate-script-api-docs.py @@ -0,0 +1,139 @@ +#!/usr/bin/env python3 +"""Generate the scripting API reference (EN/PT) from src/caffeine/script/api/*.json. + + python3 scripts/generate-script-api-docs.py # write caffeine-website pages + python3 scripts/generate-script-api-docs.py --check # validate the registry only + +The registry is the single source of truth: tests/test_script.cpp fails when a binding is missing +from it or a documented name no longer exists. Every function needs `en`, `pt`, `signature` and an +`example`; this script refuses to generate otherwise. +""" +import html +import json +import sys +from datetime import date +from pathlib import Path + +ROOT = Path(__file__).resolve().parent.parent +API = ROOT / "src/caffeine/script/api" +SITE = ROOT / "caffeine-website/content" +GROUP_ORDER = ["Core", "Input", "Physics", "Game", "World", "Rendering", "UI"] +T = { + "en": dict(api="Scripting API reference", lede="Every function the engine exposes to scripts, grouped like a standard library. Lua names are shown as `caffeine..`; the Dryad native is shown when one exists.", + ns="Namespace", fn="Functions", lua="Lua", dryad="Dryad", params="Parameters", returns="Returns", none="none", + name="Name", type="Type", desc="Description", example="Example", only_dryad="Dryad only", last="Last updated", + how="How this page is built", howtext="Generated from the API registry in the engine repository; a test fails when a binding is undocumented. Do not edit by hand.", + group="Group", total="functions across", nss="namespaces", back="All namespaces", missing="Lua: not available"), + "pt": dict(api="Referência da API de scripting", lede="Todas as funções que o engine expõe aos scripts, agrupadas como uma biblioteca padrão. Os nomes Lua aparecem como `caffeine..`; o native Dryad é mostrado quando existe.", + ns="Namespace", fn="Funções", lua="Lua", dryad="Dryad", params="Parâmetros", returns="Devolve", none="nada", + name="Nome", type="Tipo", desc="Descrição", example="Exemplo", only_dryad="Só Dryad", last="Última atualização", + how="Como esta página é construída", howtext="Gerada a partir do registo da API no repositório do engine; um teste falha quando um binding não está documentado. Não editar à mão.", + group="Grupo", total="funções em", nss="namespaces", back="Todos os namespaces", missing="Lua: indisponível"), +} + + +def load(): + data = [] + errors = [] + for f in sorted(API.glob("*.json")): + d = json.loads(f.read_text(encoding="utf-8")) + for fn in d["functions"]: + for k in ("name", "signature", "en", "pt", "example"): + if not fn.get(k): + errors.append(f"{f.name}: {fn.get('name')}: missing {k}") + if not (fn.get("lua") or fn.get("dryad")): + errors.append(f"{f.name}: {fn.get('name')}: neither lua nor dryad") + for p in fn.get("params", []): + if not (p.get("en") and p.get("pt")): + errors.append(f"{f.name}: {fn['name']}: param {p.get('name')} lacks en/pt") + for k in ("title", "summary"): + if not (d[k].get("en") and d[k].get("pt")): + errors.append(f"{f.name}: {k} lacks en/pt") + data.append(d) + return data, errors + + +def esc(s): + return html.escape(s, quote=False) + + +def md_inline(s): + return s.replace("|", "\\|") + + +def ns_page(d, lang): + t = T[lang] + n_lua = sum(1 for f in d["functions"] if f.get("lua")) + n_dry = sum(1 for f in d["functions"] if f.get("dryad")) + out = [f"# {d['title'][lang]}", "", + '
', + ' Reference', + f' {esc(d["group"])}', + f' {t["last"]}: ', + f' Lua {n_lua} · Dryad {n_dry}', "
", "", + f'

{esc(d["summary"][lang])}

', "", + f'[{t["back"]}](index.md)', ""] + if d.get("lua"): + out += [f"Namespace: `{d['lua']}`" + (f" · Dryad prefix: `{d['dryad_prefix']}`" if d.get("dryad_prefix") else ""), ""] + for f in d["functions"]: + title = f["signature"].split("(")[0] if f.get("lua") else (f.get("dryad") or f["name"]) + out += [f"## {title}", ""] + names = [] + if f.get("lua"): + names.append(f"{t['lua']}: `{f['lua']}`") + else: + names.append(t["missing"]) + if f.get("dryad"): + names.append(f"{t['dryad']}: `{f['dryad']}`") + out += [" · ".join(names), "", "```", f["signature"], "```", "", f[lang], ""] + params = f.get("params", []) + if params: + out += [f"", f"", ""] + for p in params: + out.append(f"") + out += ["", "
{t['params']}{t['type']}{t['desc']}
{esc(p['name'])}{esc(p['type'])}{esc(p[lang])}
", ""] + r = f.get("returns") + out += [f"**{t['returns']}:** " + (f"`{r['type']}`. {r[lang]}" if r else t["none"]), ""] + out += [f"**{t['example']}**", "", "```" + ("lua" if f.get("lua") else "dryad"), f["example"], "```", ""] + return "\n".join(out) + + +def index_page(data, lang): + t = T[lang] + total = sum(len(d["functions"]) for d in data) + out = [f"# {t['api']}", "", + '
', ' Reference', + f' {t["last"]}: ', "
", "", + f'

{esc(t["lede"].replace("`", ""))}

', "", + f"{total} {t['total']} {len(data)} {t['nss']}.", ""] + groups = {} + for d in data: + groups.setdefault(d["group"], []).append(d) + for g in sorted(groups, key=lambda x: GROUP_ORDER.index(x) if x in GROUP_ORDER else 99): + out += [f"## {g}", "", f"| {t['ns']} | {t['fn']} | {t['desc']} |", "|---|---|---|"] + for d in sorted(groups[g], key=lambda x: x["namespace"]): + out.append(f"| [{d['title'][lang]}]({d['namespace']}.md) | {len(d['functions'])} | {md_inline(d['summary'][lang])} |") + out.append("") + out += [f"## {t['how']}", "", t["howtext"], ""] + return "\n".join(out) + + +def main(): + data, errors = load() + if errors: + print("\n".join(errors)) + return 1 + if "--check" in sys.argv: + print(f"ok: {sum(len(d['functions']) for d in data)} functions, {len(data)} namespaces") + return 0 + for lang in ("en", "pt"): + out = SITE / lang / "docs/scripting/api" + out.mkdir(parents=True, exist_ok=True) + (out / "index.md").write_text(index_page(data, lang), encoding="utf-8") + for d in data: + (out / f"{d['namespace']}.md").write_text(ns_page(d, lang), encoding="utf-8") + print(f"generated {len(data)} namespaces x 2 languages") + return 0 + + +sys.exit(main()) diff --git a/src/caffeine/physics/PhysicsWorld3D.cpp b/src/caffeine/physics/PhysicsWorld3D.cpp index 387720d3..03c24709 100644 --- a/src/caffeine/physics/PhysicsWorld3D.cpp +++ b/src/caffeine/physics/PhysicsWorld3D.cpp @@ -234,6 +234,59 @@ bool PhysicsWorld3D::stateOf(u32 entityId, BodyState& out) const { bool PhysicsWorld3D::isAvailable() const { return true; } +PhysicsWorld3D::RayHit PhysicsWorld3D::raycast(const Vec3& origin, const Vec3& direction, + f32 maxDistance) const { + RayHit out; + const f32 len = std::sqrt(direction.x * direction.x + direction.y * direction.y + direction.z * direction.z); + if (len < 1e-6f || maxDistance <= 0.0f) return out; + const btVector3 from(origin.x, origin.y, origin.z); + const btVector3 to = from + btVector3(direction.x, direction.y, direction.z) * (maxDistance / len); + btCollisionWorld::ClosestRayResultCallback cb(from, to); + m_impl->world->rayTest(from, to, cb); + if (!cb.hasHit()) return out; + const auto* body = btRigidBody::upcast(cb.m_collisionObject); + if (!body) return out; + if (body->getCollisionFlags() & btCollisionObject::CF_NO_CONTACT_RESPONSE) return out; // trigger + out.hit = true; + out.entityId = static_cast(body->getUserIndex()); + out.point = Vec3(cb.m_hitPointWorld.x(), cb.m_hitPointWorld.y(), cb.m_hitPointWorld.z()); + out.normal = Vec3(cb.m_hitNormalWorld.x(), cb.m_hitNormalWorld.y(), cb.m_hitNormalWorld.z()); + out.distance = cb.m_closestHitFraction * maxDistance; + return out; +} + +bool PhysicsWorld3D::addForce(u32 entityId, const Vec3& force) { + auto it = m_impl->bodies.find(entityId); + if (it == m_impl->bodies.end() || it->second.type != BodyType3D::Dynamic) return false; + it->second.body->activate(true); + it->second.body->applyCentralForce(btVector3(force.x, force.y, force.z)); + return true; +} + +bool PhysicsWorld3D::addImpulse(u32 entityId, const Vec3& impulse) { + auto it = m_impl->bodies.find(entityId); + if (it == m_impl->bodies.end() || it->second.type != BodyType3D::Dynamic) return false; + it->second.body->activate(true); + it->second.body->applyCentralImpulse(btVector3(impulse.x, impulse.y, impulse.z)); + return true; +} + +bool PhysicsWorld3D::setLinearVelocity(u32 entityId, const Vec3& velocity) { + auto it = m_impl->bodies.find(entityId); + if (it == m_impl->bodies.end() || it->second.type != BodyType3D::Dynamic) return false; + it->second.body->activate(true); + it->second.body->setLinearVelocity(btVector3(velocity.x, velocity.y, velocity.z)); + return true; +} + +bool PhysicsWorld3D::linearVelocity(u32 entityId, Vec3& out) const { + auto it = m_impl->bodies.find(entityId); + if (it == m_impl->bodies.end() || it->second.type != BodyType3D::Dynamic) return false; + const btVector3 v = it->second.body->getLinearVelocity(); + out = Vec3(v.x(), v.y(), v.z()); + return true; +} + #else struct PhysicsWorld3D::Impl {}; @@ -248,6 +301,11 @@ void PhysicsWorld3D::removeMissing(const std::vector&) {} void PhysicsWorld3D::step(f32) {} bool PhysicsWorld3D::stateOf(u32, BodyState&) const { return false; } bool PhysicsWorld3D::isAvailable() const { return false; } +PhysicsWorld3D::RayHit PhysicsWorld3D::raycast(const Vec3&, const Vec3&, f32) const { return {}; } +bool PhysicsWorld3D::addForce(u32, const Vec3&) { return false; } +bool PhysicsWorld3D::addImpulse(u32, const Vec3&) { return false; } +bool PhysicsWorld3D::setLinearVelocity(u32, const Vec3&) { return false; } +bool PhysicsWorld3D::linearVelocity(u32, Vec3&) const { return false; } #endif diff --git a/src/caffeine/physics/PhysicsWorld3D.hpp b/src/caffeine/physics/PhysicsWorld3D.hpp index ab1981e4..0f5a5bdd 100644 --- a/src/caffeine/physics/PhysicsWorld3D.hpp +++ b/src/caffeine/physics/PhysicsWorld3D.hpp @@ -24,6 +24,22 @@ class PhysicsWorld3D { bool stateOf(u32 entityId, BodyState& out) const; bool isAvailable() const; + struct RayHit { + bool hit = false; + u32 entityId = 0; + Vec3 point{}; + Vec3 normal{0.0f, 1.0f, 0.0f}; + f32 distance = 0.0f; + }; + /// First body along the ray (`direction` need not be normalised). Triggers are ignored. + RayHit raycast(const Vec3& origin, const Vec3& direction, f32 maxDistance) const; + /// Force and impulse act on dynamic bodies only and wake them. Return false for unknown + /// or non-dynamic bodies. + bool addForce(u32 entityId, const Vec3& force); + bool addImpulse(u32 entityId, const Vec3& impulse); + bool setLinearVelocity(u32 entityId, const Vec3& velocity); + bool linearVelocity(u32 entityId, Vec3& out) const; + private: struct Impl; Impl* m_impl = nullptr; diff --git a/src/caffeine/scene/ComponentReflection.cpp b/src/caffeine/scene/ComponentReflection.cpp index 78f992d6..a8e9d6d3 100644 --- a/src/caffeine/scene/ComponentReflection.cpp +++ b/src/caffeine/scene/ComponentReflection.cpp @@ -424,7 +424,11 @@ const std::vector& componentRegistry() { stringField("Material", &ECS::MeshFilterComponent::customMaterialPath), f32Field("Shininess", &ECS::MeshFilterComponent::shininess, 0.0f, 1024.0f, 1.0f)}), component(12, "Script", - {stringField("Script", &Caffeine::Script::ScriptComponent::scriptPath)}), + {stringField("Script", &Caffeine::Script::ScriptComponent::scriptPath), + boolField("Enabled", &Caffeine::Script::ScriptComponent::enabled), + i32Field("Order", &Caffeine::Script::ScriptComponent::executionOrder, -1000.0f, 1000.0f), + stringField("Properties", &Caffeine::Script::ScriptComponent::properties), + boolField("Isolated", &Caffeine::Script::ScriptComponent::isolated)}), #include "scene/ComponentReflectionGenerated.entries.inc" }; return registry; diff --git a/src/caffeine/scene/EditorSceneSerializer.cpp b/src/caffeine/scene/EditorSceneSerializer.cpp index 71c6ac46..f0b7ee40 100644 --- a/src/caffeine/scene/EditorSceneSerializer.cpp +++ b/src/caffeine/scene/EditorSceneSerializer.cpp @@ -340,6 +340,11 @@ void SceneSerializer::collectScriptComponents( m_world.forEach(q, [&](ECS::Entity e, Script::ScriptComponent& sc) { std::vector data; IO::appendString(data, sc.scriptPath); + // Trailing fields (absent in older scenes): enabled, order, properties. + IO::appendU8(data, sc.enabled ? 1 : 0); + IO::appendI32(data, sc.executionOrder); + IO::appendString(data, sc.properties); + IO::appendU8(data, sc.isolated ? 1 : 0); entries.push_back({e.id(), std::move(data)}); }); } @@ -2165,6 +2170,18 @@ bool SceneSerializer::applyScriptComponent(ECS::Entity e, const u8* data, u32 si if (!IO::readString(cursor, end, path)) return false; auto& sc = m_world.add(e); sc.scriptPath = std::move(path); + // Older scenes end here and keep the defaults. + u8 enabled = 1; + i32 order = 0; + std::string properties; + if (cursor < end && IO::readU8(cursor, end, enabled) && IO::readI32(cursor, end, order) && + IO::readString(cursor, end, properties)) { + sc.enabled = enabled != 0; + sc.executionOrder = order; + sc.properties = std::move(properties); + u8 isolated = 0; + if (IO::readU8(cursor, end, isolated)) sc.isolated = isolated != 0; + } return true; } diff --git a/src/caffeine/script/DryadComponentBindings.cpp b/src/caffeine/script/DryadComponentBindings.cpp index 378a4433..c01c4682 100644 --- a/src/caffeine/script/DryadComponentBindings.cpp +++ b/src/caffeine/script/DryadComponentBindings.cpp @@ -21,6 +21,7 @@ #include "scene/ComponentAccess.hpp" #include "scene/ComponentReflection.hpp" +#include "script/DryadNatives.hpp" #include "dryad/compiler/interpreter.h" #include "dryad/runtime/value.h" @@ -124,7 +125,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return true; }; - interp.define_native("caffeine_component_list", [](const Args&) -> dryad::Value { + defineNative(interp, "caffeine_component_list", [](const Args&) -> dryad::Value { dryad::Value result = dryad::Value::create_array(); for (const R::ComponentDesc& desc : R::registry()) { result.array_push(dryad::Value(std::string(desc.name))); @@ -132,7 +133,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return result; }); - interp.define_native("caffeine_component_names", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_names", [=](const Args& args) -> dryad::Value { ECS::Entity entity; dryad::Value result = dryad::Value::create_array(); if (!entityOf(args, entity)) return result; @@ -142,7 +143,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return result; }); - interp.define_native("caffeine_component_has", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_has", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity)) return dryad::Value(false); std::string error; @@ -151,7 +152,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return dryad::Value(has); }); - interp.define_native("caffeine_component_add", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_add", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity)) return dryad::Value(false); std::string error; @@ -160,7 +161,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return dryad::Value(ok); }); - interp.define_native("caffeine_component_remove", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_remove", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity)) return dryad::Value(false); std::string error; @@ -169,7 +170,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return dryad::Value(ok); }); - interp.define_native("caffeine_component_get", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_get", [=](const Args& args) -> dryad::Value { ECS::Entity entity; dryad::Value result; if (!entityOf(args, entity)) return result; @@ -187,7 +188,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return result; }); - interp.define_native("caffeine_component_get_field", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_get_field", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity)) return dryad::Value(); const R::ComponentDesc* desc = R::findByName(textOf(args, 1)); @@ -227,7 +228,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return true; }; - interp.define_native("caffeine_component_set_field", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_set_field", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity) || args.size() < 4) return dryad::Value(false); const R::ComponentDesc* desc = R::findByName(textOf(args, 1)); @@ -247,7 +248,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return dryad::Value(write(entity, *desc, *field, args[3])); }); - interp.define_native("caffeine_component_get_number", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_get_number", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity)) return dryad::Value(); double out = 0.0; @@ -271,7 +272,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return dryad::Value(out); }); - interp.define_native("caffeine_component_set_number", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_set_number", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity) || args.size() < 4) return dryad::Value(false); std::string error; @@ -285,7 +286,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return dryad::Value(ok); }); - interp.define_native("caffeine_component_set_vec", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_set_vec", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity) || args.size() < 5) return dryad::Value(false); bool ok = true; @@ -298,7 +299,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return dryad::Value(ok); }); - interp.define_native("caffeine_component_get_text", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_get_text", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity)) return dryad::Value(); std::string out, error; @@ -309,7 +310,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return dryad::Value(out); }); - interp.define_native("caffeine_component_set_text", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_set_text", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity) || args.size() < 4) return dryad::Value(false); std::string error; @@ -318,7 +319,7 @@ void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { return dryad::Value(ok); }); - interp.define_native("caffeine_component_set", [=](const Args& args) -> dryad::Value { + defineNative(interp, "caffeine_component_set", [=](const Args& args) -> dryad::Value { ECS::Entity entity; if (!entityOf(args, entity) || args.size() < 3 || !args[2].is_object()) return dryad::Value(false); const R::ComponentDesc* desc = R::findByName(textOf(args, 1)); diff --git a/src/caffeine/script/DryadHost.cpp b/src/caffeine/script/DryadHost.cpp index d7da9040..119d0c28 100644 --- a/src/caffeine/script/DryadHost.cpp +++ b/src/caffeine/script/DryadHost.cpp @@ -7,9 +7,12 @@ #include "ecs/World.hpp" #include "dryad/common/utils.h" +#include "script/DryadNatives.hpp" +#include "physics/PhysicsWorld3D.hpp" #include "dryad/compiler/interpreter.h" #include "dryad/runtime/value.h" +#include #include #include #include @@ -21,6 +24,8 @@ namespace Caffeine::Script { void bindComponentNatives(dryad::Interpreter& interp, ECS::World** worldPtr); void bindRuntimeNatives(dryad::Interpreter& interp, ECS::World** worldPtr, Input::InputManager** inputPtr); +void bindWorldApiNatives(dryad::Interpreter& interp, ECS::World** worldPtr); +void bindPhysics3DNatives(dryad::Interpreter& interp, Physics3D::PhysicsWorld3D** physicsPtr); namespace { @@ -120,6 +125,7 @@ struct DryadHost::Impl { ECS::World* world = nullptr; Input::InputManager* input = nullptr; + Physics3D::PhysicsWorld3D* physics3d = nullptr; std::string searchRoot; std::unordered_map sessions; @@ -133,7 +139,7 @@ struct DryadHost::Impl { return dryad::Value(static_cast(v)); }; - interp.define_native("caffeine_set_position", + defineNative(interp, "caffeine_set_position", [worldPtr](const std::vector& args) -> dryad::Value { if (args.size() < 4) return dryad::Value(); const auto id = static_cast(asNumber(args[0])); @@ -143,7 +149,7 @@ struct DryadHost::Impl { static_cast(asNumber(args[3])))); return dryad::Value(); }); - interp.define_native("caffeine_translate", + defineNative(interp, "caffeine_translate", [worldPtr](const std::vector& args) -> dryad::Value { if (args.size() < 4) return dryad::Value(); const auto id = static_cast(asNumber(args[0])); @@ -154,13 +160,13 @@ struct DryadHost::Impl { writePosition(*worldPtr, id, position); return dryad::Value(); }); - interp.define_native("caffeine_get_position_x", + defineNative(interp, "caffeine_get_position_x", [readAxis](const std::vector& args) -> dryad::Value { return readAxis(args, 0); }); - interp.define_native("caffeine_get_position_y", + defineNative(interp, "caffeine_get_position_y", [readAxis](const std::vector& args) -> dryad::Value { return readAxis(args, 1); }); - interp.define_native("caffeine_get_position_z", + defineNative(interp, "caffeine_get_position_z", [readAxis](const std::vector& args) -> dryad::Value { return readAxis(args, 2); }); - interp.define_native("caffeine_set_scale", + defineNative(interp, "caffeine_set_scale", [worldPtr](const std::vector& args) -> dryad::Value { if (args.size() < 4) return dryad::Value(); const auto id = static_cast(asNumber(args[0])); @@ -178,19 +184,19 @@ struct DryadHost::Impl { const f32 v = axis == 0 ? scale.x : (axis == 1 ? scale.y : scale.z); return dryad::Value(static_cast(v)); }; - interp.define_native("caffeine_get_scale_x", + defineNative(interp, "caffeine_get_scale_x", [readScaleAxis](const std::vector& args) -> dryad::Value { return readScaleAxis(args, 0); }); - interp.define_native("caffeine_get_scale_y", + defineNative(interp, "caffeine_get_scale_y", [readScaleAxis](const std::vector& args) -> dryad::Value { return readScaleAxis(args, 1); }); - interp.define_native("caffeine_get_scale_z", + defineNative(interp, "caffeine_get_scale_z", [readScaleAxis](const std::vector& args) -> dryad::Value { return readScaleAxis(args, 2); }); - interp.define_native("caffeine_log", + defineNative(interp, "caffeine_log", [](const std::vector& args) -> dryad::Value { if (!args.empty()) { CF_INFO("Dryad", "%s", args[0].to_string().c_str()); @@ -199,6 +205,8 @@ struct DryadHost::Impl { }); bindComponentNatives(interp, worldPtr); bindRuntimeNatives(interp, worldPtr, &input); + bindWorldApiNatives(interp, worldPtr); + bindPhysics3DNatives(interp, &physics3d); interp.set_network_allowed(false); if (const char* stdlib = std::getenv("DRYAD_STDLIB_DIR")) { interp.set_stdlib_root(stdlib); @@ -219,6 +227,8 @@ void DryadHost::setWorld(ECS::World* world) { m_impl->world = world; } void DryadHost::setInput(Input::InputManager* input) { m_impl->input = input; } +void DryadHost::setPhysics3D(Physics3D::PhysicsWorld3D* physics) { m_impl->physics3d = physics; } + void DryadHost::setSearchRoot(const std::string& root) { m_impl->searchRoot = root; } std::string DryadHost::searchRoot() const { return m_impl->searchRoot; } @@ -273,6 +283,35 @@ bool DryadHost::load(const std::string& path, std::string* outError) { } } +std::vector DryadHost::nativeNames() { + std::vector names; + dryadNativeRecorder() = &names; + { + DryadHost host; + dryad::Interpreter interp; + host.m_impl->bindHost(interp); + } + dryadNativeRecorder() = nullptr; + std::sort(names.begin(), names.end()); + names.erase(std::unique(names.begin(), names.end()), names.end()); + return names; +} + +bool DryadHost::setProperty(const std::string& path, const ScriptEngine::ExposedVar& var) { + auto it = m_impl->sessions.find(resolvePath(path)); + if (it == m_impl->sessions.end()) return false; + dryad::Value value; + switch (var.kind) { + case ScriptEngine::ExposedVar::Kind::Boolean: value = dryad::Value(var.boolean); break; + case ScriptEngine::ExposedVar::Kind::Number: value = dryad::Value(var.number); break; + case ScriptEngine::ExposedVar::Kind::String: value = dryad::Value(var.string); break; + } + auto env = it->second.interp->global_env(); + if (env->has(var.name)) env->set(var.name, value); + else env->define(var.name, value); + return true; +} + bool DryadHost::reloadIfChanged(const std::string& path, std::string* outError) { const std::string resolved = resolvePath(path); auto it = m_impl->sessions.find(resolved); diff --git a/src/caffeine/script/DryadHost.hpp b/src/caffeine/script/DryadHost.hpp index a6cebd74..00f728a6 100644 --- a/src/caffeine/script/DryadHost.hpp +++ b/src/caffeine/script/DryadHost.hpp @@ -1,12 +1,15 @@ #pragma once #include "core/Types.hpp" +#include "script/ScriptEngine.hpp" #include "ecs/Entity.hpp" #include +#include namespace Caffeine::ECS { class World; } namespace Caffeine::Input { class InputManager; } +namespace Caffeine::Physics3D { class PhysicsWorld3D; } namespace Caffeine::Script { @@ -22,6 +25,8 @@ class DryadHost { void setWorld(ECS::World* world); /// Optional; without it the `caffeine_input_*` natives report no input. void setInput(Input::InputManager* input); + /// Optional; enables the `caffeine_physics3d_*` natives. + void setPhysics3D(Physics3D::PhysicsWorld3D* physics); /// Project root used to resolve relative script paths (for example /// `scripts/player.dyd`). Relative paths that already exist from the @@ -32,6 +37,9 @@ class DryadHost { /// Resolves a project-relative `.dyd` path to a filesystem path. std::string resolvePath(const std::string& path) const; + /// Every native the host defines, sorted. Used by the API documentation check. + static std::vector nativeNames(); + bool load(const std::string& path, std::string* outError = nullptr); bool isLoaded(const std::string& path) const; @@ -39,6 +47,10 @@ class DryadHost { /// Returns true when the script was reloaded. bool reloadIfChanged(const std::string& path, std::string* outError = nullptr); + /// Sets (or defines) a global of the loaded script, used for `ScriptComponent::properties`. + /// Returns false when the script is not loaded. + bool setProperty(const std::string& path, const ScriptEngine::ExposedVar& var); + /// Missing hook functions are a no-op and return true. bool call(const std::string& path, const char* function, ECS::Entity entity, f32 dt, std::string* outError = nullptr); diff --git a/src/caffeine/script/DryadNatives.hpp b/src/caffeine/script/DryadNatives.hpp new file mode 100644 index 00000000..d1da1937 --- /dev/null +++ b/src/caffeine/script/DryadNatives.hpp @@ -0,0 +1,25 @@ +#pragma once + +#include "dryad/compiler/interpreter.h" +#include "dryad/runtime/value.h" + +#include +#include +#include + +namespace Caffeine::Script { + +/// Every Dryad native is registered through this, so the set of natives can be listed +/// (`DryadHost::nativeNames()`) and checked against the documented API. +inline std::vector*& dryadNativeRecorder() { + static thread_local std::vector* recorder = nullptr; + return recorder; +} + +inline void defineNative(dryad::Interpreter& interp, const std::string& name, + std::function&)> fn) { + if (auto* rec = dryadNativeRecorder()) rec->push_back(name); + interp.define_native(name, std::move(fn)); +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/DryadPhysics3DBindings.cpp b/src/caffeine/script/DryadPhysics3DBindings.cpp new file mode 100644 index 00000000..2d897c12 --- /dev/null +++ b/src/caffeine/script/DryadPhysics3DBindings.cpp @@ -0,0 +1,70 @@ +// Dryad natives for `caffeine.physics3d`; same behaviour as the Lua functions. +// caffeine_physics3d_available() / _set_gravity(x, y, z) +// caffeine_physics3d_raycast(ox, oy, oz, dx, dy, dz, maxDistance) -> {entity, x, y, z, nx, ny, nz, distance} or null +// caffeine_physics3d_add_force / _add_impulse / _set_velocity (entity, x, y, z) -> bool +// caffeine_physics3d_velocity(entity) -> {x, y, z} or null + +#include "physics/PhysicsWorld3D.hpp" +#include "script/DryadNatives.hpp" + +namespace Caffeine::Script { + +using Args = std::vector; + +namespace { +double num(const Args& a, size_t i) { + if (i >= a.size()) return 0.0; + if (a[i].is_integer()) return static_cast(a[i].as_integer()); + if (a[i].is_float()) return a[i].as_float(); + return 0.0; +} +Vec3 vec(const Args& a, size_t i) { + return Vec3(static_cast(num(a, i)), static_cast(num(a, i + 1)), static_cast(num(a, i + 2))); +} +} // namespace + +void bindPhysics3DNatives(dryad::Interpreter& interp, Physics3D::PhysicsWorld3D** physicsPtr) { + auto physics = [physicsPtr]() -> Physics3D::PhysicsWorld3D* { return physicsPtr ? *physicsPtr : nullptr; }; + + defineNative(interp, "caffeine_physics3d_available", [=](const Args&) { + auto* p = physics(); + return dryad::Value(p && p->isAvailable()); }); + defineNative(interp, "caffeine_physics3d_set_gravity", [=](const Args& a) { + if (auto* p = physics()) p->setGravity(vec(a, 0)); + return dryad::Value(); }); + defineNative(interp, "caffeine_physics3d_raycast", [=](const Args& a) { + auto* p = physics(); + if (!p) return dryad::Value(); + const auto hit = p->raycast(vec(a, 0), vec(a, 3), static_cast(num(a, 6))); + if (!hit.hit) return dryad::Value(); + dryad::Value o = dryad::Value::create_object(); + o.object_set("entity", dryad::Value(static_cast(hit.entityId))); + o.object_set("x", dryad::Value(static_cast(hit.point.x))); + o.object_set("y", dryad::Value(static_cast(hit.point.y))); + o.object_set("z", dryad::Value(static_cast(hit.point.z))); + o.object_set("nx", dryad::Value(static_cast(hit.normal.x))); + o.object_set("ny", dryad::Value(static_cast(hit.normal.y))); + o.object_set("nz", dryad::Value(static_cast(hit.normal.z))); + o.object_set("distance", dryad::Value(static_cast(hit.distance))); + return o; }); + defineNative(interp, "caffeine_physics3d_add_force", [=](const Args& a) { + auto* p = physics(); + return dryad::Value(p && p->addForce(static_cast(num(a, 0)), vec(a, 1))); }); + defineNative(interp, "caffeine_physics3d_add_impulse", [=](const Args& a) { + auto* p = physics(); + return dryad::Value(p && p->addImpulse(static_cast(num(a, 0)), vec(a, 1))); }); + defineNative(interp, "caffeine_physics3d_set_velocity", [=](const Args& a) { + auto* p = physics(); + return dryad::Value(p && p->setLinearVelocity(static_cast(num(a, 0)), vec(a, 1))); }); + defineNative(interp, "caffeine_physics3d_velocity", [=](const Args& a) { + auto* p = physics(); + Vec3 v; + if (!p || !p->linearVelocity(static_cast(num(a, 0)), v)) return dryad::Value(); + dryad::Value o = dryad::Value::create_object(); + o.object_set("x", dryad::Value(static_cast(v.x))); + o.object_set("y", dryad::Value(static_cast(v.y))); + o.object_set("z", dryad::Value(static_cast(v.z))); + return o; }); +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/DryadRuntimeBindings.cpp b/src/caffeine/script/DryadRuntimeBindings.cpp index 8a1e899b..f6f183a3 100644 --- a/src/caffeine/script/DryadRuntimeBindings.cpp +++ b/src/caffeine/script/DryadRuntimeBindings.cpp @@ -20,6 +20,7 @@ #include "runtime/PlayClock.hpp" #include "script/ScriptInputNames.hpp" +#include "script/DryadNatives.hpp" #include "dryad/compiler/interpreter.h" #include "dryad/runtime/value.h" @@ -54,83 +55,83 @@ bool positionOf(ECS::World* world, u32 id, Vec3& out) { void bindRuntimeNatives(dryad::Interpreter& interp, ECS::World** worldPtr, Input::InputManager** inputPtr) { - interp.define_native("caffeine_time_delta", [](const Args&) { + defineNative(interp, "caffeine_time_delta", [](const Args&) { return dryad::Value(static_cast(Runtime::PlayClock::instance().deltaTime())); }); - interp.define_native("caffeine_time_unscaled_delta", [](const Args&) { + defineNative(interp, "caffeine_time_unscaled_delta", [](const Args&) { return dryad::Value(static_cast(Runtime::PlayClock::instance().unscaledDeltaTime())); }); - interp.define_native("caffeine_time_total", [](const Args&) { + defineNative(interp, "caffeine_time_total", [](const Args&) { return dryad::Value(static_cast(Runtime::PlayClock::instance().time())); }); - interp.define_native("caffeine_time_fixed_delta", [](const Args&) { + defineNative(interp, "caffeine_time_fixed_delta", [](const Args&) { return dryad::Value(static_cast(Runtime::PlayClock::instance().fixedDeltaTime())); }); - interp.define_native("caffeine_time_scale", [](const Args&) { + defineNative(interp, "caffeine_time_scale", [](const Args&) { return dryad::Value(static_cast(Runtime::PlayClock::instance().timeScale())); }); - interp.define_native("caffeine_time_frame", [](const Args&) { + defineNative(interp, "caffeine_time_frame", [](const Args&) { return dryad::Value(static_cast(Runtime::PlayClock::instance().frame())); }); - interp.define_native("caffeine_time_set_scale", [](const Args& a) { + defineNative(interp, "caffeine_time_set_scale", [](const Args& a) { if (!a.empty()) Runtime::PlayClock::instance().setTimeScale(static_cast(numberOf(a[0]))); return dryad::Value(); }); - interp.define_native("caffeine_time_paused", [](const Args&) { + defineNative(interp, "caffeine_time_paused", [](const Args&) { return dryad::Value(Runtime::PlayClock::instance().paused()); }); - interp.define_native("caffeine_time_set_paused", [](const Args& a) { + defineNative(interp, "caffeine_time_set_paused", [](const Args& a) { if (!a.empty()) Runtime::PlayClock::instance().setPaused(numberOf(a[0]) != 0.0); return dryad::Value(); }); auto input = [inputPtr]() -> Input::InputManager* { return inputPtr ? *inputPtr : nullptr; }; - interp.define_native("caffeine_input_key_down", [input](const Args& a) { + defineNative(interp, "caffeine_input_key_down", [input](const Args& a) { Input::Key key; Input::InputManager* im = input(); return dryad::Value(im && lookupScriptKey(textOf(a, 0), key) && im->isKeyDown(key)); }); - interp.define_native("caffeine_input_axis", [input](const Args& a) { + defineNative(interp, "caffeine_input_axis", [input](const Args& a) { Input::Axis axis; Input::InputManager* im = input(); if (!im || !lookupScriptAxis(textOf(a, 0), axis)) return dryad::Value(0.0); return dryad::Value(static_cast(im->axisState(axis).value)); }); - interp.define_native("caffeine_input_action_down", [input](const Args& a) { + defineNative(interp, "caffeine_input_action_down", [input](const Args& a) { Input::Action action; Input::InputManager* im = input(); return dryad::Value(im && lookupScriptAction(textOf(a, 0), action) && im->actionState(action).pressed); }); - interp.define_native("caffeine_input_action_pressed", [input](const Args& a) { + defineNative(interp, "caffeine_input_action_pressed", [input](const Args& a) { Input::Action action; Input::InputManager* im = input(); return dryad::Value(im && lookupScriptAction(textOf(a, 0), action) && im->actionState(action).justPressed); }); - interp.define_native("caffeine_input_mouse_x", [input](const Args&) { + defineNative(interp, "caffeine_input_mouse_x", [input](const Args&) { Input::InputManager* im = input(); return dryad::Value(im ? static_cast(im->mousePosition().x) : 0.0); }); - interp.define_native("caffeine_input_mouse_y", [input](const Args&) { + defineNative(interp, "caffeine_input_mouse_y", [input](const Args&) { Input::InputManager* im = input(); return dryad::Value(im ? static_cast(im->mousePosition().y) : 0.0); }); - interp.define_native("caffeine_input_mouse_dx", [input](const Args&) { + defineNative(interp, "caffeine_input_mouse_dx", [input](const Args&) { Input::InputManager* im = input(); return dryad::Value(im ? static_cast(im->mouseDelta().x) : 0.0); }); - interp.define_native("caffeine_input_mouse_dy", [input](const Args&) { + defineNative(interp, "caffeine_input_mouse_dy", [input](const Args&) { Input::InputManager* im = input(); return dryad::Value(im ? static_cast(im->mouseDelta().y) : 0.0); }); - interp.define_native("caffeine_input_mouse_down", [input](const Args& a) { + defineNative(interp, "caffeine_input_mouse_down", [input](const Args& a) { Input::MouseButton button; Input::InputManager* im = input(); const auto index = a.empty() ? 0u : static_cast(numberOf(a[0])); return dryad::Value(im && lookupScriptMouseButton(index, button) && im->isMouseButtonDown(button)); }); - interp.define_native("caffeine_world_create", [worldPtr](const Args& a) { + defineNative(interp, "caffeine_world_create", [worldPtr](const Args& a) { ECS::World* world = worldPtr ? *worldPtr : nullptr; if (!world) return dryad::Value(static_cast(0)); const std::string name = textOf(a, 0); ECS::Entity e = world->create(name.empty() ? "DryadEntity" : name.c_str()); return dryad::Value(static_cast(e.id())); }); - interp.define_native("caffeine_world_destroy", [worldPtr](const Args& a) { + defineNative(interp, "caffeine_world_destroy", [worldPtr](const Args& a) { ECS::World* world = worldPtr ? *worldPtr : nullptr; if (world && !a.empty()) { ECS::Entity e(static_cast(numberOf(a[0])), world); if (e.isValid() && world->isEntityAlive(e)) world->destroy(e); } return dryad::Value(); }); - interp.define_native("caffeine_world_is_alive", [worldPtr](const Args& a) { + defineNative(interp, "caffeine_world_is_alive", [worldPtr](const Args& a) { ECS::World* world = worldPtr ? *worldPtr : nullptr; if (!world || a.empty()) return dryad::Value(false); ECS::Entity e(static_cast(numberOf(a[0])), world); return dryad::Value(e.isValid() && world->isEntityAlive(e)); }); - interp.define_native("caffeine_world_distance", [worldPtr](const Args& a) { + defineNative(interp, "caffeine_world_distance", [worldPtr](const Args& a) { ECS::World* world = worldPtr ? *worldPtr : nullptr; Vec3 p, q; if (a.size() < 2 || !positionOf(world, static_cast(numberOf(a[0])), p) || diff --git a/src/caffeine/script/DryadWorldBindings.cpp b/src/caffeine/script/DryadWorldBindings.cpp new file mode 100644 index 00000000..65bd4dd5 --- /dev/null +++ b/src/caffeine/script/DryadWorldBindings.cpp @@ -0,0 +1,50 @@ +// Dryad natives for entity names, hierarchy and random numbers. They call the same +// implementations as Lua's `caffeine.entity`, `caffeine.hierarchy` and `caffeine.random`. + +#include "script/DryadNatives.hpp" +#include "script/ScriptWorldApi.hpp" + +namespace Caffeine::Script { + +namespace W = WorldApi; +using Args = std::vector; + +namespace { +double num(const Args& a, size_t i) { + if (i >= a.size()) return 0.0; + if (a[i].is_integer()) return static_cast(a[i].as_integer()); + if (a[i].is_float()) return a[i].as_float(); + return 0.0; +} +std::string str(const Args& a, size_t i) { return i < a.size() && a[i].is_string() ? a[i].as_string() : std::string(); } +dryad::Value ids(const std::vector& v) { + dryad::Value arr = dryad::Value::create_array(); + for (u32 id : v) arr.array_push(dryad::Value(static_cast(id))); + return arr; +} +dryad::Value id(u32 v) { return dryad::Value(static_cast(v)); } +} // namespace + +void bindWorldApiNatives(dryad::Interpreter& interp, ECS::World** worldPtr) { + auto world = [worldPtr]() -> ECS::World* { return worldPtr ? *worldPtr : nullptr; }; + + defineNative(interp, "caffeine_entity_name", [=](const Args& a) { return dryad::Value(W::nameOf(world(), static_cast(num(a, 0)))); }); + defineNative(interp, "caffeine_entity_set_name", [=](const Args& a) { return dryad::Value(W::setName(world(), static_cast(num(a, 0)), str(a, 1))); }); + defineNative(interp, "caffeine_entity_find", [=](const Args& a) { return id(W::find(world(), str(a, 0))); }); + defineNative(interp, "caffeine_entity_find_all", [=](const Args& a) { return ids(W::findAll(world(), str(a, 0))); }); + + defineNative(interp, "caffeine_hierarchy_parent", [=](const Args& a) { return id(W::parentOf(world(), static_cast(num(a, 0)))); }); + defineNative(interp, "caffeine_hierarchy_set_parent", [=](const Args& a) { return dryad::Value(W::setParent(world(), static_cast(num(a, 0)), static_cast(num(a, 1)))); }); + defineNative(interp, "caffeine_hierarchy_detach", [=](const Args& a) { return dryad::Value(W::setParent(world(), static_cast(num(a, 0)), 0)); }); + defineNative(interp, "caffeine_hierarchy_children", [=](const Args& a) { return ids(W::childrenOf(world(), static_cast(num(a, 0)))); }); + defineNative(interp, "caffeine_hierarchy_child_count", [=](const Args& a) { return id(static_cast(W::childrenOf(world(), static_cast(num(a, 0))).size())); }); + defineNative(interp, "caffeine_hierarchy_root", [=](const Args& a) { return id(W::rootOf(world(), static_cast(num(a, 0)))); }); + + defineNative(interp, "caffeine_random_set_seed", [](const Args& a) { W::Rng::instance().seed(static_cast(num(a, 0))); return dryad::Value(); }); + defineNative(interp, "caffeine_random_value", [](const Args&) { return dryad::Value(W::Rng::instance().next01()); }); + defineNative(interp, "caffeine_random_range", [](const Args& a) { return dryad::Value(W::Rng::instance().range(num(a, 0), num(a, 1))); }); + defineNative(interp, "caffeine_random_int", [](const Args& a) { return dryad::Value(static_cast(W::Rng::instance().integer(static_cast(num(a, 0)), static_cast(num(a, 1))))); }); + defineNative(interp, "caffeine_random_chance", [](const Args& a) { return dryad::Value(W::Rng::instance().chance(num(a, 0))); }); +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/Physics3DBindings.cpp b/src/caffeine/script/Physics3DBindings.cpp new file mode 100644 index 00000000..87b75231 --- /dev/null +++ b/src/caffeine/script/Physics3DBindings.cpp @@ -0,0 +1,42 @@ +#include "physics/PhysicsWorld3D.hpp" + +#include + +namespace Caffeine::Script { + +namespace P = Physics3D; + +// `caffeine.physics3d`: queries and forces on the Bullet world. Everything is a safe no-op +// (false / nil) when the host runs without a 3D physics world. +void registerPhysics3DBindings(sol::state& lua, P::PhysicsWorld3D** physicsPtr) { + auto physics = [physicsPtr]() -> P::PhysicsWorld3D* { return physicsPtr ? *physicsPtr : nullptr; }; + sol::table t = lua["caffeine"]["physics3d"].get_or_create(); + + t["isAvailable"] = [physics]() { auto* p = physics(); return p && p->isAvailable(); }; + t["setGravity"] = [physics](f32 x, f32 y, f32 z) { if (auto* p = physics()) p->setGravity(Vec3(x, y, z)); }; + t["raycast"] = [physics, &lua](f32 ox, f32 oy, f32 oz, f32 dx, f32 dy, f32 dz, f32 maxDistance) -> sol::object { + auto* p = physics(); + if (!p) return sol::nil; + const auto hit = p->raycast(Vec3(ox, oy, oz), Vec3(dx, dy, dz), maxDistance); + if (!hit.hit) return sol::nil; + sol::table r = lua.create_table(); + r["entity"] = hit.entityId; + r["x"] = hit.point.x; r["y"] = hit.point.y; r["z"] = hit.point.z; + r["nx"] = hit.normal.x; r["ny"] = hit.normal.y; r["nz"] = hit.normal.z; + r["distance"] = hit.distance; + return r; + }; + t["addForce"] = [physics](u32 e, f32 x, f32 y, f32 z) { auto* p = physics(); return p && p->addForce(e, Vec3(x, y, z)); }; + t["addImpulse"] = [physics](u32 e, f32 x, f32 y, f32 z) { auto* p = physics(); return p && p->addImpulse(e, Vec3(x, y, z)); }; + t["setVelocity"] = [physics](u32 e, f32 x, f32 y, f32 z) { auto* p = physics(); return p && p->setLinearVelocity(e, Vec3(x, y, z)); }; + t["velocity"] = [physics, &lua](u32 e) -> sol::object { + auto* p = physics(); + Vec3 v; + if (!p || !p->linearVelocity(e, v)) return sol::nil; + sol::table r = lua.create_table(); + r["x"] = v.x; r["y"] = v.y; r["z"] = v.z; + return r; + }; +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/ScriptCatalog.hpp b/src/caffeine/script/ScriptCatalog.hpp new file mode 100644 index 00000000..fd8ba0f9 --- /dev/null +++ b/src/caffeine/script/ScriptCatalog.hpp @@ -0,0 +1,162 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace Caffeine::Script { + +/// Classification data read from the top of a script. Header comment lines (`--`, `//` or `#`) +/// within the first 40 lines carry the tags: +/// +/// -- @group Gameplay/Combat/Melee groups and subgroups, separated by `/` +/// -- @name Sword swing display name (default: the file name) +/// -- @description Swings and hits. +/// -- @tags weapon, player +/// +/// Without `@group` the group is the folder path under `scripts/` (`scripts/Gameplay/AI/x.lua` +/// is group `Gameplay/AI`), so a folder tree is already a group tree. +struct ScriptMeta { + std::string path; ///< project-relative, forward slashes + std::string name; + std::string description; + std::vector group; ///< {"Gameplay", "Combat", "Melee"}; empty = Ungrouped + std::vector tags; +}; + +inline std::vector splitScriptGroup(const std::string& text) { + std::vector parts; + std::string cur; + auto flush = [&] { + const auto b = cur.find_first_not_of(" \t"); + if (b != std::string::npos) parts.push_back(cur.substr(b, cur.find_last_not_of(" \t") - b + 1)); + cur.clear(); + }; + for (char c : text) { + if (c == '/' || c == '\\' || c == '>') flush(); + else cur += c; + } + flush(); + return parts; +} + +inline ScriptMeta parseScriptMeta(const std::string& path, const std::string& source) { + ScriptMeta meta; + meta.path = path; + std::istringstream in(source); + std::string line; + bool hasGroup = false; + for (int i = 0; i < 40 && std::getline(in, line); ++i) { + const auto b = line.find_first_not_of(" \t"); + if (b == std::string::npos) continue; + size_t p = b; + if (line.compare(p, 2, "--") == 0 || line.compare(p, 2, "//") == 0) p += 2; + else if (line[p] == '#') p += 1; + else continue; + p = line.find_first_not_of(" \t", p); + if (p == std::string::npos || line[p] != '@') continue; + const auto sp = line.find_first_of(" \t", p); + const std::string key = line.substr(p + 1, sp == std::string::npos ? std::string::npos : sp - p - 1); + std::string value = sp == std::string::npos ? "" : line.substr(sp + 1); + while (!value.empty() && (value.back() == '\r' || value.back() == ' ')) value.pop_back(); + const auto vb = value.find_first_not_of(" \t"); + value = vb == std::string::npos ? "" : value.substr(vb); + if (key == "group") { meta.group = splitScriptGroup(value); hasGroup = true; } + else if (key == "name") meta.name = value; + else if (key == "description") meta.description = value; + else if (key == "tags") { + std::string tag; + std::istringstream ts(value); + while (std::getline(ts, tag, ',')) { + const auto tb = tag.find_first_not_of(" \t"); + if (tb != std::string::npos) meta.tags.push_back(tag.substr(tb, tag.find_last_not_of(" \t") - tb + 1)); + } + } + } + if (!hasGroup) { + // Folder tree under scripts/ is the default group. + std::vector folders = splitScriptGroup(path); + if (!folders.empty()) folders.pop_back(); // file name + if (!folders.empty() && folders.front() == "scripts") folders.erase(folders.begin()); + meta.group = std::move(folders); + } + if (meta.name.empty()) { + meta.name = std::filesystem::path(path).stem().string(); + } + return meta; +} + +struct ScriptGroupNode { + std::string name; + std::map> children; ///< sorted by name + std::vector scripts; ///< sorted by name + + const ScriptGroupNode* find(const std::string& slashPath) const { + const ScriptGroupNode* node = this; + for (const auto& part : splitScriptGroup(slashPath)) { + auto it = node->children.find(part); + if (it == node->children.end()) return nullptr; + node = it->second.get(); + } + return node; + } + /// Scripts in this group and every subgroup. + size_t totalScripts() const { + size_t n = scripts.size(); + for (const auto& [_, c] : children) n += c->totalScripts(); + return n; + } +}; + +/// Builds the group tree. Scripts without a group go to a top-level node named "Ungrouped". +inline ScriptGroupNode buildScriptTree(const std::vector& metas) { + ScriptGroupNode root; + for (const auto& meta : metas) { + ScriptGroupNode* node = &root; + const std::vector group = + meta.group.empty() ? std::vector{"Ungrouped"} : meta.group; + for (const auto& part : group) { + auto& child = node->children[part]; + if (!child) { child = std::make_unique(); child->name = part; } + node = child.get(); + } + node->scripts.push_back(meta); + } + std::function sortNode = [&](ScriptGroupNode& n) { + std::sort(n.scripts.begin(), n.scripts.end(), + [](const ScriptMeta& a, const ScriptMeta& b) { return a.name < b.name; }); + for (auto& [_, c] : n.children) sortNode(*c); + }; + sortNode(root); + return root; +} + +/// Scans `` for `.lua` and `.dyd` files under `scripts/` and reads their headers. +inline std::vector scanScripts(const std::string& projectRoot) { + namespace fs = std::filesystem; + std::vector out; + std::error_code ec; + const fs::path root(projectRoot); + const fs::path scripts = root / "scripts"; + if (!fs::exists(scripts, ec)) return out; + for (fs::recursive_directory_iterator it(scripts, ec), end; !ec && it != end; it.increment(ec)) { + if (!it->is_regular_file(ec)) continue; + const std::string ext = it->path().extension().string(); + if (ext != ".lua" && ext != ".dyd") continue; + std::ifstream f(it->path()); + std::stringstream ss; + ss << f.rdbuf(); + std::string rel = fs::relative(it->path(), root, ec).generic_string(); + out.push_back(parseScriptMeta(rel, ss.str())); + } + std::sort(out.begin(), out.end(), [](const ScriptMeta& a, const ScriptMeta& b) { return a.path < b.path; }); + return out; +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/ScriptEngine.cpp b/src/caffeine/script/ScriptEngine.cpp index d53f061a..af06ae7d 100644 --- a/src/caffeine/script/ScriptEngine.cpp +++ b/src/caffeine/script/ScriptEngine.cpp @@ -1,5 +1,6 @@ #include "script/ScriptEngine.hpp" #include "script/ScriptInputNames.hpp" +#include "physics/PhysicsWorld3D.hpp" #include "script/NativeModuleHost.hpp" #include "events/Events.hpp" #include "script/ScriptTypes.hpp" @@ -19,7 +20,9 @@ #include "containers/Vector.hpp" #include +#include #include +#include namespace Caffeine::Script { @@ -30,6 +33,8 @@ void registerAnimationScriptBindings(sol::state& lua, ECS::World** worldPtr); void registerEffectScriptBindings(sol::state& lua, ECS::World** worldPtr); void registerNavigationScriptBindings(sol::state& lua, ECS::World** worldPtr); void registerComponentScriptBindings(sol::state& lua, ECS::World** worldPtr); +void registerWorldApiBindings(sol::state& lua, ECS::World** worldPtr); +void registerPhysics3DBindings(sol::state& lua, Physics3D::PhysicsWorld3D** physicsPtr); sol::table makePostProcessScriptHandle(sol::state_view lua, ECS::World** worldPtr, u32 entityId); // ============================================================================ @@ -43,6 +48,7 @@ struct ScriptEngine::Impl { Input::InputManager* m_input = nullptr; Events::EventBus* m_events = nullptr; UI::UISystem* m_ui = nullptr; + Physics3D::PhysicsWorld3D* m_physics3d = nullptr; HashMap m_envs; std::string m_searchRoot; @@ -658,6 +664,7 @@ bool ScriptEngine::init(const InitParams& params) { m_impl->m_input = params.input; m_impl->m_events = params.events; m_impl->m_ui = params.ui; + m_impl->m_physics3d = params.physics3d; auto& lua = m_impl->m_lua; @@ -747,6 +754,8 @@ bool ScriptEngine::init(const InitParams& params) { registerEffectScriptBindings(lua, &m_impl->m_world); registerNavigationScriptBindings(lua, &m_impl->m_world); registerComponentScriptBindings(lua, &m_impl->m_world); + registerWorldApiBindings(lua, &m_impl->m_world); + registerPhysics3DBindings(lua, &m_impl->m_physics3d); registerRuntimeScriptBindings( lua, &m_impl->m_world, &m_impl->m_input, &m_impl->m_ui, &m_impl->m_assetText, @@ -831,6 +840,10 @@ void ScriptEngine::setWorld(ECS::World* world) { Input::InputManager* ScriptEngine::input() const { return m_impl->m_input; } +void ScriptEngine::setPhysics3D(Physics3D::PhysicsWorld3D* physics) { m_impl->m_physics3d = physics; } + +Physics3D::PhysicsWorld3D* ScriptEngine::physics3d() const { return m_impl->m_physics3d; } + void ScriptEngine::setInput(Input::InputManager* input) { m_impl->m_input = input; } @@ -894,6 +907,24 @@ bool ScriptEngine::setExposedVar(const std::string& path, const ExposedVar& var) return true; } +std::vector ScriptEngine::apiNames() { + std::vector out; + std::function walk = + [&](const sol::table& t, const std::string& prefix, int depth) { + if (depth > 4) return; + t.for_each([&](const sol::object& k, const sol::object& v) { + if (!k.is()) return; + const std::string name = prefix + "." + k.as(); + if (v.is()) out.push_back(name); + else if (v.is()) walk(v.as(), name, depth + 1); + }); + }; + sol::table root = m_impl->m_lua["caffeine"]; + walk(root, "caffeine", 0); + std::sort(out.begin(), out.end()); + return out; +} + bool ScriptEngine::loadScript(const std::string& path, std::string* outError) { return loadScriptAs(path, path, outError); } diff --git a/src/caffeine/script/ScriptEngine.hpp b/src/caffeine/script/ScriptEngine.hpp index feafbb6f..7746883c 100644 --- a/src/caffeine/script/ScriptEngine.hpp +++ b/src/caffeine/script/ScriptEngine.hpp @@ -10,6 +10,7 @@ namespace Caffeine { namespace Input { class InputManager; } } namespace Caffeine { namespace Events { class EventBus; } } namespace Caffeine { namespace UI { class UISystem; } } +namespace Caffeine { namespace Physics3D { class PhysicsWorld3D; } } namespace Caffeine::Script { @@ -26,6 +27,8 @@ class ScriptEngine { Input::InputManager* input = nullptr; Events::EventBus* events = nullptr; UI::UISystem* ui = nullptr; + /// Optional: enables `caffeine.physics3d` (raycast, forces, velocity). + Physics3D::PhysicsWorld3D* physics3d = nullptr; }; bool init(const InitParams& params); @@ -33,6 +36,8 @@ class ScriptEngine { void setWorld(ECS::World* world); void setInput(Input::InputManager* input); Input::InputManager* input() const; + void setPhysics3D(Physics3D::PhysicsWorld3D* physics); + Physics3D::PhysicsWorld3D* physics3d() const; void setSearchRoot(const std::string& root); struct ExposedVar { @@ -46,6 +51,10 @@ class ScriptEngine { std::vector listExposedVars(const std::string& path); bool setExposedVar(const std::string& path, const ExposedVar& var); + /// Dotted names of everything under the `caffeine` table (`caffeine.world.create`, ...), + /// sorted, with functions only. Used by the API documentation check. + std::vector apiNames(); + bool loadScript(const std::string& path, std::string* outError = nullptr); /// Loads `path` into its own environment stored under `key`, so one file can back /// several roles (e.g. a gameplay script and a post-process driver) without sharing state. diff --git a/src/caffeine/script/ScriptProperties.hpp b/src/caffeine/script/ScriptProperties.hpp new file mode 100644 index 00000000..1538dba4 --- /dev/null +++ b/src/caffeine/script/ScriptProperties.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include "script/ScriptEngine.hpp" + +#include +#include +#include + +namespace Caffeine::Script { + +/// Per-entity overrides for a script's exposed variables, stored as text: +/// `speed=4.5; god=true; label=hello` (separators: `;` or newline). A value is a boolean when it +/// is `true`/`false`, a number when it parses fully, and a string otherwise. Malformed entries +/// (no `=`, empty name) are skipped. +inline std::vector parseScriptProperties(const std::string& text) { + std::vector out; + auto trim = [](std::string s) { + const char* ws = " \t\r"; + const auto b = s.find_first_not_of(ws); + if (b == std::string::npos) return std::string(); + return s.substr(b, s.find_last_not_of(ws) - b + 1); + }; + size_t start = 0; + while (start <= text.size()) { + size_t end = text.find_first_of(";\n", start); + if (end == std::string::npos) end = text.size(); + const std::string entry = text.substr(start, end - start); + start = end + 1; + const auto eq = entry.find('='); + if (eq == std::string::npos) continue; + ScriptEngine::ExposedVar var; + var.name = trim(entry.substr(0, eq)); + const std::string value = trim(entry.substr(eq + 1)); + if (var.name.empty()) continue; + if (value == "true" || value == "false") { + var.kind = ScriptEngine::ExposedVar::Kind::Boolean; + var.boolean = value == "true"; + } else { + char* parsed = nullptr; + const double number = std::strtod(value.c_str(), &parsed); + if (!value.empty() && parsed && *parsed == '\0') { + var.kind = ScriptEngine::ExposedVar::Kind::Number; + var.number = number; + } else { + var.kind = ScriptEngine::ExposedVar::Kind::String; + var.string = value; + } + } + out.push_back(std::move(var)); + } + return out; +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/ScriptSystem.cpp b/src/caffeine/script/ScriptSystem.cpp index a8bc3ff2..5d49dcb1 100644 --- a/src/caffeine/script/ScriptSystem.cpp +++ b/src/caffeine/script/ScriptSystem.cpp @@ -1,5 +1,8 @@ #include "script/ScriptSystem.hpp" #include "script/DryadHost.hpp" +#include "script/ScriptProperties.hpp" + +#include #include "script/ScriptTypes.hpp" #include "script/CppScript.hpp" #include "ecs/World.hpp" @@ -65,14 +68,19 @@ void ScriptSystem::processLuaScripts(ECS::World& world, f32 dt) { struct ScriptEntry { u32 entityId; std::string scriptPath; + i32 order; + std::string properties; + bool isolated; }; Vector entries; world.forEach(q, [&entries](ECS::Entity entity, ScriptComponent& sc) { - if (sc.scriptPath.empty() || isDryadScriptPath(sc.scriptPath)) return; - entries.pushBack({entity.id(), sc.scriptPath}); + if (!sc.enabled || sc.scriptPath.empty() || isDryadScriptPath(sc.scriptPath)) return; + entries.pushBack({entity.id(), sc.scriptPath, sc.executionOrder, sc.properties, sc.isolated}); }); + std::stable_sort(entries.begin(), entries.end(), + [](const ScriptEntry& a, const ScriptEntry& b) { return a.order < b.order; }); if (entries.empty()) { if (!m_warnedNoLua) { @@ -86,13 +94,16 @@ void ScriptSystem::processLuaScripts(ECS::World& world, f32 dt) { ECS::Entity entity(entry.entityId, &world); if (!entity.isValid()) continue; - const std::string& path = entry.scriptPath; + // An isolated entity runs its own copy of the script (private globals). + const std::string& filePath = entry.scriptPath; + const std::string path = + entry.isolated ? filePath + "#" + std::to_string(entity.id()) : filePath; if (!m_engine->isLoaded(path)) { std::string err; - if (!m_engine->loadScript(path, &err)) { + if (!m_engine->loadScriptAs(path, filePath, &err)) { CF_ERROR("Script", "Failed to load %s: %s", - path.c_str(), err.c_str()); + filePath.c_str(), err.c_str()); continue; } } @@ -105,6 +116,10 @@ void ScriptSystem::processLuaScripts(ECS::World& world, f32 dt) { } } + for (const auto& var : parseScriptProperties(entry.properties)) { + m_engine->setExposedVar(path, var); + } + if (isNew) { m_engine->callOnCreate(path, entity); m_initializedLua.pushBack(entity); @@ -123,7 +138,10 @@ void ScriptSystem::processLuaScripts(ECS::World& world, f32 dt) { void ScriptSystem::processDryadScripts(ECS::World& world, f32 dt) { if (!m_dryad) return; m_dryad->setWorld(&world); - if (m_engine) m_dryad->setInput(m_engine->input()); + if (m_engine) { + m_dryad->setInput(m_engine->input()); + m_dryad->setPhysics3D(m_engine->physics3d()); + } if (!m_projectRoot.empty()) m_dryad->setSearchRoot(m_projectRoot); ECS::ComponentQuery q; @@ -132,14 +150,18 @@ void ScriptSystem::processDryadScripts(ECS::World& world, f32 dt) { struct ScriptEntry { u32 entityId; std::string scriptPath; + i32 order; + std::string properties; }; Vector entries; world.forEach(q, [&entries](ECS::Entity entity, ScriptComponent& sc) { - if (!isDryadScriptPath(sc.scriptPath)) return; - entries.pushBack({entity.id(), sc.scriptPath}); + if (!sc.enabled || !isDryadScriptPath(sc.scriptPath)) return; + entries.pushBack({entity.id(), sc.scriptPath, sc.executionOrder, sc.properties}); }); + std::stable_sort(entries.begin(), entries.end(), + [](const ScriptEntry& a, const ScriptEntry& b) { return a.order < b.order; }); for (auto& entry : entries) { ECS::Entity entity(entry.entityId, &world); @@ -158,6 +180,10 @@ void ScriptSystem::processDryadScripts(ECS::World& world, f32 dt) { } } + for (const auto& var : parseScriptProperties(entry.properties)) { + m_dryad->setProperty(path, var); + } + bool alreadyInitialized = false; for (usize i = 0; i < m_initializedDryad.size(); ++i) { if (m_initializedDryad[i].id() == entity.id()) { diff --git a/src/caffeine/script/ScriptTypes.hpp b/src/caffeine/script/ScriptTypes.hpp index 0f5b2c3d..fc5077d1 100644 --- a/src/caffeine/script/ScriptTypes.hpp +++ b/src/caffeine/script/ScriptTypes.hpp @@ -12,6 +12,16 @@ namespace Caffeine::Script { struct ScriptComponent { std::string scriptPath; + /// A disabled script is skipped by the ScriptSystem (no hooks, no initialisation). + bool enabled = true; + /// Lower runs first within a frame; ties keep entity order. + i32 executionOrder = 0; + /// Per-entity overrides of the script's exposed variables: `speed=4.5; god=true`. + /// See ScriptProperties.hpp. Applied before every hook of this entity. + std::string properties; + /// Lua only: give this entity its own copy of the script (private globals) instead of + /// sharing the file's state with every other entity that uses it. + bool isolated = false; }; using ScriptCallback = std::function; diff --git a/src/caffeine/script/ScriptWorldApi.hpp b/src/caffeine/script/ScriptWorldApi.hpp new file mode 100644 index 00000000..a4b5f975 --- /dev/null +++ b/src/caffeine/script/ScriptWorldApi.hpp @@ -0,0 +1,133 @@ +#pragma once + +// Language-independent implementations behind `caffeine.entity`, `caffeine.hierarchy` and +// `caffeine.random`. Lua (WorldApiBindings.cpp) and Dryad (DryadWorldBindings.cpp) both call +// these, so the two languages cannot disagree about behaviour. + +#include "core/Types.hpp" +#include "ecs/ComponentQuery.hpp" +#include "ecs/World.hpp" +#include "scene/EditorContext.hpp" +#include "scene/SceneComponents.hpp" + +#include +#include +#include +#include + +namespace Caffeine::Script::WorldApi { + +inline bool alive(ECS::World* world, u32 id, ECS::Entity& out) { + if (!world || id == 0) return false; + out = ECS::Entity(id, world); + return out.isValid() && world->isEntityAlive(out); +} + +// --- entity names --------------------------------------------------------------------------- + +inline std::string nameOf(ECS::World* world, u32 id) { + ECS::Entity e; + if (!alive(world, id, e)) return {}; + if (auto* nc = world->get(e)) return nc->name; + return {}; +} + +inline bool setName(ECS::World* world, u32 id, const std::string& name) { + ECS::Entity e; + if (!alive(world, id, e)) return false; + Editor::setEntityName(*world, e, name.c_str()); + return true; +} + +inline std::vector findAll(ECS::World* world, const std::string& name) { + std::vector out; + if (!world) return out; + ECS::ComponentQuery q; + q.with(); + world->forEach(q, [&](ECS::Entity e, Editor::NameComponent& nc) { + if (name == nc.name) out.push_back(e.id()); + }); + std::sort(out.begin(), out.end()); + return out; +} + +/// Lowest entity id with this name, or 0. +inline u32 find(ECS::World* world, const std::string& name) { + const auto all = findAll(world, name); + return all.empty() ? 0u : all.front(); +} + +// --- hierarchy ------------------------------------------------------------------------------ + +inline u32 parentOf(ECS::World* world, u32 id) { + ECS::Entity e; + if (!alive(world, id, e)) return 0; + auto* p = world->get(e); + return p && p->parent.isValid() ? p->parent.id() : 0u; +} + +inline std::vector childrenOf(ECS::World* world, u32 id) { + std::vector out; + if (!world || id == 0) return out; + ECS::ComponentQuery q; + q.with(); + world->forEach(q, [&](ECS::Entity e, Scene::Parent& p) { + if (p.parent.isValid() && p.parent.id() == id) out.push_back(e.id()); + }); + std::sort(out.begin(), out.end()); + return out; +} + +inline u32 rootOf(ECS::World* world, u32 id) { + u32 cur = id; + for (int guard = 0; guard < 64; ++guard) { + const u32 p = parentOf(world, cur); + if (p == 0) return cur; + cur = p; + } + return cur; +} + +/// `parent` 0 detaches. Refuses a missing entity, itself and any cycle. +inline bool setParent(ECS::World* world, u32 child, u32 parent) { + ECS::Entity c, p; + if (!alive(world, child, c)) return false; + if (parent == 0) { + world->remove(c); + return true; + } + if (!alive(world, parent, p) || parent == child) return false; + for (u32 cur = parent, guard = 0; cur != 0 && guard < 64; cur = parentOf(world, cur), ++guard) { + if (cur == child) return false; // would create a cycle + } + auto& comp = world->add(c); + comp.parent = p; + comp.dirty = true; + return true; +} + +// --- random --------------------------------------------------------------------------------- + +/// Deterministic xorshift64*; the sequence depends only on the seed. +class Rng { +public: + static Rng& instance() { static Rng r; return r; } + void seed(u64 s) { m_state = s ? s : 0x9E3779B97F4A7C15ull; } + f64 next01() { + m_state ^= m_state >> 12; m_state ^= m_state << 25; m_state ^= m_state >> 27; + const u64 v = m_state * 0x2545F4914F6CDD1Dull; + return static_cast(v >> 11) / 9007199254740992.0; // 53 bits -> [0, 1) + } + f64 range(f64 lo, f64 hi) { return lo + (hi - lo) * next01(); } + /// Inclusive on both ends; swaps reversed bounds. + i64 integer(i64 lo, i64 hi) { + if (lo > hi) std::swap(lo, hi); + const u64 span = static_cast(hi - lo) + 1; + return lo + static_cast(static_cast(next01() * static_cast(span)) % span); + } + bool chance(f64 p) { return next01() < p; } +private: + u64 m_state = 0x9E3779B97F4A7C15ull; +}; + +} // namespace Caffeine::Script::WorldApi diff --git a/src/caffeine/script/WorldApiBindings.cpp b/src/caffeine/script/WorldApiBindings.cpp new file mode 100644 index 00000000..301fc830 --- /dev/null +++ b/src/caffeine/script/WorldApiBindings.cpp @@ -0,0 +1,43 @@ +#include "script/ScriptWorldApi.hpp" + +#include + +namespace Caffeine::Script { + +namespace W = WorldApi; + +static sol::table idTable(sol::state_view lua, const std::vector& ids) { + sol::table t = lua.create_table(); + for (size_t i = 0; i < ids.size(); ++i) t[i + 1] = ids[i]; + return t; +} + +void registerWorldApiBindings(sol::state& lua, ECS::World** worldPtr) { + auto world = [worldPtr]() -> ECS::World* { return worldPtr ? *worldPtr : nullptr; }; + + sol::table ent = lua["caffeine"]["entity"].get_or_create(); + ent["name"] = [world](u32 id) { return W::nameOf(world(), id); }; + ent["setName"] = [world](u32 id, const std::string& n) { return W::setName(world(), id, n); }; + ent["find"] = [world](const std::string& n) { return W::find(world(), n); }; + ent["findAll"] = [world, &lua](const std::string& n) { return idTable(lua, W::findAll(world(), n)); }; + ent["isAlive"] = [world](u32 id) { ECS::Entity e; return W::alive(world(), id, e); }; + + sol::table h = lua["caffeine"]["hierarchy"].get_or_create(); + h["parent"] = [world](u32 id) { return W::parentOf(world(), id); }; + h["setParent"] = [world](u32 id, u32 parent) { return W::setParent(world(), id, parent); }; + h["detach"] = [world](u32 id) { return W::setParent(world(), id, 0); }; + h["children"] = [world, &lua](u32 id) { return idTable(lua, W::childrenOf(world(), id)); }; + h["childCount"] = [world](u32 id) { return static_cast(W::childrenOf(world(), id).size()); }; + h["root"] = [world](u32 id) { return W::rootOf(world(), id); }; + + sol::table r = lua["caffeine"]["random"].get_or_create(); + r["setSeed"] = [](double s) { W::Rng::instance().seed(static_cast(s)); }; + r["value"] = []() { return W::Rng::instance().next01(); }; + r["range"] = [](double lo, double hi) { return W::Rng::instance().range(lo, hi); }; + r["int"] = [](double lo, double hi) { + return static_cast(W::Rng::instance().integer(static_cast(lo), static_cast(hi))); + }; + r["chance"] = [](double p) { return W::Rng::instance().chance(p); }; +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/api/animation.json b/src/caffeine/script/api/animation.json new file mode 100644 index 00000000..d8cf7c9c --- /dev/null +++ b/src/caffeine/script/api/animation.json @@ -0,0 +1,242 @@ +{ + "namespace": "animation", + "group": "Rendering", + "lua": "caffeine.animation", + "dryad_prefix": null, + "title": { + "en": "Animation", + "pt": "Animação" + }, + "summary": { + "en": "Clip, state-machine, skinned-mesh and sprite-sheet animation control.", + "pt": "Controlo de animação por clips, máquina de estados, malhas com skin e sprite sheets." + }, + "functions": [ + { + "name": "playClip", + "lua": "caffeine.animation.playClip", + "dryad": null, + "signature": "playClip(entity, path) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "path", + "type": "string", + "en": "Clip asset path.", + "pt": "Caminho do asset do clip." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Plays an animation clip on the entity.", + "pt": "Reproduz um clip de animação na entidade.", + "example": "caffeine.animation.playClip(e, 'clips/run.anim')" + }, + { + "name": "playSkinnedClip", + "lua": "caffeine.animation.playSkinnedClip", + "dryad": null, + "signature": "playSkinnedClip(entity, meshPath, clipIndex) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "meshPath", + "type": "string", + "en": "Skinned mesh path.", + "pt": "Caminho da malha com skin." + }, + { + "name": "clipIndex", + "type": "number", + "en": "Index of the clip in the mesh.", + "pt": "Índice do clip na malha." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Plays a clip of a skinned mesh by index.", + "pt": "Reproduz um clip de uma malha com skin pelo índice.", + "example": "caffeine.animation.playSkinnedClip(e, 'models/hero.glb', 0)" + }, + { + "name": "playState", + "lua": "caffeine.animation.playState", + "dryad": null, + "signature": "playState(entity, state) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "state", + "type": "string", + "en": "State name.", + "pt": "Nome do estado." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Switches the animator to a named state.", + "pt": "Muda o animator para um estado com nome.", + "example": "caffeine.animation.playState(e, 'Idle')" + }, + { + "name": "setBool", + "lua": "caffeine.animation.setBool", + "dryad": null, + "signature": "setBool(entity, name, value) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Parameter name.", + "pt": "Nome do parâmetro." + }, + { + "name": "value", + "type": "boolean", + "en": "New value.", + "pt": "Novo valor." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Sets a boolean animator parameter.", + "pt": "Define um parâmetro booleano do animator.", + "example": "caffeine.animation.setBool(e, 'grounded', true)" + }, + { + "name": "setFloat", + "lua": "caffeine.animation.setFloat", + "dryad": null, + "signature": "setFloat(entity, name, value) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Parameter name.", + "pt": "Nome do parâmetro." + }, + { + "name": "value", + "type": "number", + "en": "New value.", + "pt": "Novo valor." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Sets a float animator parameter.", + "pt": "Define um parâmetro float do animator.", + "example": "caffeine.animation.setFloat(e, 'speed', 3.5)" + }, + { + "name": "setTrigger", + "lua": "caffeine.animation.setTrigger", + "dryad": null, + "signature": "setTrigger(entity, name) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Trigger name.", + "pt": "Nome do trigger." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Fires an animator trigger.", + "pt": "Dispara um trigger do animator.", + "example": "caffeine.animation.setTrigger(e, 'jump')" + }, + { + "name": "setSpriteSheet", + "lua": "caffeine.animation.setSpriteSheet", + "dryad": null, + "signature": "setSpriteSheet(entity, columns, rows, frameCount) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "columns", + "type": "number", + "en": "Columns in the sheet.", + "pt": "Colunas na folha." + }, + { + "name": "rows", + "type": "number", + "en": "Rows in the sheet.", + "pt": "Linhas na folha." + }, + { + "name": "frameCount", + "type": "number", + "en": "Total number of frames.", + "pt": "Número total de frames." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Configures sprite-sheet animation on the entity.", + "pt": "Configura a animação por sprite sheet na entidade.", + "example": "caffeine.animation.setSpriteSheet(e, 4, 4, 16)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/assets.json b/src/caffeine/script/api/assets.json new file mode 100644 index 00000000..cf11f1c5 --- /dev/null +++ b/src/caffeine/script/api/assets.json @@ -0,0 +1,38 @@ +{ + "namespace": "assets", + "group": "Game", + "lua": "caffeine.assets", + "dryad_prefix": null, + "title": { + "en": "Assets", + "pt": "Recursos" + }, + "summary": { + "en": "Read project assets from scripts.", + "pt": "Ler recursos do projeto a partir de scripts." + }, + "functions": [ + { + "name": "loadText", + "lua": "caffeine.assets.loadText", + "dryad": null, + "signature": "loadText(path) -> string", + "params": [ + { + "name": "path", + "type": "string", + "en": "Asset path; also searched under the project root, assets/, data/ and data/assets/.", + "pt": "Caminho do recurso; também é procurado na raiz do projeto, em assets/, data/ e data/assets/." + } + ], + "returns": { + "type": "string", + "en": "The file text (cached); on failure the error message; nil without a loader.", + "pt": "O texto do ficheiro (em cache); em caso de falha a mensagem de erro; nil sem carregador." + }, + "en": "Loads a text file. A failure returns the error text rather than raising, so check what you get back.", + "pt": "Carrega um ficheiro de texto. Uma falha devolve o texto do erro em vez de lançar erro, por isso verifique o que recebe.", + "example": "local json = caffeine.assets.loadText('data/items.json')" + } + ] +} diff --git a/src/caffeine/script/api/component.json b/src/caffeine/script/api/component.json new file mode 100644 index 00000000..d663de4f --- /dev/null +++ b/src/caffeine/script/api/component.json @@ -0,0 +1,483 @@ +{ + "namespace": "component", + "group": "Core", + "lua": "caffeine.component", + "dryad_prefix": "caffeine_component_", + "title": { + "en": "Component", + "pt": "Componente" + }, + "summary": { + "en": "Generic access to every component the reflection registry describes: list, add, remove, read and write fields by name.", + "pt": "Acesso genérico a todos os componentes descritos no registo de reflexão: listar, adicionar, remover, ler e escrever campos pelo nome." + }, + "functions": [ + { + "name": "list", + "lua": "caffeine.component.list", + "dryad": "caffeine_component_list", + "signature": "list() -> table", + "params": [], + "returns": { + "type": "table", + "en": "Array of {name, id, fields}; each field has name, kind, min, max and options (enums).", + "pt": "Lista de {name, id, fields}; cada campo tem name, kind, min, max e options (enums)." + }, + "en": "Lists every component type the reflection registry describes, with its fields. In Dryad it returns only the names.", + "pt": "Lista todos os tipos de componente descritos no registo de reflexão, com os campos. Em Dryad devolve apenas os nomes.", + "example": "for _, c in ipairs(caffeine.component.list()) do caffeine.debug.log(c.name) end" + }, + { + "name": "names", + "lua": "caffeine.component.names", + "dryad": "caffeine_component_names", + "signature": "names(entity) -> table", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "table", + "en": "Array of component names.", + "pt": "Lista de nomes de componentes." + }, + "en": "Lists the components the entity has. Errors when the entity does not exist.", + "pt": "Lista os componentes que a entidade tem. Dá erro se a entidade não existir.", + "example": "local names = caffeine.component.names(e)" + }, + { + "name": "has", + "lua": "caffeine.component.has", + "dryad": "caffeine_component_has", + "signature": "has(entity, name) -> boolean", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + } + ], + "returns": { + "type": "boolean", + "en": "True when the entity has the component.", + "pt": "Verdadeiro se a entidade tiver o componente." + }, + "en": "Checks whether an entity has a component. Errors on an unknown component name.", + "pt": "Verifica se uma entidade tem um componente. Dá erro para um nome de componente desconhecido.", + "example": "if caffeine.component.has(e, 'Rigid Body 3D') then end" + }, + { + "name": "add", + "lua": "caffeine.component.add", + "dryad": "caffeine_component_add", + "signature": "add(entity, name) -> boolean", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Adds a component with default values; does nothing if the entity already has it. In Dryad it returns false and logs an error on failure.", + "pt": "Adiciona um componente com valores por omissão; não faz nada se a entidade já o tiver. Em Dryad devolve false e regista um erro em caso de falha.", + "example": "caffeine.component.add(e, 'Rigid Body 3D')" + }, + { + "name": "remove", + "lua": "caffeine.component.remove", + "dryad": "caffeine_component_remove", + "signature": "remove(entity, name) -> boolean", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + } + ], + "returns": { + "type": "boolean", + "en": "True when the component was removed, false when the entity did not have it.", + "pt": "Verdadeiro se o componente foi removido, falso se a entidade não o tinha." + }, + "en": "Removes a component from an entity.", + "pt": "Remove um componente de uma entidade.", + "example": "caffeine.component.remove(e, 'Rigid Body 3D')" + }, + { + "name": "get", + "lua": "caffeine.component.get", + "dryad": "caffeine_component_get", + "signature": "get(entity, name) -> table|nil", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + } + ], + "returns": { + "type": "table", + "en": "Table of every field, or nil when the entity lacks the component.", + "pt": "Tabela com todos os campos, ou nil se a entidade não tiver o componente." + }, + "en": "Reads all fields of a component. Vectors are {x, y, z}; colours and 4D vectors also carry r, g, b, a; enums are option names.", + "pt": "Lê todos os campos de um componente. Os vetores são {x, y, z}; cores e vetores 4D também têm r, g, b, a; os enums são nomes de opção.", + "example": "local rb = caffeine.component.get(e, 'Rigid Body 3D')" + }, + { + "name": "getField", + "lua": "caffeine.component.getField", + "dryad": "caffeine_component_get_field", + "signature": "getField(entity, name, field) -> any", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + }, + { + "name": "field", + "type": "string", + "en": "Field name.", + "pt": "Nome do campo." + } + ], + "returns": { + "type": "any", + "en": "The field value.", + "pt": "O valor do campo." + }, + "en": "Reads one field. Errors on an unknown component or field, or when the entity lacks the component (Dryad logs the error and returns null).", + "pt": "Lê um campo. Dá erro para componente ou campo desconhecido, ou se a entidade não tiver o componente (o Dryad regista o erro e devolve null).", + "example": "local mass = caffeine.component.getField(e, 'Rigid Body 3D', 'Mass')" + }, + { + "name": "setField", + "lua": "caffeine.component.setField", + "dryad": "caffeine_component_set_field", + "signature": "setField(entity, name, field, value)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + }, + { + "name": "field", + "type": "string", + "en": "Field name.", + "pt": "Nome do campo." + }, + { + "name": "value", + "type": "any", + "en": "New value: number, boolean, text, enum option name or index, or a vector table.", + "pt": "Novo valor: número, booleano, texto, nome ou índice de opção de enum, ou tabela de vetor." + } + ], + "returns": null, + "en": "Writes one field. The entity must already have the component (use `caffeine.component.add`); a wrong value type raises an error.", + "pt": "Escreve um campo. A entidade já tem de ter o componente (use `caffeine.component.add`); um tipo de valor errado provoca erro.", + "example": "caffeine.component.setField(e, 'Rigid Body 3D', 'Mass', 7.5)" + }, + { + "name": "set", + "lua": "caffeine.component.set", + "dryad": "caffeine_component_set", + "signature": "set(entity, name, values)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + }, + { + "name": "values", + "type": "table", + "en": "Map of field name to value; omitted fields keep their value.", + "pt": "Mapa de nome de campo para valor; os campos omitidos mantêm o valor." + } + ], + "returns": null, + "en": "Adds the component when missing and writes the given fields.", + "pt": "Adiciona o componente se não existir e escreve os campos indicados.", + "example": "caffeine.component.set(e, 'Rigid Body 3D', { Mass = 3 })" + }, + { + "name": "caffeine_component_get_number", + "lua": null, + "dryad": "caffeine_component_get_number", + "signature": "caffeine_component_get_number(entity, name, field[, index]) -> number", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + }, + { + "name": "field", + "type": "string", + "en": "Field name.", + "pt": "Nome do campo." + }, + { + "name": "index", + "type": "integer", + "en": "Vector part (0 = x); default 0.", + "pt": "Parte do vetor (0 = x); por omissão 0." + } + ], + "returns": { + "type": "number", + "en": "Number; integers, enum indices and bools come back as integer/boolean. null on error.", + "pt": "Número; inteiros, índices de enum e booleanos voltam como inteiro/booleano. null em caso de erro." + }, + "en": "Dryad only: reads a numeric, boolean or enum field, or one part of a vector.", + "pt": "Apenas Dryad: lê um campo numérico, booleano ou de enum, ou uma parte de um vetor.", + "example": "let mass = caffeine_component_get_number(entity, \"Rigid Body 3D\", \"Mass\");" + }, + { + "name": "caffeine_component_set_number", + "lua": null, + "dryad": "caffeine_component_set_number", + "signature": "caffeine_component_set_number(entity, name, field, value[, index]) -> boolean", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + }, + { + "name": "field", + "type": "string", + "en": "Field name.", + "pt": "Nome do campo." + }, + { + "name": "value", + "type": "number", + "en": "Number (or boolean).", + "pt": "Número (ou booleano)." + }, + { + "name": "index", + "type": "integer", + "en": "Vector part (0 = x); default 0.", + "pt": "Parte do vetor (0 = x); por omissão 0." + } + ], + "returns": { + "type": "boolean", + "en": "True on success.", + "pt": "Verdadeiro em caso de sucesso." + }, + "en": "Dryad only: writes a numeric, boolean or enum-index field, or one part of a vector.", + "pt": "Apenas Dryad: escreve um campo numérico, booleano ou índice de enum, ou uma parte de um vetor.", + "example": "caffeine_component_set_number(entity, \"Rigid Body 3D\", \"Mass\", 7.5);" + }, + { + "name": "caffeine_component_set_vec", + "lua": null, + "dryad": "caffeine_component_set_vec", + "signature": "caffeine_component_set_vec(entity, name, field, x, y[, z[, w]]) -> boolean", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + }, + { + "name": "field", + "type": "string", + "en": "Field name.", + "pt": "Nome do campo." + }, + { + "name": "x", + "type": "number", + "en": "First part.", + "pt": "Primeira parte." + }, + { + "name": "y", + "type": "number", + "en": "Second part.", + "pt": "Segunda parte." + }, + { + "name": "z", + "type": "number", + "en": "Third part (optional).", + "pt": "Terceira parte (opcional)." + }, + { + "name": "w", + "type": "number", + "en": "Fourth part (optional).", + "pt": "Quarta parte (opcional)." + } + ], + "returns": { + "type": "boolean", + "en": "True when every part was written.", + "pt": "Verdadeiro se todas as partes foram escritas." + }, + "en": "Dryad only: writes a whole vector or colour field from its parts.", + "pt": "Apenas Dryad: escreve um campo inteiro de vetor ou cor a partir das suas partes.", + "example": "caffeine_component_set_vec(entity, \"Position 3D\", \"Position\", 4, 5, 6);" + }, + { + "name": "caffeine_component_get_text", + "lua": null, + "dryad": "caffeine_component_get_text", + "signature": "caffeine_component_get_text(entity, name, field) -> string", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + }, + { + "name": "field", + "type": "string", + "en": "Field name.", + "pt": "Nome do campo." + } + ], + "returns": { + "type": "string", + "en": "Text or enum label; null on error.", + "pt": "Texto ou rótulo de enum; null em caso de erro." + }, + "en": "Dryad only: reads a string field or an enum option name.", + "pt": "Apenas Dryad: lê um campo de texto ou o nome de uma opção de enum.", + "example": "let kind = caffeine_component_get_text(entity, \"Mesh Filter\", \"Primitive\");" + }, + { + "name": "caffeine_component_set_text", + "lua": null, + "dryad": "caffeine_component_set_text", + "signature": "caffeine_component_set_text(entity, name, field, text) -> boolean", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "Component name as listed by `caffeine.component.list()`.", + "pt": "Nome do componente, como listado por `caffeine.component.list()`." + }, + { + "name": "field", + "type": "string", + "en": "Field name.", + "pt": "Nome do campo." + }, + { + "name": "text", + "type": "string", + "en": "Text or enum option name.", + "pt": "Texto ou nome de opção de enum." + } + ], + "returns": { + "type": "boolean", + "en": "True on success.", + "pt": "Verdadeiro em caso de sucesso." + }, + "en": "Dryad only: writes a string field or sets an enum by option name.", + "pt": "Apenas Dryad: escreve um campo de texto ou define um enum pelo nome da opção.", + "example": "caffeine_component_set_text(entity, \"Mesh Filter\", \"Primitive\", \"Cone\");" + } + ] +} diff --git a/src/caffeine/script/api/core.json b/src/caffeine/script/api/core.json new file mode 100644 index 00000000..05ccb13c --- /dev/null +++ b/src/caffeine/script/api/core.json @@ -0,0 +1,34 @@ +{ + "namespace": "core", + "group": "Core", + "lua": "caffeine", + "dryad_prefix": null, + "title": { + "en": "Core", + "pt": "Núcleo" + }, + "summary": { + "en": "Top-level helpers of the caffeine table.", + "pt": "Auxiliares de topo da tabela caffeine." + }, + "functions": [ + { + "name": "require", + "lua": "caffeine.require", + "dryad": null, + "signature": "require(name)", + "params": [ + { + "name": "name", + "type": "string", + "en": "Module name; dots become folders, so 'util.maths' loads scripts/util/maths.lua.", + "pt": "Nome do módulo; os pontos tornam-se pastas, por isso 'util.maths' carrega scripts/util/maths.lua." + } + ], + "returns": null, + "en": "Loads and runs another script module from the project's scripts/ folder. It returns nothing; an error is raised if loading fails.", + "pt": "Carrega e executa outro módulo de script da pasta scripts/ do projeto. Não devolve nada; é lançado um erro se o carregamento falhar.", + "example": "caffeine.require('util.maths')" + } + ] +} diff --git a/src/caffeine/script/api/debug.json b/src/caffeine/script/api/debug.json new file mode 100644 index 00000000..b7099418 --- /dev/null +++ b/src/caffeine/script/api/debug.json @@ -0,0 +1,70 @@ +{ + "namespace": "debug", + "group": "Core", + "lua": "caffeine.debug", + "dryad_prefix": "caffeine_log", + "title": { + "en": "Debug", + "pt": "Depuração" + }, + "summary": { + "en": "Logging to the engine console.", + "pt": "Registo na consola do motor." + }, + "functions": [ + { + "name": "log", + "lua": "caffeine.debug.log", + "dryad": "caffeine_log", + "signature": "log(msg)", + "params": [ + { + "name": "msg", + "type": "string", + "en": "Message text.", + "pt": "Texto da mensagem." + } + ], + "returns": null, + "en": "Writes an info message to the engine log (source \"Lua\"). In Dryad `caffeine_log(value)` logs the first argument as text under \"Dryad\".", + "pt": "Escreve uma mensagem informativa no registo do motor (origem \"Lua\"). Em Dryad `caffeine_log(valor)` regista o primeiro argumento como texto sob \"Dryad\".", + "example": "caffeine.debug.log('hello')" + }, + { + "name": "warn", + "lua": "caffeine.debug.warn", + "dryad": null, + "signature": "warn(msg)", + "params": [ + { + "name": "msg", + "type": "string", + "en": "Message text.", + "pt": "Texto da mensagem." + } + ], + "returns": null, + "en": "Writes a warning to the engine log.", + "pt": "Escreve um aviso no registo do motor.", + "example": "caffeine.debug.warn('low health')" + }, + { + "name": "error", + "lua": "caffeine.debug.error", + "dryad": null, + "signature": "error(msg)", + "params": [ + { + "name": "msg", + "type": "string", + "en": "Message text.", + "pt": "Texto da mensagem." + } + ], + "returns": null, + "en": "Writes an error message to the engine log. It does not stop the script.", + "pt": "Escreve uma mensagem de erro no registo do motor. Não interrompe o script.", + "example": "caffeine.debug.error('missing target')" + } + ] +} diff --git a/src/caffeine/script/api/draw2d.json b/src/caffeine/script/api/draw2d.json new file mode 100644 index 00000000..d31e5f8c --- /dev/null +++ b/src/caffeine/script/api/draw2d.json @@ -0,0 +1,195 @@ +{ + "namespace": "draw2d", + "group": "UI", + "lua": "caffeine.draw2d", + "dryad_prefix": null, + "title": { + "en": "Draw 2D", + "pt": "Desenho 2D" + }, + "summary": { + "en": "Immediate-mode 2D overlay shapes (lines, circles, rectangles, polylines) in world or screen space.", + "pt": "Formas 2D de sobreposição em modo imediato (linhas, círculos, retângulos, polilinhas) em espaço de mundo ou de ecrã." + }, + "functions": [ + { + "name": "beginFrame", + "lua": "caffeine.draw2d.beginFrame", + "dryad": null, + "signature": "beginFrame()", + "params": [], + "returns": null, + "en": "Starts a new overlay frame, clearing previous draw2d shapes. Call it once at the start of drawing.", + "pt": "Inicia um novo frame de sobreposição, limpando as formas draw2d anteriores. Chame-o uma vez no início do desenho.", + "example": "caffeine.draw2d.beginFrame()" + }, + { + "name": "line", + "lua": "caffeine.draw2d.line", + "dryad": null, + "signature": "line(a, b, color[, thickness[, space]])", + "params": [ + { + "name": "a", + "type": "table", + "en": "Start {x, y}.", + "pt": "Início {x, y}." + }, + { + "name": "b", + "type": "table", + "en": "End {x, y}.", + "pt": "Fim {x, y}." + }, + { + "name": "color", + "type": "table", + "en": "{r, g, b, a} in 0..1 (each defaults to 1).", + "pt": "{r, g, b, a} em 0..1 (cada um com 1 por omissão)." + }, + { + "name": "thickness", + "type": "number", + "en": "Line thickness (default 1).", + "pt": "Espessura da linha (por omissão 1)." + }, + { + "name": "space", + "type": "string", + "en": "\"world\" (default) or \"screen\".", + "pt": "\"world\" (por omissão) ou \"screen\"." + } + ], + "returns": null, + "en": "Draws a line in the 2D overlay.", + "pt": "Desenha uma linha na sobreposição 2D.", + "example": "caffeine.draw2d.line({x=0,y=0},{x=5,y=5},{r=1,g=0,b=0,a=1}, 2)" + }, + { + "name": "circle", + "lua": "caffeine.draw2d.circle", + "dryad": null, + "signature": "circle(center, radius, color[, thickness[, space]])", + "params": [ + { + "name": "center", + "type": "table", + "en": "Center {x, y}.", + "pt": "Centro {x, y}." + }, + { + "name": "radius", + "type": "number", + "en": "Radius.", + "pt": "Raio." + }, + { + "name": "color", + "type": "table", + "en": "{r, g, b, a} in 0..1 (each defaults to 1).", + "pt": "{r, g, b, a} em 0..1 (cada um com 1 por omissão)." + }, + { + "name": "thickness", + "type": "number", + "en": "Line thickness (default 1).", + "pt": "Espessura da linha (por omissão 1)." + }, + { + "name": "space", + "type": "string", + "en": "\"world\" (default) or \"screen\".", + "pt": "\"world\" (por omissão) ou \"screen\"." + } + ], + "returns": null, + "en": "Draws a circle outline (32 segments).", + "pt": "Desenha o contorno de um círculo (32 segmentos).", + "example": "caffeine.draw2d.circle({x=0,y=0}, 3, {r=0,g=1,b=0,a=1})" + }, + { + "name": "rect", + "lua": "caffeine.draw2d.rect", + "dryad": null, + "signature": "rect(min, max, color[, thickness[, space]])", + "params": [ + { + "name": "min", + "type": "table", + "en": "Corner {x, y}.", + "pt": "Canto {x, y}." + }, + { + "name": "max", + "type": "table", + "en": "Opposite corner {x, y}.", + "pt": "Canto oposto {x, y}." + }, + { + "name": "color", + "type": "table", + "en": "{r, g, b, a} in 0..1 (each defaults to 1).", + "pt": "{r, g, b, a} em 0..1 (cada um com 1 por omissão)." + }, + { + "name": "thickness", + "type": "number", + "en": "Line thickness (default 1).", + "pt": "Espessura da linha (por omissão 1)." + }, + { + "name": "space", + "type": "string", + "en": "\"world\" (default) or \"screen\".", + "pt": "\"world\" (por omissão) ou \"screen\"." + } + ], + "returns": null, + "en": "Draws a rectangle outline.", + "pt": "Desenha o contorno de um retângulo.", + "example": "caffeine.draw2d.rect({x=-1,y=-1},{x=1,y=1},{r=1,g=1,b=0,a=1})" + }, + { + "name": "poly", + "lua": "caffeine.draw2d.poly", + "dryad": null, + "signature": "poly(points, color[, closed[, thickness[, space]]])", + "params": [ + { + "name": "points", + "type": "table", + "en": "Array of {x, y}; at least 2 points or nothing is drawn.", + "pt": "Lista de {x, y}; pelo menos 2 pontos, senão nada é desenhado." + }, + { + "name": "color", + "type": "table", + "en": "{r, g, b, a} in 0..1 (each defaults to 1).", + "pt": "{r, g, b, a} em 0..1 (cada um com 1 por omissão)." + }, + { + "name": "closed", + "type": "boolean", + "en": "Close the shape (default false).", + "pt": "Fechar a forma (por omissão false)." + }, + { + "name": "thickness", + "type": "number", + "en": "Line thickness (default 1).", + "pt": "Espessura da linha (por omissão 1)." + }, + { + "name": "space", + "type": "string", + "en": "\"world\" (default) or \"screen\".", + "pt": "\"world\" (por omissão) ou \"screen\"." + } + ], + "returns": null, + "en": "Draws a polyline or polygon outline.", + "pt": "Desenha uma polilinha ou o contorno de um polígono.", + "example": "caffeine.draw2d.poly({{x=0,y=0},{x=2,y=0},{x=1,y=2}}, {r=1,g=1,b=1,a=1}, true)" + } + ] +} diff --git a/src/caffeine/script/api/effects.json b/src/caffeine/script/api/effects.json new file mode 100644 index 00000000..e037e369 --- /dev/null +++ b/src/caffeine/script/api/effects.json @@ -0,0 +1,232 @@ +{ + "namespace": "effects", + "group": "Rendering", + "lua": "caffeine.effects", + "dryad_prefix": null, + "title": { + "en": "Effects", + "pt": "Efeitos" + }, + "summary": { + "en": "Effect components on entities: particles, volumetric light, reflective surfaces, material shades and fog.", + "pt": "Componentes de efeitos em entidades: partículas, luz volumétrica, superfícies refletoras, sombreados de material e nevoeiro." + }, + "functions": [ + { + "name": "set", + "lua": "caffeine.effects.set", + "dryad": null, + "signature": "set(entity, kind, quality) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "kind", + "type": "number", + "en": "0 Particles, 1 VolumetricLight, 2 ReflectiveSurface, 3 MaterialShade, 4 Fog; clamped to 4.", + "pt": "0 Particles, 1 VolumetricLight, 2 ReflectiveSurface, 3 MaterialShade, 4 Fog; limitado a 4." + }, + { + "name": "quality", + "type": "number", + "en": "0 Performance, 1 Balanced, 2 Quality; clamped to 2.", + "pt": "0 Performance, 1 Balanced, 2 Quality; limitado a 2." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Assigns an effect kind and quality to the entity.", + "pt": "Atribui um tipo de efeito e uma qualidade à entidade.", + "example": "caffeine.effects.set(e, 0, 1)" + }, + { + "name": "particle", + "lua": "caffeine.effects.particle", + "dryad": null, + "signature": "particle(entity, domain) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "domain", + "type": "number", + "en": "0 Both, 1 2D, 2 3D; clamped to 2.", + "pt": "0 Both, 1 2D, 2 3D; limitado a 2." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Turns the entity into a particle emitter for the given domain.", + "pt": "Transforma a entidade num emissor de partículas para o domínio indicado.", + "example": "caffeine.effects.particle(e, 2)" + }, + { + "name": "particleParams", + "lua": "caffeine.effects.particleParams", + "dryad": null, + "signature": "particleParams(entity, rate, lifetime, maxParticles, startSize, endSize, gravityY) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "rate", + "type": "number", + "en": "Emission rate.", + "pt": "Taxa de emissão." + }, + { + "name": "lifetime", + "type": "number", + "en": "Particle lifetime.", + "pt": "Tempo de vida da partícula." + }, + { + "name": "maxParticles", + "type": "number", + "en": "Maximum live particles.", + "pt": "Máximo de partículas vivas." + }, + { + "name": "startSize", + "type": "number", + "en": "Size at birth.", + "pt": "Tamanho ao nascer." + }, + { + "name": "endSize", + "type": "number", + "en": "Size at death.", + "pt": "Tamanho ao fim da vida." + }, + { + "name": "gravityY", + "type": "number", + "en": "Vertical gravity.", + "pt": "Gravidade vertical." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Sets the particle emitter parameters.", + "pt": "Define os parâmetros do emissor de partículas.", + "example": "caffeine.effects.particleParams(e, 30, 2, 200, 0.2, 0.0, -1)" + }, + { + "name": "volumetric", + "lua": "caffeine.effects.volumetric", + "dryad": null, + "signature": "volumetric(entity) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Makes the entity a volumetric light and ensures its volume mesh.", + "pt": "Torna a entidade uma luz volumétrica e garante a respetiva malha de volume.", + "example": "caffeine.effects.volumetric(lamp)" + }, + { + "name": "volumetricShape", + "lua": "caffeine.effects.volumetricShape", + "dryad": null, + "signature": "volumetricShape(entity, shape, columns, rows) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "shape", + "type": "number", + "en": "0 Sphere, 1 Cone, 2 Box, 3 Cylinder, 4 Window; clamped to 4.", + "pt": "0 Sphere, 1 Cone, 2 Box, 3 Cylinder, 4 Window; limitado a 4." + }, + { + "name": "columns", + "type": "number", + "en": "Column count.", + "pt": "Número de colunas." + }, + { + "name": "rows", + "type": "number", + "en": "Row count.", + "pt": "Número de linhas." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Sets the shape of a volumetric light.", + "pt": "Define a forma de uma luz volumétrica.", + "example": "caffeine.effects.volumetricShape(lamp, 1, 8, 8)" + }, + { + "name": "fog", + "lua": "caffeine.effects.fog", + "dryad": null, + "signature": "fog(entity, domain, style) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "domain", + "type": "number", + "en": "0 Both, 1 2D, 2 3D; clamped to 2.", + "pt": "0 Both, 1 2D, 2 3D; limitado a 2." + }, + { + "name": "style", + "type": "number", + "en": "0 Fog, 1 Dust, 2 Mist, 3 Smoke; clamped to 3.", + "pt": "0 Fog, 1 Dust, 2 Mist, 3 Smoke; limitado a 3." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Turns the entity into a fog effect with the given style.", + "pt": "Transforma a entidade num efeito de nevoeiro com o estilo indicado.", + "example": "caffeine.effects.fog(e, 2, 2)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/entity.json b/src/caffeine/script/api/entity.json new file mode 100644 index 00000000..7a02ae6e --- /dev/null +++ b/src/caffeine/script/api/entity.json @@ -0,0 +1,132 @@ +{ + "namespace": "entity", + "group": "Core", + "lua": "caffeine.entity", + "dryad_prefix": "caffeine_entity_", + "title": { + "en": "Entity", + "pt": "Entidade" + }, + "summary": { + "en": "Names and lookup. Entities are plain numeric ids; a name is optional and need not be unique.", + "pt": "Nomes e procura. As entidades são ids numéricos; o nome é opcional e não tem de ser único." + }, + "functions": [ + { + "name": "name", + "lua": "caffeine.entity.name", + "dryad": "caffeine_entity_name", + "signature": "name(entity) -> string", + "params": [ + { + "name": "entity", + "type": "number", + "en": "The entity id.", + "pt": "O id da entidade." + } + ], + "returns": { + "type": "string", + "en": "The name, or an empty string when unnamed or dead.", + "pt": "O nome, ou texto vazio se não tiver nome ou estiver morta." + }, + "en": "Reads the editor name of an entity.", + "pt": "Lê o nome de editor de uma entidade.", + "example": "print(caffeine.entity.name(eid))" + }, + { + "name": "setName", + "lua": "caffeine.entity.setName", + "dryad": "caffeine_entity_set_name", + "signature": "setName(entity, name) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "The entity id.", + "pt": "O id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "New name, at most 63 characters.", + "pt": "Novo nome, até 63 caracteres." + } + ], + "returns": { + "type": "boolean", + "en": "false when the entity is not alive.", + "pt": "false se a entidade não estiver viva." + }, + "en": "Names an entity so it can be found later.", + "pt": "Dá um nome a uma entidade para a poder encontrar depois.", + "example": "caffeine.entity.setName(eid, \"Boss\")" + }, + { + "name": "find", + "lua": "caffeine.entity.find", + "dryad": "caffeine_entity_find", + "signature": "find(name) -> number", + "params": [ + { + "name": "name", + "type": "string", + "en": "Exact name to look for.", + "pt": "Nome exato a procurar." + } + ], + "returns": { + "type": "number", + "en": "The lowest matching entity id, or 0 when none.", + "pt": "O menor id que corresponde, ou 0 se nenhum." + }, + "en": "Finds an entity by name.", + "pt": "Encontra uma entidade pelo nome.", + "example": "local boss = caffeine.entity.find(\"Boss\")" + }, + { + "name": "findAll", + "lua": "caffeine.entity.findAll", + "dryad": "caffeine_entity_find_all", + "signature": "findAll(name) -> table", + "params": [ + { + "name": "name", + "type": "string", + "en": "Exact name to look for.", + "pt": "Nome exato a procurar." + } + ], + "returns": { + "type": "table", + "en": "Array of matching entity ids, ascending (empty when none).", + "pt": "Array de ids que correspondem, por ordem crescente (vazio se nenhum)." + }, + "en": "Finds every entity with a name.", + "pt": "Encontra todas as entidades com um nome.", + "example": "for _, id in ipairs(caffeine.entity.findAll(\"Coin\")) do caffeine.world.destroy(id) end" + }, + { + "name": "isAlive", + "lua": "caffeine.entity.isAlive", + "dryad": null, + "signature": "isAlive(entity) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "The entity id.", + "pt": "O id da entidade." + } + ], + "returns": { + "type": "boolean", + "en": "true when the entity exists.", + "pt": "true se a entidade existir." + }, + "en": "Tells whether an id still refers to a live entity. Dryad: use caffeine_world_is_alive.", + "pt": "Indica se um id ainda refere uma entidade viva. Dryad: usar caffeine_world_is_alive.", + "example": "if caffeine.entity.isAlive(target) then end" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/events.json b/src/caffeine/script/api/events.json new file mode 100644 index 00000000..7def3cef --- /dev/null +++ b/src/caffeine/script/api/events.json @@ -0,0 +1,86 @@ +{ + "namespace": "events", + "group": "Game", + "lua": "caffeine.events", + "dryad_prefix": null, + "title": { + "en": "Events", + "pt": "Eventos" + }, + "summary": { + "en": "A simple named-event bus: subscribe, emit and unsubscribe.", + "pt": "Um barramento simples de eventos nomeados: subscrever, emitir e cancelar a subscrição." + }, + "functions": [ + { + "name": "on", + "lua": "caffeine.events.on", + "dryad": null, + "signature": "on(eventName, callback) -> integer", + "params": [ + { + "name": "eventName", + "type": "string", + "en": "Event name.", + "pt": "Nome do evento." + }, + { + "name": "callback", + "type": "function", + "en": "Called with the arguments given to emit.", + "pt": "Chamada com os argumentos passados a emit." + } + ], + "returns": { + "type": "integer", + "en": "Handler handle for off.", + "pt": "Handle do handler para off." + }, + "en": "Subscribes a callback to a named event.", + "pt": "Subscreve um callback a um evento nomeado.", + "example": "local h = caffeine.events.on('hit', function(dmg) end)" + }, + { + "name": "emit", + "lua": "caffeine.events.emit", + "dryad": null, + "signature": "emit(eventName, ...)", + "params": [ + { + "name": "eventName", + "type": "string", + "en": "Event name.", + "pt": "Nome do evento." + }, + { + "name": "...", + "type": "any", + "en": "Arguments passed to each handler.", + "pt": "Argumentos passados a cada handler." + } + ], + "returns": null, + "en": "Calls every handler of the event in registration order. A handler error is logged and does not stop the others.", + "pt": "Chama todos os handlers do evento por ordem de registo. Um erro num handler é registado e não impede os outros.", + "example": "caffeine.events.emit('hit', 10)" + }, + { + "name": "off", + "lua": "caffeine.events.off", + "dryad": null, + "signature": "off(handle)", + "params": [ + { + "name": "handle", + "type": "integer", + "en": "Handle returned by on.", + "pt": "Handle devolvido por on." + } + ], + "returns": null, + "en": "Removes a handler.", + "pt": "Remove um handler.", + "example": "caffeine.events.off(h)" + } + ] +} diff --git a/src/caffeine/script/api/forwardrender.json b/src/caffeine/script/api/forwardrender.json new file mode 100644 index 00000000..460f4a6d --- /dev/null +++ b/src/caffeine/script/api/forwardrender.json @@ -0,0 +1,188 @@ +{ + "namespace": "forwardrender", + "group": "Rendering", + "lua": "caffeine.forwardrender", + "dryad_prefix": null, + "title": { + "en": "Forward render", + "pt": "Render forward" + }, + "summary": { + "en": "Per-entity forward renderer features: instancing, image-based lighting, occlusion, reflections and volumetrics.", + "pt": "Funcionalidades do renderer forward por entidade: instancing, iluminação baseada em imagem, oclusão, reflexos e volumétricos." + }, + "functions": [ + { + "name": "ensure", + "lua": "caffeine.forwardrender.ensure", + "dryad": null, + "signature": "ensure(entity) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "boolean", + "en": "false if the entity is invalid.", + "pt": "false se a entidade for inválida." + }, + "en": "Adds the forward-render features component to the entity if missing. The setters below do nothing without it.", + "pt": "Adiciona à entidade o componente de funcionalidades do render forward, se faltar. Os setters abaixo não fazem nada sem ele.", + "example": "caffeine.forwardrender.ensure(cam)" + }, + { + "name": "setInstancing", + "lua": "caffeine.forwardrender.setInstancing", + "dryad": null, + "signature": "setInstancing(entity, enabled, maxBatch)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "enabled", + "type": "boolean", + "en": "Turns the feature on or off.", + "pt": "Liga ou desliga a funcionalidade." + }, + { + "name": "maxBatch", + "type": "number", + "en": "Maximum instances per batch. Optional.", + "pt": "Máximo de instâncias por lote. Opcional." + } + ], + "returns": null, + "en": "Configures GPU instancing.", + "pt": "Configura o instancing na GPU.", + "example": "caffeine.forwardrender.setInstancing(cam, true, 256)" + }, + { + "name": "setIbl", + "lua": "caffeine.forwardrender.setIbl", + "dryad": null, + "signature": "setIbl(entity, enabled, diffuse, specular)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "enabled", + "type": "boolean", + "en": "Turns the feature on or off.", + "pt": "Liga ou desliga a funcionalidade." + }, + { + "name": "diffuse", + "type": "number", + "en": "Diffuse strength. Optional.", + "pt": "Intensidade difusa. Opcional." + }, + { + "name": "specular", + "type": "number", + "en": "Specular strength. Optional.", + "pt": "Intensidade especular. Opcional." + } + ], + "returns": null, + "en": "Configures image-based lighting.", + "pt": "Configura a iluminação baseada em imagem.", + "example": "caffeine.forwardrender.setIbl(cam, true, 1.0, 1.0)" + }, + { + "name": "setOcclusion", + "lua": "caffeine.forwardrender.setOcclusion", + "dryad": null, + "signature": "setOcclusion(entity, enabled)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "enabled", + "type": "boolean", + "en": "Turns the feature on or off.", + "pt": "Liga ou desliga a funcionalidade." + } + ], + "returns": null, + "en": "Turns occlusion on or off.", + "pt": "Liga ou desliga a oclusão.", + "example": "caffeine.forwardrender.setOcclusion(cam, true)" + }, + { + "name": "setReflections", + "lua": "caffeine.forwardrender.setReflections", + "dryad": null, + "signature": "setReflections(entity, enabled, mode)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "enabled", + "type": "boolean", + "en": "Turns the feature on or off.", + "pt": "Liga ou desliga a funcionalidade." + }, + { + "name": "mode", + "type": "number", + "en": "0 Off, 1 Planar, 2 ScreenSpace, 3 Probe; clamped to 0..3. Optional.", + "pt": "0 Off, 1 Planar, 2 ScreenSpace, 3 Probe; limitado a 0..3. Opcional." + } + ], + "returns": null, + "en": "Configures reflections and their mode.", + "pt": "Configura os reflexos e o respetivo modo.", + "example": "caffeine.forwardrender.setReflections(cam, true, 2)" + }, + { + "name": "setVolumetrics", + "lua": "caffeine.forwardrender.setVolumetrics", + "dryad": null, + "signature": "setVolumetrics(entity, enabled, quality)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "enabled", + "type": "boolean", + "en": "Turns the feature on or off.", + "pt": "Liga ou desliga a funcionalidade." + }, + { + "name": "quality", + "type": "number", + "en": "0 Off, 1 Low, 2 Medium, 3 High; clamped to 0..3. Optional.", + "pt": "0 Off, 1 Low, 2 Medium, 3 High; limitado a 0..3. Opcional." + } + ], + "returns": null, + "en": "Configures volumetric fog and its quality.", + "pt": "Configura o nevoeiro volumétrico e a respetiva qualidade.", + "example": "caffeine.forwardrender.setVolumetrics(cam, true, 2)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/gameState.json b/src/caffeine/script/api/gameState.json new file mode 100644 index 00000000..d378ef5b --- /dev/null +++ b/src/caffeine/script/api/gameState.json @@ -0,0 +1,94 @@ +{ + "namespace": "gameState", + "group": "Game", + "lua": "caffeine.gameState", + "dryad_prefix": null, + "title": { + "en": "Game state", + "pt": "Estado de jogo" + }, + "summary": { + "en": "An optional push/pop stack of named game states.", + "pt": "Uma pilha opcional de estados de jogo nomeados." + }, + "functions": [ + { + "name": "push", + "lua": "caffeine.gameState.push", + "dryad": null, + "signature": "push(id)", + "params": [ + { + "name": "id", + "type": "string", + "en": "State id.", + "pt": "Id do estado." + } + ], + "returns": null, + "en": "Pushes a game state onto the stack.", + "pt": "Empilha um estado de jogo.", + "example": "caffeine.gameState.push('pause_menu')" + }, + { + "name": "pop", + "lua": "caffeine.gameState.pop", + "dryad": null, + "signature": "pop() -> boolean", + "params": [], + "returns": { + "type": "boolean", + "en": "The result of the stack pop (see GameStateStack::pop).", + "pt": "O resultado da remoção do topo (ver GameStateStack::pop)." + }, + "en": "Pops the top game state.", + "pt": "Remove o estado de jogo do topo.", + "example": "caffeine.gameState.pop()" + }, + { + "name": "top", + "lua": "caffeine.gameState.top", + "dryad": null, + "signature": "top() -> string", + "params": [], + "returns": { + "type": "string", + "en": "Id of the top state.", + "pt": "Id do estado do topo." + }, + "en": "Returns the id of the top game state.", + "pt": "Devolve o id do estado de jogo do topo.", + "example": "local id = caffeine.gameState.top()" + }, + { + "name": "pause", + "lua": "caffeine.gameState.pause", + "dryad": null, + "signature": "pause() -> boolean", + "params": [], + "returns": { + "type": "boolean", + "en": "Result of pausing the top state.", + "pt": "Resultado de pausar o estado do topo." + }, + "en": "Pauses the top game state.", + "pt": "Pausa o estado de jogo do topo.", + "example": "caffeine.gameState.pause()" + }, + { + "name": "resume", + "lua": "caffeine.gameState.resume", + "dryad": null, + "signature": "resume() -> boolean", + "params": [], + "returns": { + "type": "boolean", + "en": "Result of resuming the top state.", + "pt": "Resultado de retomar o estado do topo." + }, + "en": "Resumes the top game state.", + "pt": "Retoma o estado de jogo do topo.", + "example": "caffeine.gameState.resume()" + } + ] +} diff --git a/src/caffeine/script/api/hierarchy.json b/src/caffeine/script/api/hierarchy.json new file mode 100644 index 00000000..722a5578 --- /dev/null +++ b/src/caffeine/script/api/hierarchy.json @@ -0,0 +1,154 @@ +{ + "namespace": "hierarchy", + "group": "Core", + "lua": "caffeine.hierarchy", + "dryad_prefix": "caffeine_hierarchy_", + "title": { + "en": "Hierarchy", + "pt": "Hierarquia" + }, + "summary": { + "en": "Parent and child links between entities. A child's transform is composed with its parent's.", + "pt": "Ligações pai e filho entre entidades. O transform do filho compõe-se com o do pai." + }, + "functions": [ + { + "name": "parent", + "lua": "caffeine.hierarchy.parent", + "dryad": "caffeine_hierarchy_parent", + "signature": "parent(entity) -> number", + "params": [ + { + "name": "entity", + "type": "number", + "en": "The entity id.", + "pt": "O id da entidade." + } + ], + "returns": { + "type": "number", + "en": "The parent id, or 0 when it has none.", + "pt": "O id do pai, ou 0 se não tiver." + }, + "en": "Returns the parent of an entity.", + "pt": "Devolve o pai de uma entidade.", + "example": "local p = caffeine.hierarchy.parent(eid)" + }, + { + "name": "setParent", + "lua": "caffeine.hierarchy.setParent", + "dryad": "caffeine_hierarchy_set_parent", + "signature": "setParent(entity, parent) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "The child.", + "pt": "O filho." + }, + { + "name": "parent", + "type": "number", + "en": "The new parent; 0 detaches.", + "pt": "O novo pai; 0 desliga." + } + ], + "returns": { + "type": "boolean", + "en": "false when either entity is dead, the parent is the entity itself, or the link would create a cycle.", + "pt": "false se uma das entidades estiver morta, o pai for a própria entidade ou a ligação criar um ciclo." + }, + "en": "Attaches an entity under another.", + "pt": "Liga uma entidade por baixo de outra.", + "example": "caffeine.hierarchy.setParent(wheel, car)" + }, + { + "name": "detach", + "lua": "caffeine.hierarchy.detach", + "dryad": "caffeine_hierarchy_detach", + "signature": "detach(entity) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "The entity id.", + "pt": "O id da entidade." + } + ], + "returns": { + "type": "boolean", + "en": "false when the entity is dead.", + "pt": "false se a entidade estiver morta." + }, + "en": "Removes the parent link.", + "pt": "Remove a ligação ao pai.", + "example": "caffeine.hierarchy.detach(wheel)" + }, + { + "name": "children", + "lua": "caffeine.hierarchy.children", + "dryad": "caffeine_hierarchy_children", + "signature": "children(entity) -> table", + "params": [ + { + "name": "entity", + "type": "number", + "en": "The entity id.", + "pt": "O id da entidade." + } + ], + "returns": { + "type": "table", + "en": "Array of direct child ids, ascending.", + "pt": "Array de ids dos filhos diretos, por ordem crescente." + }, + "en": "Lists the direct children of an entity.", + "pt": "Lista os filhos diretos de uma entidade.", + "example": "for _, c in ipairs(caffeine.hierarchy.children(car)) do end" + }, + { + "name": "childCount", + "lua": "caffeine.hierarchy.childCount", + "dryad": "caffeine_hierarchy_child_count", + "signature": "childCount(entity) -> number", + "params": [ + { + "name": "entity", + "type": "number", + "en": "The entity id.", + "pt": "O id da entidade." + } + ], + "returns": { + "type": "number", + "en": "Number of direct children.", + "pt": "Número de filhos diretos." + }, + "en": "Counts the direct children.", + "pt": "Conta os filhos diretos.", + "example": "local n = caffeine.hierarchy.childCount(car)" + }, + { + "name": "root", + "lua": "caffeine.hierarchy.root", + "dryad": "caffeine_hierarchy_root", + "signature": "root(entity) -> number", + "params": [ + { + "name": "entity", + "type": "number", + "en": "The entity id.", + "pt": "O id da entidade." + } + ], + "returns": { + "type": "number", + "en": "The topmost ancestor (the entity itself when it has no parent).", + "pt": "O antepassado de topo (a própria entidade se não tiver pai)." + }, + "en": "Walks up to the top of the hierarchy.", + "pt": "Sobe até ao topo da hierarquia.", + "example": "local top = caffeine.hierarchy.root(wheel)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/input.json b/src/caffeine/script/api/input.json new file mode 100644 index 00000000..2fe15934 --- /dev/null +++ b/src/caffeine/script/api/input.json @@ -0,0 +1,216 @@ +{ + "namespace": "input", + "group": "Input", + "lua": "caffeine.input", + "dryad_prefix": "caffeine_input_", + "title": { + "en": "Input", + "pt": "Entrada" + }, + "summary": { + "en": "Keyboard, mapped axes and actions, and the mouse. Dryad mirrors them with caffeine_input_* natives.", + "pt": "Teclado, eixos e ações mapeados e o rato. O Dryad espelha-os com as natives caffeine_input_*." + }, + "functions": [ + { + "name": "isKeyDown", + "lua": "caffeine.input.isKeyDown", + "dryad": "caffeine_input_key_down", + "signature": "isKeyDown(name) -> boolean", + "params": [ + { + "name": "name", + "type": "string", + "en": "Key name such as \"Space\", \"W\", \"Up\", \"LShift\", \"Escape\", \"0\"-\"9\".", + "pt": "Nome da tecla, como \"Space\", \"W\", \"Up\", \"LShift\", \"Escape\", \"0\"-\"9\"." + } + ], + "returns": { + "type": "boolean", + "en": "True while the key is held; false for an unknown name or without input.", + "pt": "Verdadeiro enquanto a tecla está premida; falso para um nome desconhecido ou sem entrada." + }, + "en": "Checks whether a keyboard key is held.", + "pt": "Verifica se uma tecla do teclado está premida.", + "example": "if caffeine.input.isKeyDown('Space') then end" + }, + { + "name": "getAxis", + "lua": "caffeine.input.getAxis", + "dryad": "caffeine_input_axis", + "signature": "getAxis(name) -> number", + "params": [ + { + "name": "name", + "type": "string", + "en": "Axis: Horizontal, Vertical, LookX, LookY.", + "pt": "Eixo: Horizontal, Vertical, LookX, LookY." + } + ], + "returns": { + "type": "number", + "en": "Axis value; 0 for an unknown name or without input.", + "pt": "Valor do eixo; 0 para um nome desconhecido ou sem entrada." + }, + "en": "Reads a mapped input axis.", + "pt": "Lê um eixo de entrada mapeado.", + "example": "local h = caffeine.input.getAxis('Horizontal')" + }, + { + "name": "isActionDown", + "lua": "caffeine.input.isActionDown", + "dryad": "caffeine_input_action_down", + "signature": "isActionDown(name) -> boolean", + "params": [ + { + "name": "name", + "type": "string", + "en": "Action: MoveUp, MoveDown, MoveLeft, MoveRight, Jump, Attack, Interact, Pause.", + "pt": "Ação: MoveUp, MoveDown, MoveLeft, MoveRight, Jump, Attack, Interact, Pause." + } + ], + "returns": { + "type": "boolean", + "en": "True while the action is held.", + "pt": "Verdadeiro enquanto a ação está ativa." + }, + "en": "Checks whether a mapped action is held.", + "pt": "Verifica se uma ação mapeada está ativa.", + "example": "if caffeine.input.isActionDown('Jump') then end" + }, + { + "name": "isActionPressed", + "lua": "caffeine.input.isActionPressed", + "dryad": "caffeine_input_action_pressed", + "signature": "isActionPressed(name) -> boolean", + "params": [ + { + "name": "name", + "type": "string", + "en": "Action: MoveUp, MoveDown, MoveLeft, MoveRight, Jump, Attack, Interact, Pause.", + "pt": "Ação: MoveUp, MoveDown, MoveLeft, MoveRight, Jump, Attack, Interact, Pause." + } + ], + "returns": { + "type": "boolean", + "en": "True only on the frame the action started.", + "pt": "Verdadeiro apenas no frame em que a ação começou." + }, + "en": "Checks whether a mapped action was just pressed this frame.", + "pt": "Verifica se uma ação mapeada acabou de ser premida neste frame.", + "example": "if caffeine.input.isActionPressed('Attack') then end" + }, + { + "name": "mouseDelta", + "lua": "caffeine.input.mouseDelta", + "dryad": null, + "signature": "mouseDelta() -> number, number", + "params": [], + "returns": { + "type": "number, number", + "en": "dx, dy (two return values).", + "pt": "dx, dy (dois valores de retorno)." + }, + "en": "Mouse movement since the previous frame. Returns two values, not a table.", + "pt": "Movimento do rato desde o frame anterior. Devolve dois valores, não uma tabela.", + "example": "local dx, dy = caffeine.input.mouseDelta()" + }, + { + "name": "mousePosition", + "lua": "caffeine.input.mousePosition", + "dryad": null, + "signature": "mousePosition() -> number, number", + "params": [], + "returns": { + "type": "number, number", + "en": "x, y (two return values).", + "pt": "x, y (dois valores de retorno)." + }, + "en": "Mouse position as reported by the input manager. Returns two values, not a table.", + "pt": "Posição do rato conforme indicada pelo gestor de entrada. Devolve dois valores, não uma tabela.", + "example": "local mx, my = caffeine.input.mousePosition()" + }, + { + "name": "isMouseButtonDown", + "lua": "caffeine.input.isMouseButtonDown", + "dryad": "caffeine_input_mouse_down", + "signature": "isMouseButtonDown(button) -> boolean", + "params": [ + { + "name": "button", + "type": "integer", + "en": "1 left, 2 middle, 3 right.", + "pt": "1 esquerdo, 2 do meio, 3 direito." + } + ], + "returns": { + "type": "boolean", + "en": "True while held; false for any other number.", + "pt": "Verdadeiro enquanto premido; falso para qualquer outro número." + }, + "en": "Checks whether a mouse button is held.", + "pt": "Verifica se um botão do rato está premido.", + "example": "if caffeine.input.isMouseButtonDown(1) then end" + }, + { + "name": "caffeine_input_mouse_x", + "lua": null, + "dryad": "caffeine_input_mouse_x", + "signature": "caffeine_input_mouse_x() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Mouse x position; 0 without input.", + "pt": "Rato: posição x; 0 sem entrada." + }, + "en": "Dryad only: mouse x position.", + "pt": "Apenas Dryad: rato, posição x.", + "example": "let v = caffeine_input_mouse_x();" + }, + { + "name": "caffeine_input_mouse_y", + "lua": null, + "dryad": "caffeine_input_mouse_y", + "signature": "caffeine_input_mouse_y() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Mouse y position; 0 without input.", + "pt": "Rato: posição y; 0 sem entrada." + }, + "en": "Dryad only: mouse y position.", + "pt": "Apenas Dryad: rato, posição y.", + "example": "let v = caffeine_input_mouse_y();" + }, + { + "name": "caffeine_input_mouse_dx", + "lua": null, + "dryad": "caffeine_input_mouse_dx", + "signature": "caffeine_input_mouse_dx() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Mouse x movement since the previous frame; 0 without input.", + "pt": "Rato: movimento x desde o frame anterior; 0 sem entrada." + }, + "en": "Dryad only: mouse x movement since the previous frame.", + "pt": "Apenas Dryad: rato, movimento x desde o frame anterior.", + "example": "let v = caffeine_input_mouse_dx();" + }, + { + "name": "caffeine_input_mouse_dy", + "lua": null, + "dryad": "caffeine_input_mouse_dy", + "signature": "caffeine_input_mouse_dy() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Mouse y movement since the previous frame; 0 without input.", + "pt": "Rato: movimento y desde o frame anterior; 0 sem entrada." + }, + "en": "Dryad only: mouse y movement since the previous frame.", + "pt": "Apenas Dryad: rato, movimento y desde o frame anterior.", + "example": "let v = caffeine_input_mouse_dy();" + } + ] +} diff --git a/src/caffeine/script/api/map.json b/src/caffeine/script/api/map.json new file mode 100644 index 00000000..33a30d7e --- /dev/null +++ b/src/caffeine/script/api/map.json @@ -0,0 +1,38 @@ +{ + "namespace": "map", + "group": "World", + "lua": "caffeine.map", + "dryad_prefix": null, + "title": { + "en": "Map", + "pt": "Mapa" + }, + "summary": { + "en": "Hooks for map surface chunk requests.", + "pt": "Ganchos para pedidos de chunks de superfícies de mapa." + }, + "functions": [ + { + "name": "onChunkRequest", + "lua": "caffeine.map.onChunkRequest", + "dryad": null, + "signature": "onChunkRequest(callback) -> number", + "params": [ + { + "name": "callback", + "type": "function", + "en": "Called with a payload table: `surfaceEntityId`, `chunkX`, `chunkY`, `worldMinX`, `worldMinY`, `chunkSize`.", + "pt": "Chamada com uma tabela: `surfaceEntityId`, `chunkX`, `chunkY`, `worldMinX`, `worldMinY`, `chunkSize`." + } + ], + "returns": { + "type": "number", + "en": "Event handler handle.", + "pt": "Handle do handler de evento." + }, + "en": "Registers a handler for the `mapChunkRequest` event raised when a map surface requests a chunk.", + "pt": "Regista um handler para o evento `mapChunkRequest`, gerado quando uma superfície de mapa pede um chunk.", + "example": "caffeine.map.onChunkRequest(function(req)\n print(req.chunkX, req.chunkY)\nend)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/math.json b/src/caffeine/script/api/math.json new file mode 100644 index 00000000..8d727868 --- /dev/null +++ b/src/caffeine/script/api/math.json @@ -0,0 +1,678 @@ +{ + "namespace": "math", + "group": "Core", + "lua": "caffeine.math", + "dryad_prefix": null, + "title": { + "en": "Math", + "pt": "Matemática" + }, + "summary": { + "en": "Vector tables ({x, y[, z]}), scalar helpers and angle conversion. Also defines the constants caffeine.math.pi and caffeine.math.epsilon (1e-5).", + "pt": "Tabelas de vetor ({x, y[, z]}), auxiliares escalares e conversão de ângulos. Define também as constantes caffeine.math.pi e caffeine.math.epsilon (1e-5)." + }, + "functions": [ + { + "name": "vec2", + "lua": "caffeine.math.vec2", + "dryad": null, + "signature": "vec2(x, y) -> table", + "params": [ + { + "name": "x", + "type": "number", + "en": "X.", + "pt": "X." + }, + { + "name": "y", + "type": "number", + "en": "Y.", + "pt": "Y." + } + ], + "returns": { + "type": "table", + "en": "{x, y}", + "pt": "{x, y}" + }, + "en": "Creates a 2D vector table.", + "pt": "Cria uma tabela de vetor 2D.", + "example": "local v = caffeine.math.vec2(1, 2)" + }, + { + "name": "vec3", + "lua": "caffeine.math.vec3", + "dryad": null, + "signature": "vec3(x, y, z) -> table", + "params": [ + { + "name": "x", + "type": "number", + "en": "X.", + "pt": "X." + }, + { + "name": "y", + "type": "number", + "en": "Y.", + "pt": "Y." + }, + { + "name": "z", + "type": "number", + "en": "Z.", + "pt": "Z." + } + ], + "returns": { + "type": "table", + "en": "{x, y, z}", + "pt": "{x, y, z}" + }, + "en": "Creates a 3D vector table.", + "pt": "Cria uma tabela de vetor 3D.", + "example": "local v = caffeine.math.vec3(1, 2, 3)" + }, + { + "name": "add", + "lua": "caffeine.math.add", + "dryad": null, + "signature": "add(a, b) -> table", + "params": [ + { + "name": "a", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + }, + { + "name": "b", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + } + ], + "returns": { + "type": "table", + "en": "Vector table; has z only when an operand has z.", + "pt": "Tabela de vetor; só tem z se um operando tiver z." + }, + "en": "Component-wise sum of two vectors.", + "pt": "Soma componente a componente de dois vetores.", + "example": "local p = caffeine.math.add(a, b)" + }, + { + "name": "sub", + "lua": "caffeine.math.sub", + "dryad": null, + "signature": "sub(a, b) -> table", + "params": [ + { + "name": "a", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + }, + { + "name": "b", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + } + ], + "returns": { + "type": "table", + "en": "Vector table; has z only when an operand has z.", + "pt": "Tabela de vetor; só tem z se um operando tiver z." + }, + "en": "Component-wise difference a - b.", + "pt": "Diferença componente a componente a - b.", + "example": "local d = caffeine.math.sub(a, b)" + }, + { + "name": "mul", + "lua": "caffeine.math.mul", + "dryad": null, + "signature": "mul(a, b) -> table", + "params": [ + { + "name": "a", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + }, + { + "name": "b", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + } + ], + "returns": { + "type": "table", + "en": "Vector table; has z only when an operand has z.", + "pt": "Tabela de vetor; só tem z se um operando tiver z." + }, + "en": "Component-wise product of two vectors (not a dot product).", + "pt": "Produto componente a componente de dois vetores (não é o produto escalar).", + "example": "local m = caffeine.math.mul(a, b)" + }, + { + "name": "scale", + "lua": "caffeine.math.scale", + "dryad": null, + "signature": "scale(v, s) -> table", + "params": [ + { + "name": "v", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + }, + { + "name": "s", + "type": "number", + "en": "Scalar factor.", + "pt": "Fator escalar." + } + ], + "returns": { + "type": "table", + "en": "Scaled vector.", + "pt": "Vetor escalado." + }, + "en": "Multiplies a vector by a scalar.", + "pt": "Multiplica um vetor por um escalar.", + "example": "local v2 = caffeine.math.scale(v, 2)" + }, + { + "name": "dot", + "lua": "caffeine.math.dot", + "dryad": null, + "signature": "dot(a, b) -> number", + "params": [ + { + "name": "a", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + }, + { + "name": "b", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + } + ], + "returns": { + "type": "number", + "en": "Dot product.", + "pt": "Produto escalar." + }, + "en": "Dot product of two vectors; a missing z counts as 0.", + "pt": "Produto escalar de dois vetores; um z em falta conta como 0.", + "example": "local d = caffeine.math.dot(a, b)" + }, + { + "name": "cross", + "lua": "caffeine.math.cross", + "dryad": null, + "signature": "cross(a, b) -> table", + "params": [ + { + "name": "a", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + }, + { + "name": "b", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + } + ], + "returns": { + "type": "table", + "en": "{x, y, z} vector.", + "pt": "Vetor {x, y, z}." + }, + "en": "Cross product; the result is always 3D.", + "pt": "Produto vetorial; o resultado é sempre 3D.", + "example": "local n = caffeine.math.cross(a, b)" + }, + { + "name": "length", + "lua": "caffeine.math.length", + "dryad": null, + "signature": "length(v) -> number", + "params": [ + { + "name": "v", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + } + ], + "returns": { + "type": "number", + "en": "Vector length.", + "pt": "Comprimento do vetor." + }, + "en": "Length of a vector.", + "pt": "Comprimento de um vetor.", + "example": "local l = caffeine.math.length(v)" + }, + { + "name": "lengthSquared", + "lua": "caffeine.math.lengthSquared", + "dryad": null, + "signature": "lengthSquared(v) -> number", + "params": [ + { + "name": "v", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + } + ], + "returns": { + "type": "number", + "en": "Squared length.", + "pt": "Comprimento ao quadrado." + }, + "en": "Squared length of a vector, without the square root.", + "pt": "Comprimento ao quadrado de um vetor, sem a raiz quadrada.", + "example": "local l2 = caffeine.math.lengthSquared(v)" + }, + { + "name": "distance", + "lua": "caffeine.math.distance", + "dryad": null, + "signature": "distance(a, b) -> number", + "params": [ + { + "name": "a", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + }, + { + "name": "b", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + } + ], + "returns": { + "type": "number", + "en": "Distance between the points.", + "pt": "Distância entre os pontos." + }, + "en": "Distance between two points.", + "pt": "Distância entre dois pontos.", + "example": "local d = caffeine.math.distance(a, b)" + }, + { + "name": "normalize", + "lua": "caffeine.math.normalize", + "dryad": null, + "signature": "normalize(v) -> table", + "params": [ + { + "name": "v", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + } + ], + "returns": { + "type": "table", + "en": "Unit vector, or zeros when the length is at most 0.0001.", + "pt": "Vetor unitário, ou zeros se o comprimento for no máximo 0.0001." + }, + "en": "Returns the vector scaled to length 1.", + "pt": "Devolve o vetor escalado para comprimento 1.", + "example": "local dir = caffeine.math.normalize(caffeine.math.sub(b, a))" + }, + { + "name": "lerpVec", + "lua": "caffeine.math.lerpVec", + "dryad": null, + "signature": "lerpVec(a, b, t) -> table", + "params": [ + { + "name": "a", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + }, + { + "name": "b", + "type": "table", + "en": "Vector table {x, y[, z]}.", + "pt": "Tabela de vetor {x, y[, z]}." + }, + { + "name": "t", + "type": "number", + "en": "Blend factor; not clamped.", + "pt": "Fator de mistura; não é limitado." + } + ], + "returns": { + "type": "table", + "en": "Vector table; has z only when an operand has z.", + "pt": "Tabela de vetor; só tem z se um operando tiver z." + }, + "en": "Linear interpolation between two vectors.", + "pt": "Interpolação linear entre dois vetores.", + "example": "local mid = caffeine.math.lerpVec(a, b, 0.5)" + }, + { + "name": "clamp", + "lua": "caffeine.math.clamp", + "dryad": null, + "signature": "clamp(v, lo, hi) -> number", + "params": [ + { + "name": "v", + "type": "number", + "en": "Value.", + "pt": "Valor." + }, + { + "name": "lo", + "type": "number", + "en": "Lower bound.", + "pt": "Limite inferior." + }, + { + "name": "hi", + "type": "number", + "en": "Upper bound.", + "pt": "Limite superior." + } + ], + "returns": { + "type": "number", + "en": "Clamped value.", + "pt": "Valor limitado." + }, + "en": "Limits a value to a range; swapped bounds are accepted.", + "pt": "Limita um valor a um intervalo; limites trocados são aceites.", + "example": "local hp = caffeine.math.clamp(hp, 0, 100)" + }, + { + "name": "clamp01", + "lua": "caffeine.math.clamp01", + "dryad": null, + "signature": "clamp01(v) -> number", + "params": [ + { + "name": "v", + "type": "number", + "en": "Value.", + "pt": "Valor." + } + ], + "returns": { + "type": "number", + "en": "Value limited to 0..1.", + "pt": "Valor limitado a 0..1." + }, + "en": "Limits a value to 0..1.", + "pt": "Limita um valor a 0..1.", + "example": "local t = caffeine.math.clamp01(t)" + }, + { + "name": "lerp", + "lua": "caffeine.math.lerp", + "dryad": null, + "signature": "lerp(a, b, t) -> number", + "params": [ + { + "name": "a", + "type": "number", + "en": "Start.", + "pt": "Início." + }, + { + "name": "b", + "type": "number", + "en": "End.", + "pt": "Fim." + }, + { + "name": "t", + "type": "number", + "en": "Blend factor; not clamped.", + "pt": "Fator de mistura; não é limitado." + } + ], + "returns": { + "type": "number", + "en": "a + (b - a) * t", + "pt": "a + (b - a) * t" + }, + "en": "Linear interpolation between two numbers.", + "pt": "Interpolação linear entre dois números.", + "example": "local x = caffeine.math.lerp(0, 10, 0.25)" + }, + { + "name": "inverseLerp", + "lua": "caffeine.math.inverseLerp", + "dryad": null, + "signature": "inverseLerp(a, b, v) -> number", + "params": [ + { + "name": "a", + "type": "number", + "en": "Start.", + "pt": "Início." + }, + { + "name": "b", + "type": "number", + "en": "End.", + "pt": "Fim." + }, + { + "name": "v", + "type": "number", + "en": "Value.", + "pt": "Valor." + } + ], + "returns": { + "type": "number", + "en": "Position of v between a and b; 0 when a and b are equal.", + "pt": "Posição de v entre a e b; 0 se a e b forem iguais." + }, + "en": "The inverse of lerp; the result is not clamped.", + "pt": "O inverso de lerp; o resultado não é limitado.", + "example": "local t = caffeine.math.inverseLerp(0, 10, 5)" + }, + { + "name": "remap", + "lua": "caffeine.math.remap", + "dryad": null, + "signature": "remap(v, inLo, inHi, outLo, outHi) -> number", + "params": [ + { + "name": "v", + "type": "number", + "en": "Value.", + "pt": "Valor." + }, + { + "name": "inLo", + "type": "number", + "en": "Input range start.", + "pt": "Início do intervalo de entrada." + }, + { + "name": "inHi", + "type": "number", + "en": "Input range end.", + "pt": "Fim do intervalo de entrada." + }, + { + "name": "outLo", + "type": "number", + "en": "Output range start.", + "pt": "Início do intervalo de saída." + }, + { + "name": "outHi", + "type": "number", + "en": "Output range end.", + "pt": "Fim do intervalo de saída." + } + ], + "returns": { + "type": "number", + "en": "Remapped value (not clamped).", + "pt": "Valor remapeado (não limitado)." + }, + "en": "Maps a value from one range to another.", + "pt": "Mapeia um valor de um intervalo para outro.", + "example": "local pct = caffeine.math.remap(hp, 0, 100, 0, 1)" + }, + { + "name": "smoothstep", + "lua": "caffeine.math.smoothstep", + "dryad": null, + "signature": "smoothstep(e0, e1, v) -> number", + "params": [ + { + "name": "e0", + "type": "number", + "en": "Lower edge.", + "pt": "Limite inferior." + }, + { + "name": "e1", + "type": "number", + "en": "Upper edge.", + "pt": "Limite superior." + }, + { + "name": "v", + "type": "number", + "en": "Value.", + "pt": "Valor." + } + ], + "returns": { + "type": "number", + "en": "Smooth value in 0..1.", + "pt": "Valor suave entre 0 e 1." + }, + "en": "Smooth Hermite interpolation between two edges.", + "pt": "Interpolação suave de Hermite entre dois limites.", + "example": "local s = caffeine.math.smoothstep(0, 1, t)" + }, + { + "name": "approach", + "lua": "caffeine.math.approach", + "dryad": null, + "signature": "approach(cur, target, step) -> number", + "params": [ + { + "name": "cur", + "type": "number", + "en": "Current value.", + "pt": "Valor atual." + }, + { + "name": "target", + "type": "number", + "en": "Target value.", + "pt": "Valor alvo." + }, + { + "name": "step", + "type": "number", + "en": "Maximum change; its absolute value is used.", + "pt": "Mudança máxima; usa-se o valor absoluto." + } + ], + "returns": { + "type": "number", + "en": "New value, never past the target.", + "pt": "Novo valor, nunca além do alvo." + }, + "en": "Moves a value toward a target by at most step.", + "pt": "Move um valor para um alvo em no máximo step.", + "example": "speed = caffeine.math.approach(speed, 0, 20 * caffeine.time.delta())" + }, + { + "name": "sign", + "lua": "caffeine.math.sign", + "dryad": null, + "signature": "sign(v) -> number", + "params": [ + { + "name": "v", + "type": "number", + "en": "Value.", + "pt": "Valor." + } + ], + "returns": { + "type": "number", + "en": "-1, 0 or 1.", + "pt": "-1, 0 ou 1." + }, + "en": "Sign of a number.", + "pt": "Sinal de um número.", + "example": "local s = caffeine.math.sign(-3)" + }, + { + "name": "radians", + "lua": "caffeine.math.radians", + "dryad": null, + "signature": "radians(deg) -> number", + "params": [ + { + "name": "deg", + "type": "number", + "en": "Degrees.", + "pt": "Graus." + } + ], + "returns": { + "type": "number", + "en": "Radians.", + "pt": "Radianos." + }, + "en": "Converts degrees to radians.", + "pt": "Converte graus em radianos.", + "example": "local r = caffeine.math.radians(90)" + }, + { + "name": "degrees", + "lua": "caffeine.math.degrees", + "dryad": null, + "signature": "degrees(rad) -> number", + "params": [ + { + "name": "rad", + "type": "number", + "en": "Radians.", + "pt": "Radianos." + } + ], + "returns": { + "type": "number", + "en": "Degrees.", + "pt": "Graus." + }, + "en": "Converts radians to degrees.", + "pt": "Converte radianos em graus.", + "example": "local d = caffeine.math.degrees(caffeine.math.pi)" + } + ] +} diff --git a/src/caffeine/script/api/native.json b/src/caffeine/script/api/native.json new file mode 100644 index 00000000..08d58831 --- /dev/null +++ b/src/caffeine/script/api/native.json @@ -0,0 +1,72 @@ +{ + "namespace": "native", + "group": "Game", + "lua": "caffeine.native", + "dryad_prefix": null, + "title": { + "en": "Native modules", + "pt": "Módulos nativos" + }, + "summary": { + "en": "Load and call native modules through JSON.", + "pt": "Carregar e chamar módulos nativos através de JSON." + }, + "functions": [ + { + "name": "load", + "lua": "caffeine.native.load", + "dryad": null, + "signature": "load(name) -> boolean", + "params": [ + { + "name": "name", + "type": "string", + "en": "Native module name.", + "pt": "Nome do módulo nativo." + } + ], + "returns": { + "type": "boolean", + "en": "True when the module loaded.", + "pt": "Verdadeiro se o módulo foi carregado." + }, + "en": "Loads a native module. The load error is not reported to the script.", + "pt": "Carrega um módulo nativo. O erro de carregamento não é devolvido ao script.", + "example": "caffeine.native.load('mymodule')" + }, + { + "name": "call", + "lua": "caffeine.native.call", + "dryad": null, + "signature": "call(module, fn[, argsJson]) -> string", + "params": [ + { + "name": "module", + "type": "string", + "en": "Module name.", + "pt": "Nome do módulo." + }, + { + "name": "fn", + "type": "string", + "en": "Function name.", + "pt": "Nome da função." + }, + { + "name": "argsJson", + "type": "string", + "en": "JSON arguments (default \"{}\").", + "pt": "Argumentos em JSON (por omissão \"{}\")." + } + ], + "returns": { + "type": "string", + "en": "The result text; on failure the error message is returned instead.", + "pt": "O texto do resultado; em caso de falha devolve-se a mensagem de erro." + }, + "en": "Calls a function of a loaded native module with JSON arguments.", + "pt": "Chama uma função de um módulo nativo carregado com argumentos JSON.", + "example": "local out = caffeine.native.call('mymodule', 'ping', '{}')" + } + ] +} diff --git a/src/caffeine/script/api/navigation.json b/src/caffeine/script/api/navigation.json new file mode 100644 index 00000000..4c92e91f --- /dev/null +++ b/src/caffeine/script/api/navigation.json @@ -0,0 +1,180 @@ +{ + "namespace": "navigation", + "group": "World", + "lua": "caffeine.navigation", + "dryad_prefix": null, + "title": { + "en": "Navigation", + "pt": "Navegação" + }, + "summary": { + "en": "Navigation agents: destinations, patrol points, follow targets and behaviour scripts.", + "pt": "Agentes de navegação: destinos, pontos de patrulha, alvos a seguir e scripts de comportamento." + }, + "functions": [ + { + "name": "setDestination", + "lua": "caffeine.navigation.setDestination", + "dryad": null, + "signature": "setDestination(entity, x, y, z) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "x", + "type": "number", + "en": "World X.", + "pt": "X no mundo." + }, + { + "name": "y", + "type": "number", + "en": "World Y.", + "pt": "Y no mundo." + }, + { + "name": "z", + "type": "number", + "en": "World Z.", + "pt": "Z no mundo." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Sets the agent's destination in world space.", + "pt": "Define o destino do agente no espaço do mundo.", + "example": "caffeine.navigation.setDestination(npc, 10, 0, 5)" + }, + { + "name": "setMode", + "lua": "caffeine.navigation.setMode", + "dryad": null, + "signature": "setMode(entity, mode) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "mode", + "type": "string", + "en": "\"patrol\", \"follow\" or \"scripted\"; any other value means idle.", + "pt": "\"patrol\", \"follow\" ou \"scripted\"; qualquer outro valor significa idle." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Sets the agent's navigation mode.", + "pt": "Define o modo de navegação do agente.", + "example": "caffeine.navigation.setMode(npc, 'patrol')" + }, + { + "name": "addPatrolPoint", + "lua": "caffeine.navigation.addPatrolPoint", + "dryad": null, + "signature": "addPatrolPoint(entity, x, y, z) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "x", + "type": "number", + "en": "World X.", + "pt": "X no mundo." + }, + { + "name": "y", + "type": "number", + "en": "World Y.", + "pt": "Y no mundo." + }, + { + "name": "z", + "type": "number", + "en": "World Z.", + "pt": "Z no mundo." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Appends a point to the agent's patrol route.", + "pt": "Acrescenta um ponto à rota de patrulha do agente.", + "example": "caffeine.navigation.addPatrolPoint(npc, 0, 0, 0)" + }, + { + "name": "setFollowTarget", + "lua": "caffeine.navigation.setFollowTarget", + "dryad": null, + "signature": "setFollowTarget(entity, targetId) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "targetId", + "type": "number", + "en": "Entity id to follow.", + "pt": "Id da entidade a seguir." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Sets the entity the agent follows.", + "pt": "Define a entidade que o agente segue.", + "example": "caffeine.navigation.setFollowTarget(npc, player)" + }, + { + "name": "setBehaviorScript", + "lua": "caffeine.navigation.setBehaviorScript", + "dryad": null, + "signature": "setBehaviorScript(entity, path) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "path", + "type": "string", + "en": "Behaviour script path.", + "pt": "Caminho do script de comportamento." + } + ], + "returns": { + "type": "boolean", + "en": "true on success.", + "pt": "true em caso de sucesso." + }, + "en": "Sets the script that drives the agent in scripted mode.", + "pt": "Define o script que controla o agente no modo scripted.", + "example": "caffeine.navigation.setBehaviorScript(npc, 'scripts/ai.lua')" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/particles.json b/src/caffeine/script/api/particles.json new file mode 100644 index 00000000..b970f987 --- /dev/null +++ b/src/caffeine/script/api/particles.json @@ -0,0 +1,40 @@ +{ + "namespace": "particles", + "group": "Rendering", + "lua": "caffeine.particles", + "dryad_prefix": null, + "title": { + "en": "Particles", + "pt": "Partículas" + }, + "summary": { + "en": "Manual particle emission on entities that have a particle emitter.", + "pt": "Emissão manual de partículas em entidades com um emissor de partículas." + }, + "functions": [ + { + "name": "emit", + "lua": "caffeine.particles.emit", + "dryad": null, + "signature": "emit(entity, count)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "count", + "type": "number", + "en": "Number of particles to spawn; stops at the emitter's maximum.", + "pt": "Número de partículas a criar; pára no máximo do emissor." + } + ], + "returns": null, + "en": "Spawns particles immediately at the entity position with random velocities. Does nothing if the entity has no emitter.", + "pt": "Cria partículas de imediato na posição da entidade com velocidades aleatórias. Não faz nada se a entidade não tiver emissor.", + "example": "caffeine.particles.emit(e, 20)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/physics3d.json b/src/caffeine/script/api/physics3d.json new file mode 100644 index 00000000..5bfdd32b --- /dev/null +++ b/src/caffeine/script/api/physics3d.json @@ -0,0 +1,237 @@ +{ + "namespace": "physics3d", + "group": "Physics", + "lua": "caffeine.physics3d", + "dryad_prefix": "caffeine_physics3d_", + "title": { + "en": "Physics 3D", + "pt": "Física 3D" + }, + "summary": { + "en": "Ray queries and forces on the Bullet 3D world. Everything is a safe no-op (false or nil) when the host runs without 3D physics. Forces and velocity only affect dynamic bodies.", + "pt": "Consultas por raio e forças no mundo 3D Bullet. Tudo é um no-op seguro (false ou nil) quando o host corre sem física 3D. Forças e velocidade só afetam corpos dinâmicos." + }, + "functions": [ + { + "name": "isAvailable", + "lua": "caffeine.physics3d.isAvailable", + "dryad": "caffeine_physics3d_available", + "signature": "isAvailable() -> boolean", + "params": [], + "returns": { + "type": "boolean", + "en": "true when a 3D physics world is attached and the Bullet backend is built in.", + "pt": "true quando há um mundo de física 3D e o backend Bullet está compilado." + }, + "en": "Tells whether 3D physics can be used at all.", + "pt": "Indica se a física 3D pode ser usada.", + "example": "if not caffeine.physics3d.isAvailable() then caffeine.debug.warn(\"no 3D physics\") end" + }, + { + "name": "setGravity", + "lua": "caffeine.physics3d.setGravity", + "dryad": "caffeine_physics3d_set_gravity", + "signature": "setGravity(x, y, z)", + "params": [ + { + "name": "x", + "type": "number", + "en": "X component.", + "pt": "Componente X." + }, + { + "name": "y", + "type": "number", + "en": "Y component.", + "pt": "Componente Y." + }, + { + "name": "z", + "type": "number", + "en": "Z component.", + "pt": "Componente Z." + } + ], + "returns": null, + "en": "Sets the gravity vector in metres per second squared (default 0, -9.81, 0).", + "pt": "Define o vetor de gravidade em metros por segundo ao quadrado (por omissão 0, -9.81, 0).", + "example": "caffeine.physics3d.setGravity(0, -3.7, 0) -- Mars" + }, + { + "name": "raycast", + "lua": "caffeine.physics3d.raycast", + "dryad": "caffeine_physics3d_raycast", + "signature": "raycast(ox, oy, oz, dx, dy, dz, maxDistance) -> table | nil", + "params": [ + { + "name": "ox, oy, oz", + "type": "number", + "en": "Ray origin in world space.", + "pt": "Origem do raio no espaço do mundo." + }, + { + "name": "dx, dy, dz", + "type": "number", + "en": "Direction; it does not need to be normalised.", + "pt": "Direção; não precisa de estar normalizada." + }, + { + "name": "maxDistance", + "type": "number", + "en": "Maximum length in metres.", + "pt": "Comprimento máximo em metros." + } + ], + "returns": { + "type": "table | nil", + "en": "{ entity, x, y, z, nx, ny, nz, distance } for the nearest body hit, or nil. Triggers are ignored.", + "pt": "{ entity, x, y, z, nx, ny, nz, distance } para o corpo mais próximo atingido, ou nil. Os triggers são ignorados." + }, + "en": "Casts a ray and returns the first solid body it hits, with the hit point and surface normal.", + "pt": "Lança um raio e devolve o primeiro corpo sólido que atinge, com o ponto de impacto e a normal da superfície.", + "example": "local hit = caffeine.physics3d.raycast(0, 10, 0, 0, -1, 0, 100)\nif hit then caffeine.debug.log(hit.entity .. \" at \" .. hit.distance) end" + }, + { + "name": "addForce", + "lua": "caffeine.physics3d.addForce", + "dryad": "caffeine_physics3d_add_force", + "signature": "addForce(entity, x, y, z) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "A body with a RigidBody3D and Collider3D.", + "pt": "Um corpo com RigidBody3D e Collider3D." + }, + { + "name": "x", + "type": "number", + "en": "X component.", + "pt": "Componente X." + }, + { + "name": "y", + "type": "number", + "en": "Y component.", + "pt": "Componente Y." + }, + { + "name": "z", + "type": "number", + "en": "Z component.", + "pt": "Componente Z." + } + ], + "returns": { + "type": "boolean", + "en": "false for an unknown or non-dynamic body.", + "pt": "false para um corpo desconhecido ou não dinâmico." + }, + "en": "Applies a force (newtons) at the centre of mass for the next physics step.", + "pt": "Aplica uma força (newtons) no centro de massa no próximo passo de física.", + "example": "caffeine.physics3d.addForce(eid, 0, 50, 0)" + }, + { + "name": "addImpulse", + "lua": "caffeine.physics3d.addImpulse", + "dryad": "caffeine_physics3d_add_impulse", + "signature": "addImpulse(entity, x, y, z) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "A body with a RigidBody3D and Collider3D.", + "pt": "Um corpo com RigidBody3D e Collider3D." + }, + { + "name": "x", + "type": "number", + "en": "X component.", + "pt": "Componente X." + }, + { + "name": "y", + "type": "number", + "en": "Y component.", + "pt": "Componente Y." + }, + { + "name": "z", + "type": "number", + "en": "Z component.", + "pt": "Componente Z." + } + ], + "returns": { + "type": "boolean", + "en": "false for an unknown or non-dynamic body.", + "pt": "false para um corpo desconhecido ou não dinâmico." + }, + "en": "Applies an instant change of momentum (newton-seconds) at the centre of mass, e.g. a jump.", + "pt": "Aplica uma mudança instantânea de momento (newton-segundos) no centro de massa, por exemplo um salto.", + "example": "caffeine.physics3d.addImpulse(eid, 0, 6, 0)" + }, + { + "name": "setVelocity", + "lua": "caffeine.physics3d.setVelocity", + "dryad": "caffeine_physics3d_set_velocity", + "signature": "setVelocity(entity, x, y, z) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "A body with a RigidBody3D and Collider3D.", + "pt": "Um corpo com RigidBody3D e Collider3D." + }, + { + "name": "x", + "type": "number", + "en": "X component.", + "pt": "Componente X." + }, + { + "name": "y", + "type": "number", + "en": "Y component.", + "pt": "Componente Y." + }, + { + "name": "z", + "type": "number", + "en": "Z component.", + "pt": "Componente Z." + } + ], + "returns": { + "type": "boolean", + "en": "false for an unknown or non-dynamic body.", + "pt": "false para um corpo desconhecido ou não dinâmico." + }, + "en": "Sets the linear velocity in metres per second.", + "pt": "Define a velocidade linear em metros por segundo.", + "example": "caffeine.physics3d.setVelocity(eid, 4, 0, 0)" + }, + { + "name": "velocity", + "lua": "caffeine.physics3d.velocity", + "dryad": "caffeine_physics3d_velocity", + "signature": "velocity(entity) -> table | nil", + "params": [ + { + "name": "entity", + "type": "number", + "en": "A body with a RigidBody3D and Collider3D.", + "pt": "Um corpo com RigidBody3D e Collider3D." + } + ], + "returns": { + "type": "table | nil", + "en": "{ x, y, z } in metres per second, or nil for an unknown or non-dynamic body.", + "pt": "{ x, y, z } em metros por segundo, ou nil para um corpo desconhecido ou não dinâmico." + }, + "en": "Reads the linear velocity of a body.", + "pt": "Lê a velocidade linear de um corpo.", + "example": "local v = caffeine.physics3d.velocity(eid)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/pick.json b/src/caffeine/script/api/pick.json new file mode 100644 index 00000000..0afbfcea --- /dev/null +++ b/src/caffeine/script/api/pick.json @@ -0,0 +1,211 @@ +{ + "namespace": "pick", + "group": "Input", + "lua": "caffeine.pick", + "dryad_prefix": null, + "title": { + "en": "Pick", + "pt": "Seleção" + }, + "summary": { + "en": "Find the entity under a point, a screen position, the mouse or a 3D ray, and register custom pickers.", + "pt": "Encontrar a entidade sob um ponto, uma posição do ecrã, o rato ou um raio 3D, e registar seletores personalizados." + }, + "functions": [ + { + "name": "world", + "lua": "caffeine.pick.world", + "dryad": null, + "signature": "world(wx, wy) -> integer", + "params": [ + { + "name": "wx", + "type": "number", + "en": "World x.", + "pt": "x do mundo." + }, + { + "name": "wy", + "type": "number", + "en": "World y.", + "pt": "y do mundo." + } + ], + "returns": { + "type": "integer", + "en": "Entity id, or 0 when nothing is hit.", + "pt": "Id da entidade, ou 0 se nada for atingido." + }, + "en": "Picks the entity under a 2D world position.", + "pt": "Escolhe a entidade sob uma posição 2D do mundo.", + "example": "local e = caffeine.pick.world(3, 4)" + }, + { + "name": "screen", + "lua": "caffeine.pick.screen", + "dryad": null, + "signature": "screen(sx, sy) -> integer", + "params": [ + { + "name": "sx", + "type": "number", + "en": "Screen x.", + "pt": "x do ecrã." + }, + { + "name": "sy", + "type": "number", + "en": "Screen y.", + "pt": "y do ecrã." + } + ], + "returns": { + "type": "integer", + "en": "Entity id, or 0 when nothing is hit.", + "pt": "Id da entidade, ou 0 se nada for atingido." + }, + "en": "Converts a screen position to the world using the play-mode camera and picks the entity there.", + "pt": "Converte uma posição do ecrã para o mundo usando a câmara do modo de jogo e escolhe a entidade aí.", + "example": "local e = caffeine.pick.screen(400, 300)" + }, + { + "name": "atMouse", + "lua": "caffeine.pick.atMouse", + "dryad": null, + "signature": "atMouse() -> integer", + "params": [], + "returns": { + "type": "integer", + "en": "Entity id, or 0 when nothing is hit.", + "pt": "Id da entidade, ou 0 se nada for atingido." + }, + "en": "Picks the entity under the mouse cursor; 0 without a world or input.", + "pt": "Escolhe a entidade sob o cursor do rato; 0 sem mundo ou entrada.", + "example": "local e = caffeine.pick.atMouse()" + }, + { + "name": "screenToWorld", + "lua": "caffeine.pick.screenToWorld", + "dryad": null, + "signature": "screenToWorld(sx, sy) -> table", + "params": [ + { + "name": "sx", + "type": "number", + "en": "Screen x.", + "pt": "x do ecrã." + }, + { + "name": "sy", + "type": "number", + "en": "Screen y.", + "pt": "y do ecrã." + } + ], + "returns": { + "type": "table", + "en": "{x, y} in world units.", + "pt": "{x, y} em unidades do mundo." + }, + "en": "Converts a screen position to a 2D world position.", + "pt": "Converte uma posição do ecrã numa posição 2D do mundo.", + "example": "local w = caffeine.pick.screenToWorld(400, 300)" + }, + { + "name": "register", + "lua": "caffeine.pick.register", + "dryad": null, + "signature": "register(fn) -> integer", + "params": [ + { + "name": "fn", + "type": "function", + "en": "Called as fn(worldX, worldY); return an entity id (above 0) for a hit, or false/nil for none.", + "pt": "Chamada como fn(worldX, worldY); devolva um id de entidade (maior que 0) para um acerto, ou false/nil para nenhum." + } + ], + "returns": { + "type": "integer", + "en": "Handle for unregister.", + "pt": "Handle para unregister." + }, + "en": "Registers a custom picker consulted by pick queries.", + "pt": "Regista um seletor personalizado consultado pelas pesquisas de seleção.", + "example": "local h = caffeine.pick.register(function(x, y) return 0 end)" + }, + { + "name": "unregister", + "lua": "caffeine.pick.unregister", + "dryad": null, + "signature": "unregister(handle)", + "params": [ + { + "name": "handle", + "type": "integer", + "en": "Handle from register.", + "pt": "Handle devolvido por register." + } + ], + "returns": null, + "en": "Removes a custom picker.", + "pt": "Remove um seletor personalizado.", + "example": "caffeine.pick.unregister(h)" + }, + { + "name": "query", + "lua": "caffeine.pick.query", + "dryad": null, + "signature": "query(wx, wy) -> table", + "params": [ + { + "name": "wx", + "type": "number", + "en": "World x.", + "pt": "x do mundo." + }, + { + "name": "wy", + "type": "number", + "en": "World y.", + "pt": "y do mundo." + } + ], + "returns": { + "type": "table", + "en": "{kind = \"entity\", entityId}, {kind = \"custom\", customId} or {kind = \"none\"}; empty without a world.", + "pt": "{kind = \"entity\", entityId}, {kind = \"custom\", customId} ou {kind = \"none\"}; vazia sem mundo." + }, + "en": "Full pick query at a world position, including custom pickers.", + "pt": "Pesquisa de seleção completa numa posição do mundo, incluindo seletores personalizados.", + "example": "local hit = caffeine.pick.query(3, 4)\nif hit.kind == 'entity' then caffeine.debug.log(hit.entityId) end" + }, + { + "name": "raycast", + "lua": "caffeine.pick.raycast", + "dryad": null, + "signature": "raycast(origin, dir) -> integer", + "params": [ + { + "name": "origin", + "type": "table", + "en": "{x, y, z}; missing parts are 0.", + "pt": "{x, y, z}; partes em falta são 0." + }, + { + "name": "dir", + "type": "table", + "en": "{x, y, z} direction; normalised for you (default z = 1).", + "pt": "Direção {x, y, z}; é normalizada por si (z = 1 por omissão)." + } + ], + "returns": { + "type": "integer", + "en": "Entity id, or 0 when nothing is hit.", + "pt": "Id da entidade, ou 0 se nada for atingido." + }, + "en": "Casts a 3D ray and returns the entity hit.", + "pt": "Lança um raio 3D e devolve a entidade atingida.", + "example": "local e = caffeine.pick.raycast({x=0,y=1,z=0}, {x=0,y=0,z=1})" + } + ] +} diff --git a/src/caffeine/script/api/postprocess.json b/src/caffeine/script/api/postprocess.json new file mode 100644 index 00000000..53427ee3 --- /dev/null +++ b/src/caffeine/script/api/postprocess.json @@ -0,0 +1,799 @@ +{ + "namespace": "postprocess", + "group": "Rendering", + "lua": "caffeine.postprocess", + "dryad_prefix": null, + "title": { + "en": "Post-process", + "pt": "Pós-processamento" + }, + "summary": { + "en": "Per-entity post-process effects such as bloom, vignette, colour grading and fog, with presets and path-based field access.", + "pt": "Efeitos de pós-processamento por entidade, como bloom, vinheta, correção de cor e nevoeiro, com presets e acesso a campos por caminho." + }, + "functions": [ + { + "name": "has", + "lua": "caffeine.postprocess.has", + "dryad": null, + "signature": "has(entity) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "boolean", + "en": "true if the entity has a post-process component.", + "pt": "true se a entidade tiver um componente de pós-processamento." + }, + "en": "Checks whether the entity has a post-process component.", + "pt": "Verifica se a entidade tem um componente de pós-processamento.", + "example": "if caffeine.postprocess.has(cam) then print('ok') end" + }, + { + "name": "add", + "lua": "caffeine.postprocess.add", + "dryad": null, + "signature": "add(entity) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "boolean", + "en": "false if the entity is not alive.", + "pt": "false se a entidade não estiver viva." + }, + "en": "Adds a post-process component to the entity if it does not have one.", + "pt": "Adiciona um componente de pós-processamento à entidade, se ainda não tiver.", + "example": "caffeine.postprocess.add(cam)" + }, + { + "name": "remove", + "lua": "caffeine.postprocess.remove", + "dryad": null, + "signature": "remove(entity)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": null, + "en": "Removes the post-process component from the entity, if present.", + "pt": "Remove o componente de pós-processamento da entidade, se existir.", + "example": "caffeine.postprocess.remove(cam)" + }, + { + "name": "get", + "lua": "caffeine.postprocess.get", + "dryad": null, + "signature": "get(entity) -> table", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "table", + "en": "A table of effect groups (for example `bloom`, `vignette`) with their fields, plus `enabled`, `customEffectScript` and the flat aliases `exposure`, `vignetteIntensity`, `bloomIntensity`. Empty if the entity has no component.", + "pt": "Uma tabela com grupos de efeitos (por exemplo `bloom`, `vignette`) e os seus campos, mais `enabled`, `customEffectScript` e os aliases `exposure`, `vignetteIntensity`, `bloomIntensity`. Vazia se a entidade não tiver o componente." + }, + "en": "Returns a snapshot of the whole post-process state as a table.", + "pt": "Devolve uma tabela com o estado completo de pós-processamento.", + "example": "local s = caffeine.postprocess.get(cam)\nprint(s.bloom.intensity)" + }, + { + "name": "set", + "lua": "caffeine.postprocess.set", + "dryad": null, + "signature": "set(entity, values) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "values", + "type": "table", + "en": "Table shaped like the result of `get`; only the keys present are applied.", + "pt": "Tabela com o formato do resultado de `get`; só as chaves presentes são aplicadas." + } + ], + "returns": { + "type": "boolean", + "en": "false if the entity has no component.", + "pt": "false se a entidade não tiver o componente." + }, + "en": "Merges a table of values into the post-process state.", + "pt": "Aplica uma tabela de valores ao estado de pós-processamento.", + "example": "caffeine.postprocess.set(cam, { bloom = { intensity = 0.8 } })" + }, + { + "name": "getValue", + "lua": "caffeine.postprocess.getValue", + "dryad": null, + "signature": "getValue(entity, path) -> number|boolean|nil", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "path", + "type": "string", + "en": "Field path such as \"bloom.intensity\".", + "pt": "Caminho do campo, por exemplo \"bloom.intensity\"." + } + ], + "returns": { + "type": "number|boolean|nil", + "en": "The field value, or nil if the entity or field is unknown.", + "pt": "O valor do campo, ou nil se a entidade ou o campo não existirem." + }, + "en": "Reads one field by path.", + "pt": "Lê um campo pelo seu caminho.", + "example": "print(caffeine.postprocess.getValue(cam, 'bloom.intensity'))" + }, + { + "name": "setValue", + "lua": "caffeine.postprocess.setValue", + "dryad": null, + "signature": "setValue(entity, path, value) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "path", + "type": "string", + "en": "Field path such as \"bloom.intensity\".", + "pt": "Caminho do campo, por exemplo \"bloom.intensity\"." + }, + { + "name": "value", + "type": "number|boolean", + "en": "New value.", + "pt": "Novo valor." + } + ], + "returns": { + "type": "boolean", + "en": "true if the field was set.", + "pt": "true se o campo foi alterado." + }, + "en": "Writes one field by path.", + "pt": "Escreve um campo pelo seu caminho.", + "example": "caffeine.postprocess.setValue(cam, 'bloom.threshold', 1.0)" + }, + { + "name": "effects", + "lua": "caffeine.postprocess.effects", + "dryad": null, + "signature": "effects() -> table", + "params": [], + "returns": { + "type": "table", + "en": "List of effect names.", + "pt": "Lista de nomes de efeitos." + }, + "en": "Lists the names of the available post-process effects.", + "pt": "Lista os nomes dos efeitos de pós-processamento disponíveis.", + "example": "for _, name in ipairs(caffeine.postprocess.effects()) do print(name) end" + }, + { + "name": "fields", + "lua": "caffeine.postprocess.fields", + "dryad": null, + "signature": "fields(effect) -> table", + "params": [ + { + "name": "effect", + "type": "string", + "en": "Effect name such as \"bloom\".", + "pt": "Nome do efeito, por exemplo \"bloom\"." + } + ], + "returns": { + "type": "table", + "en": "List of tables with `name`, `min`, `max` and `type` (\"bool\", \"int\" or \"number\").", + "pt": "Lista de tabelas com `name`, `min`, `max` e `type` (\"bool\", \"int\" ou \"number\")." + }, + "en": "Lists the fields of one effect with their ranges and types.", + "pt": "Lista os campos de um efeito com os respetivos intervalos e tipos.", + "example": "for _, f in ipairs(caffeine.postprocess.fields('bloom')) do print(f.name, f.min, f.max) end" + }, + { + "name": "setEnabled", + "lua": "caffeine.postprocess.setEnabled", + "dryad": null, + "signature": "setEnabled(entity, enabled)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "enabled", + "type": "boolean", + "en": "Master switch.", + "pt": "Interruptor geral." + } + ], + "returns": null, + "en": "Turns the whole post-process component on or off.", + "pt": "Liga ou desliga todo o componente de pós-processamento.", + "example": "caffeine.postprocess.setEnabled(cam, false)" + }, + { + "name": "enableEffect", + "lua": "caffeine.postprocess.enableEffect", + "dryad": null, + "signature": "enableEffect(entity, effect, enabled) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "effect", + "type": "string", + "en": "Effect name such as \"bloom\".", + "pt": "Nome do efeito, por exemplo \"bloom\"." + }, + { + "name": "enabled", + "type": "boolean", + "en": "Whether the effect is on.", + "pt": "Se o efeito fica ligado." + } + ], + "returns": { + "type": "boolean", + "en": "true if the effect exists.", + "pt": "true se o efeito existir." + }, + "en": "Turns a single effect on or off.", + "pt": "Liga ou desliga um único efeito.", + "example": "caffeine.postprocess.enableEffect(cam, 'bloom', true)" + }, + { + "name": "isEffectEnabled", + "lua": "caffeine.postprocess.isEffectEnabled", + "dryad": null, + "signature": "isEffectEnabled(entity, effect) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "effect", + "type": "string", + "en": "Effect name such as \"bloom\".", + "pt": "Nome do efeito, por exemplo \"bloom\"." + } + ], + "returns": { + "type": "boolean", + "en": "true if the effect is on; false if off or unknown.", + "pt": "true se o efeito estiver ligado; false se estiver desligado ou for desconhecido." + }, + "en": "Checks whether an effect is enabled.", + "pt": "Verifica se um efeito está ligado.", + "example": "print(caffeine.postprocess.isEffectEnabled(cam, 'bloom'))" + }, + { + "name": "applyPreset", + "lua": "caffeine.postprocess.applyPreset", + "dryad": null, + "signature": "applyPreset(entity, name) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "name", + "type": "string", + "en": "One of \"cinematic\", \"horror\", \"arcade\", \"reset\" (or \"default\").", + "pt": "Um de \"cinematic\", \"horror\", \"arcade\", \"reset\" (ou \"default\")." + } + ], + "returns": { + "type": "boolean", + "en": "false for an unknown preset or missing component.", + "pt": "false para um preset desconhecido ou componente em falta." + }, + "en": "Applies a built-in post-process preset.", + "pt": "Aplica um preset de pós-processamento incluído.", + "example": "caffeine.postprocess.applyPreset(cam, 'cinematic')" + }, + { + "name": "blend", + "lua": "caffeine.postprocess.blend", + "dryad": null, + "signature": "blend(entity, from, to, t) -> boolean", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "from", + "type": "table", + "en": "Table of values for the start state.", + "pt": "Tabela de valores para o estado inicial." + }, + { + "name": "to", + "type": "table", + "en": "Table of values for the end state.", + "pt": "Tabela de valores para o estado final." + }, + { + "name": "t", + "type": "number", + "en": "Blend factor, clamped to 0..1.", + "pt": "Fator de mistura, limitado a 0..1." + } + ], + "returns": { + "type": "boolean", + "en": "false if the entity has no component.", + "pt": "false se a entidade não tiver o componente." + }, + "en": "Interpolates between two tables of values (each applied on top of the current state) and stores the result.", + "pt": "Interpola entre duas tabelas de valores (cada uma aplicada sobre o estado atual) e guarda o resultado.", + "example": "caffeine.postprocess.blend(cam, { bloom = { intensity = 0 } }, { bloom = { intensity = 1 } }, 0.5)" + }, + { + "name": "setExposure", + "lua": "caffeine.postprocess.setExposure", + "dryad": null, + "signature": "setExposure(entity, exposure)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "exposure", + "type": "number", + "en": "Exposure value.", + "pt": "Valor de exposição." + } + ], + "returns": null, + "en": "Sets colour-grading exposure and enables colour grading.", + "pt": "Define a exposição da correção de cor e ativa-a.", + "example": "caffeine.postprocess.setExposure(cam, 1.2)" + }, + { + "name": "setColorGrading", + "lua": "caffeine.postprocess.setColorGrading", + "dryad": null, + "signature": "setColorGrading(entity, contrast, saturation, temperature, tint)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "contrast", + "type": "number", + "en": "Contrast.", + "pt": "Contraste." + }, + { + "name": "saturation", + "type": "number", + "en": "Saturation.", + "pt": "Saturação." + }, + { + "name": "temperature", + "type": "number", + "en": "Colour temperature. Optional.", + "pt": "Temperatura de cor. Opcional." + }, + { + "name": "tint", + "type": "number", + "en": "Tint. Optional.", + "pt": "Matiz. Opcional." + } + ], + "returns": null, + "en": "Sets colour-grading values and enables colour grading.", + "pt": "Define valores de correção de cor e ativa-a.", + "example": "caffeine.postprocess.setColorGrading(cam, 1.1, 0.9)" + }, + { + "name": "setBloom", + "lua": "caffeine.postprocess.setBloom", + "dryad": null, + "signature": "setBloom(entity, intensity, threshold)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "intensity", + "type": "number", + "en": "Bloom intensity; the effect is enabled when above 0.001.", + "pt": "Intensidade do bloom; o efeito fica ativo acima de 0.001." + }, + { + "name": "threshold", + "type": "number", + "en": "Brightness threshold. Optional.", + "pt": "Limiar de brilho. Opcional." + } + ], + "returns": null, + "en": "Sets bloom intensity and optionally the threshold.", + "pt": "Define a intensidade do bloom e, opcionalmente, o limiar.", + "example": "caffeine.postprocess.setBloom(cam, 0.6, 1.0)" + }, + { + "name": "setVignette", + "lua": "caffeine.postprocess.setVignette", + "dryad": null, + "signature": "setVignette(entity, intensity)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "intensity", + "type": "number", + "en": "Intensity; enabled when above 0.001.", + "pt": "Intensidade; ativo acima de 0.001." + } + ], + "returns": null, + "en": "Sets vignette intensity.", + "pt": "Define a intensidade da vinheta.", + "example": "caffeine.postprocess.setVignette(cam, 0.4)" + }, + { + "name": "setChromaticAberration", + "lua": "caffeine.postprocess.setChromaticAberration", + "dryad": null, + "signature": "setChromaticAberration(entity, intensity)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "intensity", + "type": "number", + "en": "Intensity; enabled when above 0.001.", + "pt": "Intensidade; ativo acima de 0.001." + } + ], + "returns": null, + "en": "Sets chromatic aberration intensity.", + "pt": "Define a intensidade da aberração cromática.", + "example": "caffeine.postprocess.setChromaticAberration(cam, 0.2)" + }, + { + "name": "setGrain", + "lua": "caffeine.postprocess.setGrain", + "dryad": null, + "signature": "setGrain(entity, intensity)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "intensity", + "type": "number", + "en": "Intensity; enabled when above 0.001.", + "pt": "Intensidade; ativo acima de 0.001." + } + ], + "returns": null, + "en": "Sets film grain intensity.", + "pt": "Define a intensidade do grão de película.", + "example": "caffeine.postprocess.setGrain(cam, 0.1)" + }, + { + "name": "setLensDistortion", + "lua": "caffeine.postprocess.setLensDistortion", + "dryad": null, + "signature": "setLensDistortion(entity, intensity)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "intensity", + "type": "number", + "en": "Intensity; enabled when its absolute value is above 0.001.", + "pt": "Intensidade; ativo quando o valor absoluto é superior a 0.001." + } + ], + "returns": null, + "en": "Sets lens distortion intensity.", + "pt": "Define a intensidade da distorção de lente.", + "example": "caffeine.postprocess.setLensDistortion(cam, -0.1)" + }, + { + "name": "setMotionBlur", + "lua": "caffeine.postprocess.setMotionBlur", + "dryad": null, + "signature": "setMotionBlur(entity, intensity)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "intensity", + "type": "number", + "en": "Intensity; enabled when above 0.001.", + "pt": "Intensidade; ativo acima de 0.001." + } + ], + "returns": null, + "en": "Sets motion blur intensity.", + "pt": "Define a intensidade do desfoque de movimento.", + "example": "caffeine.postprocess.setMotionBlur(cam, 0.5)" + }, + { + "name": "setDepthOfField", + "lua": "caffeine.postprocess.setDepthOfField", + "dryad": null, + "signature": "setDepthOfField(entity, focusDistance, aperture)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "focusDistance", + "type": "number", + "en": "Focus distance.", + "pt": "Distância de foco." + }, + { + "name": "aperture", + "type": "number", + "en": "Aperture.", + "pt": "Abertura." + } + ], + "returns": null, + "en": "Sets depth-of-field focus and aperture and enables the effect.", + "pt": "Define o foco e a abertura da profundidade de campo e ativa o efeito.", + "example": "caffeine.postprocess.setDepthOfField(cam, 10, 2.8)" + }, + { + "name": "setFog", + "lua": "caffeine.postprocess.setFog", + "dryad": null, + "signature": "setFog(entity, density, r, g, b)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "density", + "type": "number", + "en": "Fog density; enabled when above 0.001.", + "pt": "Densidade do nevoeiro; ativo acima de 0.001." + }, + { + "name": "r", + "type": "number", + "en": "Red; the colour is applied only if r, g and b are all given. Optional.", + "pt": "Vermelho; a cor só é aplicada se r, g e b forem todos indicados. Opcional." + }, + { + "name": "g", + "type": "number", + "en": "Green. Optional.", + "pt": "Verde. Opcional." + }, + { + "name": "b", + "type": "number", + "en": "Blue. Optional.", + "pt": "Azul. Opcional." + } + ], + "returns": null, + "en": "Sets the deferred fog density and optionally its colour.", + "pt": "Define a densidade do nevoeiro diferido e, opcionalmente, a cor.", + "example": "caffeine.postprocess.setFog(cam, 0.02, 0.6, 0.7, 0.8)" + }, + { + "name": "setAmbientOcclusion", + "lua": "caffeine.postprocess.setAmbientOcclusion", + "dryad": null, + "signature": "setAmbientOcclusion(entity, intensity, radius)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "intensity", + "type": "number", + "en": "Intensity; enabled when above 0.001.", + "pt": "Intensidade; ativo acima de 0.001." + }, + { + "name": "radius", + "type": "number", + "en": "Sampling radius. Optional.", + "pt": "Raio de amostragem. Opcional." + } + ], + "returns": null, + "en": "Sets ambient occlusion intensity and optionally the radius.", + "pt": "Define a intensidade da oclusão ambiente e, opcionalmente, o raio.", + "example": "caffeine.postprocess.setAmbientOcclusion(cam, 1.0, 0.5)" + }, + { + "name": "setAntiAliasing", + "lua": "caffeine.postprocess.setAntiAliasing", + "dryad": null, + "signature": "setAntiAliasing(entity, mode)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "mode", + "type": "string", + "en": "\"fxaa\", \"off\" or \"none\"; any other value selects the non-FXAA mode.", + "pt": "\"fxaa\", \"off\" ou \"none\"; qualquer outro valor seleciona o modo que não é FXAA." + } + ], + "returns": null, + "en": "Selects the anti-aliasing mode; \"off\" and \"none\" disable it.", + "pt": "Seleciona o modo de anti-aliasing; \"off\" e \"none\" desativam-no.", + "example": "caffeine.postprocess.setAntiAliasing(cam, 'fxaa')" + }, + { + "name": "setAutoExposure", + "lua": "caffeine.postprocess.setAutoExposure", + "dryad": null, + "signature": "setAutoExposure(entity, enabled, compensation)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "enabled", + "type": "boolean", + "en": "Turns auto exposure on or off.", + "pt": "Liga ou desliga a exposição automática." + }, + { + "name": "compensation", + "type": "number", + "en": "Exposure compensation. Optional.", + "pt": "Compensação de exposição. Opcional." + } + ], + "returns": null, + "en": "Toggles auto exposure and optionally sets its compensation.", + "pt": "Liga ou desliga a exposição automática e, opcionalmente, define a compensação.", + "example": "caffeine.postprocess.setAutoExposure(cam, true, 0.5)" + }, + { + "name": "setCustomScript", + "lua": "caffeine.postprocess.setCustomScript", + "dryad": null, + "signature": "setCustomScript(entity, path)", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "path", + "type": "string", + "en": "Path of the custom effect script.", + "pt": "Caminho do script de efeito personalizado." + } + ], + "returns": null, + "en": "Sets the custom effect script of the entity.", + "pt": "Define o script de efeito personalizado da entidade.", + "example": "caffeine.postprocess.setCustomScript(cam, 'scripts/fx.lua')" + }, + { + "name": "handle", + "lua": "caffeine.postprocess.handle", + "dryad": null, + "signature": "handle(entity) -> table", + "params": [ + { + "name": "entity", + "type": "number", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "table", + "en": "Table with `entity`, `get`, `set`, `enable`, `isEnabled`, `snapshot`, `apply` and `preset`, all bound to the entity.", + "pt": "Tabela com `entity`, `get`, `set`, `enable`, `isEnabled`, `snapshot`, `apply` e `preset`, todas ligadas à entidade." + }, + "en": "Returns a per-entity handle, the same kind passed to `onPostProcess`, so calls need no entity id.", + "pt": "Devolve um handle por entidade, do mesmo tipo passado a `onPostProcess`, para que as chamadas não precisem do id.", + "example": "local h = caffeine.postprocess.handle(cam)\nh.set('bloom.intensity', 0.5)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/procedural.json b/src/caffeine/script/api/procedural.json new file mode 100644 index 00000000..69cf1676 --- /dev/null +++ b/src/caffeine/script/api/procedural.json @@ -0,0 +1,467 @@ +{ + "namespace": "procedural", + "group": "World", + "lua": "caffeine.procedural", + "dryad_prefix": null, + "title": { + "en": "Procedural", + "pt": "Procedural" + }, + "summary": { + "en": "Deterministic noise, chunk streaming and terrain generation helpers for procedural worlds.", + "pt": "Auxiliares de ruído determinístico, streaming de chunks e geração de terreno para mundos procedurais." + }, + "functions": [ + { + "name": "hash", + "lua": "caffeine.procedural.hash", + "dryad": null, + "signature": "hash(x, z, seed, salt) -> number", + "params": [ + { + "name": "x", + "type": "number", + "en": "Integer X.", + "pt": "X inteiro." + }, + { + "name": "z", + "type": "number", + "en": "Integer Z.", + "pt": "Z inteiro." + }, + { + "name": "seed", + "type": "number", + "en": "Seed.", + "pt": "Semente." + }, + { + "name": "salt", + "type": "number", + "en": "Extra salt.", + "pt": "Sal adicional." + } + ], + "returns": { + "type": "number", + "en": "Hash value (named hash01 in the engine).", + "pt": "Valor de hash (chamado hash01 no motor)." + }, + "en": "Deterministic hash of a cell, seed and salt.", + "pt": "Hash determinístico de uma célula, semente e sal.", + "example": "local r = caffeine.procedural.hash(3, 4, 42, 0)" + }, + { + "name": "noise2d", + "lua": "caffeine.procedural.noise2d", + "dryad": null, + "signature": "noise2d(x, z, seed) -> number", + "params": [ + { + "name": "x", + "type": "number", + "en": "X coordinate.", + "pt": "Coordenada X." + }, + { + "name": "z", + "type": "number", + "en": "Z coordinate.", + "pt": "Coordenada Z." + }, + { + "name": "seed", + "type": "number", + "en": "Seed.", + "pt": "Semente." + } + ], + "returns": { + "type": "number", + "en": "Noise value.", + "pt": "Valor de ruído." + }, + "en": "2D value noise.", + "pt": "Ruído de valor 2D.", + "example": "local n = caffeine.procedural.noise2d(1.5, 2.5, 42)" + }, + { + "name": "fbm2d", + "lua": "caffeine.procedural.fbm2d", + "dryad": null, + "signature": "fbm2d(x, z, seed, octaves, lacunarity, persistence) -> number", + "params": [ + { + "name": "x", + "type": "number", + "en": "X coordinate.", + "pt": "Coordenada X." + }, + { + "name": "z", + "type": "number", + "en": "Z coordinate.", + "pt": "Coordenada Z." + }, + { + "name": "seed", + "type": "number", + "en": "Seed.", + "pt": "Semente." + }, + { + "name": "octaves", + "type": "number", + "en": "Octave count.", + "pt": "Número de oitavas." + }, + { + "name": "lacunarity", + "type": "number", + "en": "Frequency multiplier per octave.", + "pt": "Multiplicador de frequência por oitava." + }, + { + "name": "persistence", + "type": "number", + "en": "Amplitude multiplier per octave.", + "pt": "Multiplicador de amplitude por oitava." + } + ], + "returns": { + "type": "number", + "en": "Noise value.", + "pt": "Valor de ruído." + }, + "en": "2D fractal Brownian motion noise.", + "pt": "Ruído fractal Brownian motion 2D.", + "example": "local h = caffeine.procedural.fbm2d(x * 0.02, z * 0.02, 42, 5, 2.0, 0.5)" + }, + { + "name": "worldToChunk", + "lua": "caffeine.procedural.worldToChunk", + "dryad": null, + "signature": "worldToChunk(worldCoord, chunkSize) -> number", + "params": [ + { + "name": "worldCoord", + "type": "number", + "en": "World coordinate.", + "pt": "Coordenada do mundo." + }, + { + "name": "chunkSize", + "type": "number", + "en": "Chunk size in world units.", + "pt": "Tamanho do chunk em unidades do mundo." + } + ], + "returns": { + "type": "number", + "en": "Chunk index.", + "pt": "Índice do chunk." + }, + "en": "Converts a world coordinate to a chunk index.", + "pt": "Converte uma coordenada do mundo num índice de chunk.", + "example": "local cx = caffeine.procedural.worldToChunk(pos.x, 64)" + }, + { + "name": "findTerrain", + "lua": "caffeine.procedural.findTerrain", + "dryad": null, + "signature": "findTerrain() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Terrain entity id, or 0 if none.", + "pt": "Id da entidade de terreno, ou 0 se não houver." + }, + "en": "Finds the terrain entity.", + "pt": "Procura a entidade de terreno.", + "example": "local t = caffeine.procedural.findTerrain()" + }, + { + "name": "getFocusChunk", + "lua": "caffeine.procedural.getFocusChunk", + "dryad": null, + "signature": "getFocusChunk(directorId, chunkSize, focusId) -> table", + "params": [ + { + "name": "directorId", + "type": "number", + "en": "Entity id of the procedural world director.", + "pt": "Id da entidade diretora do mundo procedural." + }, + { + "name": "chunkSize", + "type": "number", + "en": "Chunk size, used if the director has no procedural settings.", + "pt": "Tamanho do chunk, usado se o diretor não tiver definições procedurais." + }, + { + "name": "focusId", + "type": "number", + "en": "Focus entity id. Optional.", + "pt": "Id da entidade de foco. Opcional." + } + ], + "returns": { + "type": "table", + "en": "Table with `cx` and `cz` (0, 0 if unavailable).", + "pt": "Tabela com `cx` e `cz` (0, 0 se indisponível)." + }, + "en": "Returns the chunk the focus entity is in.", + "pt": "Devolve o chunk onde está a entidade de foco.", + "example": "local c = caffeine.procedural.getFocusChunk(dir, 64, player)\nprint(c.cx, c.cz)" + }, + { + "name": "isChunkLoaded", + "lua": "caffeine.procedural.isChunkLoaded", + "dryad": null, + "signature": "isChunkLoaded(directorId, cx, cz) -> boolean", + "params": [ + { + "name": "directorId", + "type": "number", + "en": "Entity id of the procedural world director.", + "pt": "Id da entidade diretora do mundo procedural." + }, + { + "name": "cx", + "type": "number", + "en": "Chunk X index.", + "pt": "Índice X do chunk." + }, + { + "name": "cz", + "type": "number", + "en": "Chunk Z index.", + "pt": "Índice Z do chunk." + } + ], + "returns": { + "type": "boolean", + "en": "true if the chunk is loaded.", + "pt": "true se o chunk estiver carregado." + }, + "en": "Checks whether a chunk is loaded for the director.", + "pt": "Verifica se um chunk está carregado para o diretor.", + "example": "print(caffeine.procedural.isChunkLoaded(dir, 0, 0))" + }, + { + "name": "unloadChunk", + "lua": "caffeine.procedural.unloadChunk", + "dryad": null, + "signature": "unloadChunk(directorId, cx, cz)", + "params": [ + { + "name": "directorId", + "type": "number", + "en": "Entity id of the procedural world director.", + "pt": "Id da entidade diretora do mundo procedural." + }, + { + "name": "cx", + "type": "number", + "en": "Chunk X index.", + "pt": "Índice X do chunk." + }, + { + "name": "cz", + "type": "number", + "en": "Chunk Z index.", + "pt": "Índice Z do chunk." + } + ], + "returns": null, + "en": "Unloads a chunk of the director.", + "pt": "Descarrega um chunk do diretor.", + "example": "caffeine.procedural.unloadChunk(dir, 0, 0)" + }, + { + "name": "stream", + "lua": "caffeine.procedural.stream", + "dryad": null, + "signature": "stream(directorId, terrainId, cx, cz, preset)", + "params": [ + { + "name": "directorId", + "type": "number", + "en": "Entity id of the procedural world director.", + "pt": "Id da entidade diretora do mundo procedural." + }, + { + "name": "terrainId", + "type": "number", + "en": "Terrain entity id. Optional.", + "pt": "Id da entidade de terreno. Opcional." + }, + { + "name": "cx", + "type": "number", + "en": "Chunk X index.", + "pt": "Índice X do chunk." + }, + { + "name": "cz", + "type": "number", + "en": "Chunk Z index.", + "pt": "Índice Z do chunk." + }, + { + "name": "preset", + "type": "string", + "en": "Preset name. Optional.", + "pt": "Nome do preset. Opcional." + } + ], + "returns": null, + "en": "Streams chunks around the given chunk, adding procedural settings to the director if needed.", + "pt": "Faz streaming de chunks em redor do chunk indicado, adicionando definições procedurais ao diretor se necessário.", + "example": "caffeine.procedural.stream(dir, caffeine.procedural.findTerrain(), 0, 0)" + }, + { + "name": "generateTerrainChunk", + "lua": "caffeine.procedural.generateTerrainChunk", + "dryad": null, + "signature": "generateTerrainChunk(terrainId, cx, cz, seed, preset)", + "params": [ + { + "name": "terrainId", + "type": "number", + "en": "Terrain entity id.", + "pt": "Id da entidade de terreno." + }, + { + "name": "cx", + "type": "number", + "en": "Chunk X index.", + "pt": "Índice X do chunk." + }, + { + "name": "cz", + "type": "number", + "en": "Chunk Z index.", + "pt": "Índice Z do chunk." + }, + { + "name": "seed", + "type": "number", + "en": "Seed.", + "pt": "Semente." + }, + { + "name": "preset", + "type": "string", + "en": "Preset name. Optional.", + "pt": "Nome do preset. Opcional." + } + ], + "returns": null, + "en": "Generates one terrain chunk.", + "pt": "Gera um chunk de terreno.", + "example": "caffeine.procedural.generateTerrainChunk(terrain, 0, 0, 42)" + }, + { + "name": "spawnCube", + "lua": "caffeine.procedural.spawnCube", + "dryad": null, + "signature": "spawnCube(directorId, cx, cz, x, y, z, sx, sy, sz) -> number", + "params": [ + { + "name": "directorId", + "type": "number", + "en": "Entity id of the procedural world director.", + "pt": "Id da entidade diretora do mundo procedural." + }, + { + "name": "cx", + "type": "number", + "en": "Chunk X index.", + "pt": "Índice X do chunk." + }, + { + "name": "cz", + "type": "number", + "en": "Chunk Z index.", + "pt": "Índice Z do chunk." + }, + { + "name": "x", + "type": "number", + "en": "World X.", + "pt": "X no mundo." + }, + { + "name": "y", + "type": "number", + "en": "World Y.", + "pt": "Y no mundo." + }, + { + "name": "z", + "type": "number", + "en": "World Z.", + "pt": "Z no mundo." + }, + { + "name": "sx", + "type": "number", + "en": "Scale X.", + "pt": "Escala X." + }, + { + "name": "sy", + "type": "number", + "en": "Scale Y.", + "pt": "Escala Y." + }, + { + "name": "sz", + "type": "number", + "en": "Scale Z.", + "pt": "Escala Z." + } + ], + "returns": { + "type": "number", + "en": "Id of the new entity, or 0 if no world.", + "pt": "Id da nova entidade, ou 0 se não houver mundo." + }, + "en": "Spawns a cube entity tagged with the director and chunk.", + "pt": "Cria uma entidade cubo marcada com o diretor e o chunk.", + "example": "local c = caffeine.procedural.spawnCube(dir, 0, 0, 1, 0.5, 1, 1, 1, 1)" + }, + { + "name": "fillTerrainNoise", + "lua": "caffeine.procedural.fillTerrainNoise", + "dryad": null, + "signature": "fillTerrainNoise(terrainId, seed, amplitude)", + "params": [ + { + "name": "terrainId", + "type": "number", + "en": "Terrain entity id.", + "pt": "Id da entidade de terreno." + }, + { + "name": "seed", + "type": "number", + "en": "Seed.", + "pt": "Semente." + }, + { + "name": "amplitude", + "type": "number", + "en": "Height multiplier; results are clamped to 0..1.", + "pt": "Multiplicador de altura; os resultados são limitados a 0..1." + } + ], + "returns": null, + "en": "Fills the terrain heightmap with fractal noise.", + "pt": "Preenche o heightmap do terreno com ruído fractal.", + "example": "caffeine.procedural.fillTerrainNoise(terrain, 42, 1.0)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/random.json b/src/caffeine/script/api/random.json new file mode 100644 index 00000000..4d9f1c20 --- /dev/null +++ b/src/caffeine/script/api/random.json @@ -0,0 +1,127 @@ +{ + "namespace": "random", + "group": "Core", + "lua": "caffeine.random", + "dryad_prefix": "caffeine_random_", + "title": { + "en": "Random", + "pt": "Aleatório" + }, + "summary": { + "en": "A deterministic generator: the same seed always gives the same sequence, on every platform.", + "pt": "Um gerador determinístico: a mesma semente dá sempre a mesma sequência, em todas as plataformas." + }, + "functions": [ + { + "name": "setSeed", + "lua": "caffeine.random.setSeed", + "dryad": "caffeine_random_set_seed", + "signature": "setSeed(seed)", + "params": [ + { + "name": "seed", + "type": "number", + "en": "Any whole number; 0 is replaced by a fixed value.", + "pt": "Qualquer inteiro; 0 é substituído por um valor fixo." + } + ], + "returns": null, + "en": "Restarts the sequence.", + "pt": "Reinicia a sequência.", + "example": "caffeine.random.setSeed(1234)" + }, + { + "name": "value", + "lua": "caffeine.random.value", + "dryad": "caffeine_random_value", + "signature": "value() -> number", + "params": [], + "returns": { + "type": "number", + "en": "A number in [0, 1).", + "pt": "Um número em [0, 1)." + }, + "en": "Next random number.", + "pt": "Próximo número aleatório.", + "example": "local r = caffeine.random.value()" + }, + { + "name": "range", + "lua": "caffeine.random.range", + "dryad": "caffeine_random_range", + "signature": "range(min, max) -> number", + "params": [ + { + "name": "min", + "type": "number", + "en": "Lower bound (inclusive).", + "pt": "Limite inferior (inclusivo)." + }, + { + "name": "max", + "type": "number", + "en": "Upper bound (exclusive).", + "pt": "Limite superior (exclusivo)." + } + ], + "returns": { + "type": "number", + "en": "A number in [min, max).", + "pt": "Um número em [min, max)." + }, + "en": "A random number in a range.", + "pt": "Um número aleatório num intervalo.", + "example": "local x = caffeine.random.range(-5, 5)" + }, + { + "name": "int", + "lua": "caffeine.random.int", + "dryad": "caffeine_random_int", + "signature": "int(min, max) -> number", + "params": [ + { + "name": "min", + "type": "number", + "en": "Lower bound (inclusive).", + "pt": "Limite inferior (inclusivo)." + }, + { + "name": "max", + "type": "number", + "en": "Upper bound (inclusive); reversed bounds are swapped.", + "pt": "Limite superior (inclusivo); limites invertidos são trocados." + } + ], + "returns": { + "type": "number", + "en": "A whole number in [min, max].", + "pt": "Um inteiro em [min, max]." + }, + "en": "A random whole number, both ends included.", + "pt": "Um inteiro aleatório, com os dois extremos incluídos.", + "example": "local roll = caffeine.random.int(1, 6)" + }, + { + "name": "chance", + "lua": "caffeine.random.chance", + "dryad": "caffeine_random_chance", + "signature": "chance(p) -> boolean", + "params": [ + { + "name": "p", + "type": "number", + "en": "Probability from 0 to 1.", + "pt": "Probabilidade de 0 a 1." + } + ], + "returns": { + "type": "boolean", + "en": "true with probability p.", + "pt": "true com probabilidade p." + }, + "en": "A weighted coin flip.", + "pt": "Um cara ou coroa com pesos.", + "example": "if caffeine.random.chance(0.25) then end" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/time.json b/src/caffeine/script/api/time.json new file mode 100644 index 00000000..4b6e6b5f --- /dev/null +++ b/src/caffeine/script/api/time.json @@ -0,0 +1,190 @@ +{ + "namespace": "time", + "group": "Core", + "lua": "caffeine.time", + "dryad_prefix": "caffeine_time_", + "title": { + "en": "Time", + "pt": "Tempo" + }, + "summary": { + "en": "The play clock: scaled and unscaled frame time, the fixed step, pause and the deterministic random seed.", + "pt": "O relógio de jogo: tempo de frame com e sem escala, o passo fixo, pausa e a semente aleatória determinística." + }, + "functions": [ + { + "name": "delta", + "lua": "caffeine.time.delta", + "dryad": "caffeine_time_delta", + "signature": "delta() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Seconds since the previous frame, multiplied by the time scale (0 while paused).", + "pt": "Segundos desde o frame anterior, multiplicados pela escala de tempo (0 em pausa)." + }, + "en": "Frame time to use for movement and timers in `onUpdate`.", + "pt": "Tempo de frame a usar para movimento e temporizadores em `onUpdate`.", + "example": "local speed = 5\nfunction onUpdate(e, dt)\n local t = caffeine.world.getTransform(e)\n caffeine.world.setTransform(e, { x = t.x + speed * caffeine.time.delta(), y = t.y })\nend" + }, + { + "name": "setTimeScale", + "lua": "caffeine.time.setTimeScale", + "dryad": "caffeine_time_set_scale", + "signature": "setTimeScale(scale)", + "params": [ + { + "name": "scale", + "type": "number", + "en": "1 = normal, 0.5 = half speed, 0 = frozen.", + "pt": "1 = normal, 0.5 = metade da velocidade, 0 = parado." + } + ], + "returns": null, + "en": "Changes how fast scaled time advances. Unscaled time and the UI are not affected.", + "pt": "Altera a velocidade do tempo escalado. O tempo sem escala e a UI não são afetados.", + "example": "caffeine.time.setTimeScale(0.25) -- slow motion" + }, + { + "name": "unscaledDelta", + "lua": "caffeine.time.unscaledDelta", + "dryad": "caffeine_time_unscaled_delta", + "signature": "unscaledDelta() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Seconds since the previous frame, ignoring the time scale.", + "pt": "Segundos desde o frame anterior, ignorando a escala de tempo." + }, + "en": "Real frame time, unaffected by the time scale or pause. Use it for UI and effects that must keep running.", + "pt": "Tempo real de frame, não afetado pela escala de tempo nem pela pausa. Use-o para UI e efeitos que devem continuar a correr.", + "example": "local real = caffeine.time.unscaledDelta()" + }, + { + "name": "time", + "lua": "caffeine.time.time", + "dryad": "caffeine_time_total", + "signature": "time() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Scaled play time in seconds.", + "pt": "Tempo de jogo escalado em segundos." + }, + "en": "Total play time accumulated by the play clock.", + "pt": "Tempo de jogo total acumulado pelo relógio de jogo.", + "example": "caffeine.debug.log('t=' .. caffeine.time.time())" + }, + { + "name": "fixedDelta", + "lua": "caffeine.time.fixedDelta", + "dryad": "caffeine_time_fixed_delta", + "signature": "fixedDelta() -> number", + "params": [], + "returns": { + "type": "number", + "en": "The fixed step in seconds (1/60 by default).", + "pt": "O passo fixo em segundos (1/60 por omissão)." + }, + "en": "The fixed simulation step of the play clock.", + "pt": "O passo fixo de simulação do relógio de jogo.", + "example": "local step = caffeine.time.fixedDelta()" + }, + { + "name": "timeScale", + "lua": "caffeine.time.timeScale", + "dryad": "caffeine_time_scale", + "signature": "timeScale() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Current time scale.", + "pt": "Escala de tempo atual." + }, + "en": "Returns the current time scale (1 is normal speed).", + "pt": "Devolve a escala de tempo atual (1 é a velocidade normal).", + "example": "local s = caffeine.time.timeScale()" + }, + { + "name": "paused", + "lua": "caffeine.time.paused", + "dryad": "caffeine_time_paused", + "signature": "paused() -> boolean", + "params": [], + "returns": { + "type": "boolean", + "en": "True while the play clock is paused.", + "pt": "Verdadeiro enquanto o relógio de jogo está em pausa." + }, + "en": "Tells whether the play clock is paused.", + "pt": "Indica se o relógio de jogo está em pausa.", + "example": "if caffeine.time.paused() then return end" + }, + { + "name": "setPaused", + "lua": "caffeine.time.setPaused", + "dryad": "caffeine_time_set_paused", + "signature": "setPaused(paused)", + "params": [ + { + "name": "paused", + "type": "boolean", + "en": "True to pause, false to resume.", + "pt": "Verdadeiro para pausar, falso para retomar." + } + ], + "returns": null, + "en": "Pauses or resumes the play clock; scaled delta is 0 while paused.", + "pt": "Pausa ou retoma o relógio de jogo; o delta escalado é 0 em pausa.", + "example": "caffeine.time.setPaused(true)" + }, + { + "name": "frame", + "lua": "caffeine.time.frame", + "dryad": "caffeine_time_frame", + "signature": "frame() -> number", + "params": [], + "returns": { + "type": "number", + "en": "Frame counter of the play clock.", + "pt": "Contador de frames do relógio de jogo." + }, + "en": "Returns the number of frames advanced by the play clock.", + "pt": "Devolve o número de frames avançados pelo relógio de jogo.", + "example": "local n = caffeine.time.frame()" + }, + { + "name": "seed", + "lua": "caffeine.time.seed", + "dryad": null, + "signature": "seed() -> integer", + "params": [], + "returns": { + "type": "integer", + "en": "Current random seed.", + "pt": "Semente aleatória atual." + }, + "en": "Returns the deterministic random seed of the play clock.", + "pt": "Devolve a semente aleatória determinística do relógio de jogo.", + "example": "local s = caffeine.time.seed()" + }, + { + "name": "setSeed", + "lua": "caffeine.time.setSeed", + "dryad": null, + "signature": "setSeed(seed)", + "params": [ + { + "name": "seed", + "type": "integer", + "en": "New seed.", + "pt": "Nova semente." + } + ], + "returns": null, + "en": "Sets the deterministic random seed of the play clock.", + "pt": "Define a semente aleatória determinística do relógio de jogo.", + "example": "caffeine.time.setSeed(1234)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/ui.json b/src/caffeine/script/api/ui.json new file mode 100644 index 00000000..8f32681f --- /dev/null +++ b/src/caffeine/script/api/ui.json @@ -0,0 +1,200 @@ +{ + "namespace": "ui", + "group": "UI", + "lua": "caffeine.ui", + "dryad_prefix": null, + "title": { + "en": "UI", + "pt": "Interface" + }, + "summary": { + "en": "Create canvases, labels and buttons, update them and hit-test screen positions.", + "pt": "Criar canvases, rótulos e botões, atualizá-los e testar acertos em posições do ecrã." + }, + "functions": [ + { + "name": "createCanvas", + "lua": "caffeine.ui.createCanvas", + "dryad": null, + "signature": "createCanvas([w, h]) -> integer", + "params": [ + { + "name": "w", + "type": "number", + "en": "Width (default 1280).", + "pt": "Largura (por omissão 1280)." + }, + { + "name": "h", + "type": "number", + "en": "Height (default 720).", + "pt": "Altura (por omissão 720)." + } + ], + "returns": { + "type": "integer", + "en": "Canvas entity id, or 0 without a UI system or world.", + "pt": "Id da entidade do canvas, ou 0 sem sistema de UI ou mundo." + }, + "en": "Creates a UI canvas entity.", + "pt": "Cria uma entidade de canvas de UI.", + "example": "local canvas = caffeine.ui.createCanvas(1280, 720)" + }, + { + "name": "createLabel", + "lua": "caffeine.ui.createLabel", + "dryad": null, + "signature": "createLabel(parent, text, pos) -> integer", + "params": [ + { + "name": "parent", + "type": "integer", + "en": "Parent canvas or widget id.", + "pt": "Id do canvas ou widget pai." + }, + { + "name": "text", + "type": "string", + "en": "Label text.", + "pt": "Texto do rótulo." + }, + { + "name": "pos", + "type": "table", + "en": "{x, y} position.", + "pt": "Posição {x, y}." + } + ], + "returns": { + "type": "integer", + "en": "Label entity id, or 0.", + "pt": "Id da entidade do rótulo, ou 0." + }, + "en": "Creates a text label under a parent.", + "pt": "Cria um rótulo de texto sob um pai.", + "example": "local l = caffeine.ui.createLabel(canvas, 'Score: 0', { x = 10, y = 10 })" + }, + { + "name": "createButton", + "lua": "caffeine.ui.createButton", + "dryad": null, + "signature": "createButton(parent, text, pos[, w, h]) -> integer", + "params": [ + { + "name": "parent", + "type": "integer", + "en": "Parent canvas or widget id.", + "pt": "Id do canvas ou widget pai." + }, + { + "name": "text", + "type": "string", + "en": "Button text.", + "pt": "Texto do botão." + }, + { + "name": "pos", + "type": "table", + "en": "{x, y} position.", + "pt": "Posição {x, y}." + }, + { + "name": "w", + "type": "number", + "en": "Width (default 120).", + "pt": "Largura (por omissão 120)." + }, + { + "name": "h", + "type": "number", + "en": "Height (default 40).", + "pt": "Altura (por omissão 40)." + } + ], + "returns": { + "type": "integer", + "en": "Button entity id, or 0.", + "pt": "Id da entidade do botão, ou 0." + }, + "en": "Creates a button under a parent.", + "pt": "Cria um botão sob um pai.", + "example": "local b = caffeine.ui.createButton(canvas, 'Play', { x = 20, y = 60 })" + }, + { + "name": "hitTest", + "lua": "caffeine.ui.hitTest", + "dryad": null, + "signature": "hitTest(sx, sy) -> integer", + "params": [ + { + "name": "sx", + "type": "number", + "en": "Screen x.", + "pt": "x do ecrã." + }, + { + "name": "sy", + "type": "number", + "en": "Screen y.", + "pt": "y do ecrã." + } + ], + "returns": { + "type": "integer", + "en": "UI entity id under the point, or 0.", + "pt": "Id da entidade de UI sob o ponto, ou 0." + }, + "en": "Finds the UI element at a screen position.", + "pt": "Encontra o elemento de UI numa posição do ecrã.", + "example": "local hit = caffeine.ui.hitTest(100, 80)" + }, + { + "name": "setLabel", + "lua": "caffeine.ui.setLabel", + "dryad": null, + "signature": "setLabel(entity, text)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "text", + "type": "string", + "en": "New text (up to 255 characters).", + "pt": "Novo texto (até 255 caracteres)." + } + ], + "returns": null, + "en": "Changes a label's text. Does nothing when the entity has no label.", + "pt": "Muda o texto de um rótulo. Não faz nada se a entidade não tiver rótulo.", + "example": "caffeine.ui.setLabel(l, 'Score: 10')" + }, + { + "name": "setProgress", + "lua": "caffeine.ui.setProgress", + "dryad": null, + "signature": "setProgress(entity, normalized)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "normalized", + "type": "number", + "en": "0..1; clamped.", + "pt": "0..1; é limitado." + } + ], + "returns": null, + "en": "Sets a progress bar between its min and max. Does nothing when the entity has no progress bar.", + "pt": "Define uma barra de progresso entre o mínimo e o máximo. Não faz nada se a entidade não tiver barra de progresso.", + "example": "caffeine.ui.setProgress(bar, 0.5)" + } + ] +} diff --git a/src/caffeine/script/api/world.json b/src/caffeine/script/api/world.json new file mode 100644 index 00000000..2c185d27 --- /dev/null +++ b/src/caffeine/script/api/world.json @@ -0,0 +1,681 @@ +{ + "namespace": "world", + "group": "Core", + "lua": "caffeine.world", + "dryad_prefix": "caffeine_world_", + "title": { + "en": "World", + "pt": "Mundo" + }, + "summary": { + "en": "Create and destroy entities, move them, and read or write transforms, 2D physics, sprites and particle emitters. Dryad adds position and scale natives.", + "pt": "Criar e destruir entidades, movê-las e ler ou escrever transformações, física 2D, sprites e emissores de partículas. O Dryad acrescenta natives de posição e escala." + }, + "functions": [ + { + "name": "create", + "lua": "caffeine.world.create", + "dryad": "caffeine_world_create", + "signature": "create() -> integer", + "params": [], + "returns": { + "type": "integer", + "en": "The new entity id, or 0 when there is no world.", + "pt": "O id da nova entidade, ou 0 se não houver mundo." + }, + "en": "Creates an entity named \"LuaEntity\".", + "pt": "Cria uma entidade com o nome \"LuaEntity\".", + "example": "local e = caffeine.world.create()" + }, + { + "name": "destroy", + "lua": "caffeine.world.destroy", + "dryad": "caffeine_world_destroy", + "signature": "destroy(entity)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": null, + "en": "Destroys an entity. Does nothing when there is no world.", + "pt": "Destrói uma entidade. Não faz nada se não houver mundo.", + "example": "caffeine.world.destroy(e)" + }, + { + "name": "hasComponent", + "lua": "caffeine.world.hasComponent", + "dryad": null, + "signature": "hasComponent(entity, type) -> boolean", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "type", + "type": "string", + "en": "One of \"Transform\", \"Sprite\", \"RigidBody2D\", \"Collider2D\".", + "pt": "Um de \"Transform\", \"Sprite\", \"RigidBody2D\", \"Collider2D\"." + } + ], + "returns": { + "type": "boolean", + "en": "True when the entity has it; false for any other type name.", + "pt": "Verdadeiro se a entidade o tiver; falso para qualquer outro nome." + }, + "en": "Checks one of four built-in component types. \"Transform\" is also true for a Position3D. For other components use `caffeine.component.has`.", + "pt": "Verifica um de quatro tipos de componente incorporados. \"Transform\" também é verdadeiro para Position3D. Para outros componentes use `caffeine.component.has`.", + "example": "if caffeine.world.hasComponent(e, 'Sprite') then end" + }, + { + "name": "getTransform", + "lua": "caffeine.world.getTransform", + "dryad": null, + "signature": "getTransform(entity) -> table", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "table", + "en": "{x, y, z, rotation, scaleX, scaleY}; defaults 0 and scale 1.", + "pt": "{x, y, z, rotation, scaleX, scaleY}; por omissão 0 e escala 1." + }, + "en": "Reads the position of the entity (from Position3D or Transform); rotation and scale come from Transform.", + "pt": "Lê a posição da entidade (de Position3D ou Transform); a rotação e a escala vêm de Transform.", + "example": "local t = caffeine.world.getTransform(e)\ncaffeine.debug.log(t.x .. ', ' .. t.y)" + }, + { + "name": "setTransform", + "lua": "caffeine.world.setTransform", + "dryad": null, + "signature": "setTransform(entity, t)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "t", + "type": "table", + "en": "Fields x, y, z, rotation, scaleX, scaleY; missing fields keep the current value.", + "pt": "Campos x, y, z, rotation, scaleX, scaleY; os campos em falta mantêm o valor atual." + } + ], + "returns": null, + "en": "Writes position (and rotation/scale on a Transform). Creates a Transform when the entity has neither Transform nor Position3D.", + "pt": "Escreve a posição (e rotação/escala num Transform). Cria um Transform se a entidade não tiver Transform nem Position3D.", + "example": "caffeine.world.setTransform(e, { x = 1, y = 2 })" + }, + { + "name": "addTransform", + "lua": "caffeine.world.addTransform", + "dryad": null, + "signature": "addTransform(entity, t)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "t", + "type": "table", + "en": "Same fields as setTransform.", + "pt": "Os mesmos campos que setTransform." + } + ], + "returns": null, + "en": "Alias of `caffeine.world.setTransform`.", + "pt": "Alias de `caffeine.world.setTransform`.", + "example": "caffeine.world.addTransform(e, { x = 0, y = 0 })" + }, + { + "name": "distanceTo", + "lua": "caffeine.world.distanceTo", + "dryad": "caffeine_world_distance", + "signature": "distanceTo(a, b) -> number", + "params": [ + { + "name": "a", + "type": "integer", + "en": "First entity id.", + "pt": "Id da primeira entidade." + }, + { + "name": "b", + "type": "integer", + "en": "Second entity id.", + "pt": "Id da segunda entidade." + } + ], + "returns": { + "type": "number", + "en": "Distance in world units; 1e9 when either entity has no position or there is no world.", + "pt": "Distância em unidades do mundo; 1e9 se alguma entidade não tiver posição ou não houver mundo." + }, + "en": "Straight-line distance between two entities.", + "pt": "Distância em linha reta entre duas entidades.", + "example": "local d = caffeine.world.distanceTo(e, target)" + }, + { + "name": "findNearest", + "lua": "caffeine.world.findNearest", + "dryad": null, + "signature": "findNearest(from, maxDist) -> integer", + "params": [ + { + "name": "from", + "type": "integer", + "en": "Entity to search around.", + "pt": "Entidade à volta da qual procurar." + }, + { + "name": "maxDist", + "type": "number", + "en": "Search radius; must be greater than 0.", + "pt": "Raio de pesquisa; tem de ser maior que 0." + } + ], + "returns": { + "type": "integer", + "en": "Id of the nearest other entity with a position, or 0.", + "pt": "Id da entidade mais próxima com posição, ou 0." + }, + "en": "Finds the closest other entity that has a Position3D or Transform within maxDist.", + "pt": "Encontra a entidade mais próxima, com Position3D ou Transform, dentro de maxDist.", + "example": "local near = caffeine.world.findNearest(e, 10)" + }, + { + "name": "setYawPitch", + "lua": "caffeine.world.setYawPitch", + "dryad": null, + "signature": "setYawPitch(entity, yaw, pitch)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "yaw", + "type": "number", + "en": "Yaw in radians.", + "pt": "Guinada em radianos." + }, + { + "name": "pitch", + "type": "number", + "en": "Pitch in radians.", + "pt": "Inclinação em radianos." + } + ], + "returns": null, + "en": "Sets a 3D rotation (Rotation3D quaternion, roll 0). When the entity has a Transform its rotation x/y are also written in degrees.", + "pt": "Define uma rotação 3D (quaternião de Rotation3D, roll 0). Se a entidade tiver Transform, a rotação x/y também é escrita em graus.", + "example": "caffeine.world.setYawPitch(e, caffeine.math.radians(90), 0)" + }, + { + "name": "getRigidBody2D", + "lua": "caffeine.world.getRigidBody2D", + "dryad": null, + "signature": "getRigidBody2D(entity) -> table", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "table", + "en": "{mass, restitution, friction, linearDamping, isKinematic, lockRotation, velocityX, velocityY}; empty when there is no RigidBody2D.", + "pt": "{mass, restitution, friction, linearDamping, isKinematic, lockRotation, velocityX, velocityY}; vazia se não houver RigidBody2D." + }, + "en": "Reads the 2D rigid body of an entity.", + "pt": "Lê o corpo rígido 2D de uma entidade.", + "example": "local rb = caffeine.world.getRigidBody2D(e)" + }, + { + "name": "setRigidBody2D", + "lua": "caffeine.world.setRigidBody2D", + "dryad": null, + "signature": "setRigidBody2D(entity, t)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "t", + "type": "table", + "en": "Fields mass (1), restitution (0.3), friction (0.5), linearDamping (0), isKinematic (false), lockRotation (true), velocityX, velocityY.", + "pt": "Campos mass (1), restitution (0.3), friction (0.5), linearDamping (0), isKinematic (false), lockRotation (true), velocityX, velocityY." + } + ], + "returns": null, + "en": "Adds a RigidBody2D when missing and writes it. Fields you omit are reset to the defaults listed, except velocityX/velocityY, which keep their value.", + "pt": "Adiciona um RigidBody2D se não existir e escreve-o. Os campos omitidos voltam aos valores por omissão indicados, exceto velocityX/velocityY, que mantêm o valor.", + "example": "caffeine.world.setRigidBody2D(e, { mass = 2, friction = 0.8 })" + }, + { + "name": "getVelocity", + "lua": "caffeine.world.getVelocity", + "dryad": null, + "signature": "getVelocity(entity) -> table", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "table", + "en": "{x, y}; 0 when there is no RigidBody2D.", + "pt": "{x, y}; 0 se não houver RigidBody2D." + }, + "en": "Reads the 2D velocity of the rigid body.", + "pt": "Lê a velocidade 2D do corpo rígido.", + "example": "local v = caffeine.world.getVelocity(e)" + }, + { + "name": "setVelocity", + "lua": "caffeine.world.setVelocity", + "dryad": null, + "signature": "setVelocity(entity, v)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "v", + "type": "table", + "en": "{x, y}; missing fields keep the current value.", + "pt": "{x, y}; os campos em falta mantêm o valor atual." + } + ], + "returns": null, + "en": "Sets the 2D velocity (adds a RigidBody2D when missing) and wakes the body.", + "pt": "Define a velocidade 2D (adiciona um RigidBody2D se não existir) e acorda o corpo.", + "example": "caffeine.world.setVelocity(e, { x = 5, y = 0 })" + }, + { + "name": "getSprite", + "lua": "caffeine.world.getSprite", + "dryad": null, + "signature": "getSprite(entity) -> table", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "table", + "en": "{name, frameIndex}; empty when there is no Sprite.", + "pt": "{name, frameIndex}; vazia se não houver Sprite." + }, + "en": "Reads the sprite name and frame index.", + "pt": "Lê o nome e o índice de frame do sprite.", + "example": "local s = caffeine.world.getSprite(e)" + }, + { + "name": "setSprite", + "lua": "caffeine.world.setSprite", + "dryad": null, + "signature": "setSprite(entity, t)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "t", + "type": "table", + "en": "Fields name (string, default \"\") and frameIndex (default 0).", + "pt": "Campos name (texto, por omissão \"\") e frameIndex (por omissão 0)." + } + ], + "returns": null, + "en": "Adds a Sprite when missing and writes name and frame index.", + "pt": "Adiciona um Sprite se não existir e escreve o nome e o índice de frame.", + "example": "caffeine.world.setSprite(e, { name = 'hero', frameIndex = 2 })" + }, + { + "name": "addSprite", + "lua": "caffeine.world.addSprite", + "dryad": null, + "signature": "addSprite(entity, t)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "t", + "type": "table", + "en": "Same fields as setSprite.", + "pt": "Os mesmos campos que setSprite." + } + ], + "returns": null, + "en": "Alias of `caffeine.world.setSprite`.", + "pt": "Alias de `caffeine.world.setSprite`.", + "example": "caffeine.world.addSprite(e, { name = 'hero' })" + }, + { + "name": "addParticleEmitter", + "lua": "caffeine.world.addParticleEmitter", + "dryad": null, + "signature": "addParticleEmitter(entity, t)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "t", + "type": "table", + "en": "Fields maxParticles (100), emissionRate (10), lifetime (2), startSize (1), endSize (0), startColor and endColor ({r,g,b,a} in 0..1).", + "pt": "Campos maxParticles (100), emissionRate (10), lifetime (2), startSize (1), endSize (0), startColor e endColor ({r,g,b,a} em 0..1)." + } + ], + "returns": null, + "en": "Adds a particle emitter component to the entity (and a Transform when missing).", + "pt": "Adiciona um componente emissor de partículas à entidade (e um Transform se não existir).", + "example": "caffeine.world.addParticleEmitter(e, { emissionRate = 30, lifetime = 1.5 })" + }, + { + "name": "caffeine_world_is_alive", + "lua": null, + "dryad": "caffeine_world_is_alive", + "signature": "caffeine_world_is_alive(entity) -> boolean", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "boolean", + "en": "True when the entity exists.", + "pt": "Verdadeiro se a entidade existir." + }, + "en": "Dryad only: checks that an entity id still refers to a live entity.", + "pt": "Apenas Dryad: verifica se um id ainda corresponde a uma entidade viva.", + "example": "function onUpdate(entity, dt) {\n if (caffeine_world_is_alive(entity)) { caffeine_translate(entity, 0, dt, 0); }\n}" + }, + { + "name": "caffeine_set_position", + "lua": null, + "dryad": "caffeine_set_position", + "signature": "caffeine_set_position(entity, x, y, z)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "x", + "type": "number", + "en": "X.", + "pt": "X." + }, + { + "name": "y", + "type": "number", + "en": "Y.", + "pt": "Y." + }, + { + "name": "z", + "type": "number", + "en": "Z.", + "pt": "Z." + } + ], + "returns": null, + "en": "Dryad only: sets the position of an entity (Position3D and/or Transform; a Transform is created when it has neither).", + "pt": "Apenas Dryad: define a posição de uma entidade (Position3D e/ou Transform; é criado um Transform se não tiver nenhum).", + "example": "caffeine_set_position(entity, 0, 1, 0);" + }, + { + "name": "caffeine_translate", + "lua": null, + "dryad": "caffeine_translate", + "signature": "caffeine_translate(entity, dx, dy, dz)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "dx", + "type": "number", + "en": "Offset on X.", + "pt": "Deslocamento em X." + }, + { + "name": "dy", + "type": "number", + "en": "Offset on Y.", + "pt": "Deslocamento em Y." + }, + { + "name": "dz", + "type": "number", + "en": "Offset on Z.", + "pt": "Deslocamento em Z." + } + ], + "returns": null, + "en": "Dryad only: moves an entity by an offset.", + "pt": "Apenas Dryad: move uma entidade por um deslocamento.", + "example": "caffeine_translate(entity, 1 * dt, 0, 0);" + }, + { + "name": "caffeine_get_position_x", + "lua": null, + "dryad": "caffeine_get_position_x", + "signature": "caffeine_get_position_x(entity) -> number", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "number", + "en": "Position on X; 0 when the entity has none.", + "pt": "Posição em X; 0 se a entidade não tiver." + }, + "en": "Dryad only: reads the X position of an entity.", + "pt": "Apenas Dryad: lê a posição X de uma entidade.", + "example": "let p = caffeine_get_position_x(entity);" + }, + { + "name": "caffeine_get_position_y", + "lua": null, + "dryad": "caffeine_get_position_y", + "signature": "caffeine_get_position_y(entity) -> number", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "number", + "en": "Position on Y; 0 when the entity has none.", + "pt": "Posição em Y; 0 se a entidade não tiver." + }, + "en": "Dryad only: reads the Y position of an entity.", + "pt": "Apenas Dryad: lê a posição Y de uma entidade.", + "example": "let p = caffeine_get_position_y(entity);" + }, + { + "name": "caffeine_get_position_z", + "lua": null, + "dryad": "caffeine_get_position_z", + "signature": "caffeine_get_position_z(entity) -> number", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "number", + "en": "Position on Z; 0 when the entity has none.", + "pt": "Posição em Z; 0 se a entidade não tiver." + }, + "en": "Dryad only: reads the Z position of an entity.", + "pt": "Apenas Dryad: lê a posição Z de uma entidade.", + "example": "let p = caffeine_get_position_z(entity);" + }, + { + "name": "caffeine_set_scale", + "lua": null, + "dryad": "caffeine_set_scale", + "signature": "caffeine_set_scale(entity, x, y, z)", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + }, + { + "name": "x", + "type": "number", + "en": "Scale on X.", + "pt": "Escala em X." + }, + { + "name": "y", + "type": "number", + "en": "Scale on Y.", + "pt": "Escala em Y." + }, + { + "name": "z", + "type": "number", + "en": "Scale on Z.", + "pt": "Escala em Z." + } + ], + "returns": null, + "en": "Dryad only: sets the scale of an entity (Scale3D or Transform).", + "pt": "Apenas Dryad: define a escala de uma entidade (Scale3D ou Transform).", + "example": "caffeine_set_scale(entity, 2, 2, 2);" + }, + { + "name": "caffeine_get_scale_x", + "lua": null, + "dryad": "caffeine_get_scale_x", + "signature": "caffeine_get_scale_x(entity) -> number", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "number", + "en": "Scale on X; 1 when the entity has none.", + "pt": "Escala em X; 1 se a entidade não tiver." + }, + "en": "Dryad only: reads the X scale of an entity.", + "pt": "Apenas Dryad: lê a escala X de uma entidade.", + "example": "let s = caffeine_get_scale_x(entity);" + }, + { + "name": "caffeine_get_scale_y", + "lua": null, + "dryad": "caffeine_get_scale_y", + "signature": "caffeine_get_scale_y(entity) -> number", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "number", + "en": "Scale on Y; 1 when the entity has none.", + "pt": "Escala em Y; 1 se a entidade não tiver." + }, + "en": "Dryad only: reads the Y scale of an entity.", + "pt": "Apenas Dryad: lê a escala Y de uma entidade.", + "example": "let s = caffeine_get_scale_y(entity);" + }, + { + "name": "caffeine_get_scale_z", + "lua": null, + "dryad": "caffeine_get_scale_z", + "signature": "caffeine_get_scale_z(entity) -> number", + "params": [ + { + "name": "entity", + "type": "integer", + "en": "Entity id.", + "pt": "Id da entidade." + } + ], + "returns": { + "type": "number", + "en": "Scale on Z; 1 when the entity has none.", + "pt": "Escala em Z; 1 se a entidade não tiver." + }, + "en": "Dryad only: reads the Z scale of an entity.", + "pt": "Apenas Dryad: lê a escala Z de uma entidade.", + "example": "let s = caffeine_get_scale_z(entity);" + } + ] +} diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index e35291f7..56782074 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -64,6 +64,7 @@ if(CAF_PACK_AVAILABLE) target_compile_definitions(CaffeineTest PRIVATE CF_HAS_CAF_PACK=1) endif() +target_compile_definitions(CaffeineTest PRIVATE CF_SCRIPT_API_DIR="${CMAKE_SOURCE_DIR}/src/caffeine/script/api") target_include_directories(CaffeineTest PRIVATE ${CMAKE_CURRENT_SOURCE_DIR} ${CMAKE_CURRENT_SOURCE_DIR}/Catch2 ${CMAKE_SOURCE_DIR}/caf-pack/include) if(MSVC) target_compile_options(CaffeineTest PRIVATE /W4 /WX-) diff --git a/tests/test_dryad_host.cpp b/tests/test_dryad_host.cpp index 510d3aaa..65cc3221 100644 --- a/tests/test_dryad_host.cpp +++ b/tests/test_dryad_host.cpp @@ -229,4 +229,56 @@ TEST_CASE("Dryad natives read input, time and the world", "[dryad][runtime]") { std::remove(path.c_str()); } +TEST_CASE("Dryad properties override script globals", "[dryad][component]") { + const std::string path = "dryad_props.dyd"; + { + std::ofstream out(path); + out << "let speed = 1;\n" + << "function onUpdate(entity, dt) {\n caffeine_set_position(entity, speed, 0, 0);\n}\n"; + } + ECS::World world; + DryadHost host; + host.setWorld(&world); + ECS::Entity entity = world.create("DryadProps"); + entity.getOrAdd().position = Vec3(0, 0, 0); + REQUIRE(host.load(path)); + ScriptEngine::ExposedVar var; + var.name = "speed"; + var.kind = ScriptEngine::ExposedVar::Kind::Number; + var.number = 9.0; + REQUIRE(host.setProperty(path, var)); + REQUIRE(host.call(path, "onUpdate", entity, 0.016f)); + REQUIRE(entity.get()->position.x == 9.0f); + std::remove(path.c_str()); +} + +TEST_CASE("Dryad natives cover names, hierarchy and random", "[dryad][world]") { + const std::string path = "dryad_world_api.dyd"; + { + std::ofstream out(path); + out << "function onUpdate(entity, dt) {\n" + << " let a = caffeine_world_create(\"A\");\n" + << " let b = caffeine_world_create(\"B\");\n" + << " caffeine_entity_set_name(a, \"Boss\");\n" + << " caffeine_entity_set_name(b, \"Minion\");\n" + << " let score = 0;\n" + << " if (caffeine_hierarchy_set_parent(b, a)) { score = score + 1; }\n" + << " if (!caffeine_hierarchy_set_parent(a, b)) { score = score + 10; }\n" + << " if (caffeine_hierarchy_child_count(a) == 1 && caffeine_entity_find(\"Minion\") == b) { score = score + 100; }\n" + << " caffeine_random_set_seed(7);\n let r1 = caffeine_random_value();\n" + << " caffeine_random_set_seed(7);\n if (r1 == caffeine_random_value()) { score = score + 1000; }\n" + << " caffeine_set_position(entity, score, 0, 0);\n}\n"; + } + ECS::World world; + DryadHost host; + host.setWorld(&world); + ECS::Entity entity = world.create("DryadWorld"); + entity.getOrAdd().position = Vec3(0, 0, 0); + REQUIRE(host.load(path)); + std::string err; + REQUIRE(host.call(path, "onUpdate", entity, 0.016f, &err)); + REQUIRE(entity.get()->position.x == 1111.0f); + std::remove(path.c_str()); +} + #endif diff --git a/tests/test_script.cpp b/tests/test_script.cpp index 3dafe8fc..e6070dd7 100644 --- a/tests/test_script.cpp +++ b/tests/test_script.cpp @@ -4,6 +4,11 @@ #include "../src/caffeine/script/ScriptEngine.hpp" #include "../src/caffeine/script/ScriptSystem.hpp" +#include "../src/caffeine/script/ScriptProperties.hpp" +#include "../src/caffeine/script/ScriptCatalog.hpp" +#include "../src/caffeine/script/DryadHost.hpp" +#include "../src/caffeine/physics/PhysicsWorld3D.hpp" +#include "../src/caffeine/scene/EditorSceneSerializer.hpp" #include "../src/caffeine/script/ScriptTypes.hpp" #include "../src/caffeine/ecs/World.hpp" #include "../src/caffeine/ecs/Components.hpp" @@ -11,6 +16,11 @@ #include "../src/caffeine/events/EventBus.hpp" #include "../src/caffeine/debug/LogSystem.hpp" +#include +#include +#include +#include +#include #include using namespace Caffeine; @@ -368,6 +378,257 @@ TEST_CASE("Math supports 3D vectors and scalar helpers", "[script][math]") { REQUIRE(t->position.z == Approx(1.0f)); } +// ============================================================================ +// ScriptComponent: enabled, order and per-entity properties +// ============================================================================ + +TEST_CASE("ScriptComponent properties parse into typed exposed variables", "[script][component]") { + const auto vars = parseScriptProperties("speed = 4.5; god=true\nlabel=hello world;broken;=x"); + REQUIRE(vars.size() == 3); + REQUIRE(vars[0].name == "speed"); + REQUIRE(vars[0].kind == ScriptEngine::ExposedVar::Kind::Number); + REQUIRE(vars[0].number == Approx(4.5)); + REQUIRE(vars[1].kind == ScriptEngine::ExposedVar::Kind::Boolean); + REQUIRE(vars[1].boolean); + REQUIRE(vars[2].kind == ScriptEngine::ExposedVar::Kind::String); + REQUIRE(vars[2].string == "hello world"); +} + +TEST_CASE("ScriptSystem honours enabled, order and properties", "[script][component]") { + ScriptTestFixture fix; + REQUIRE(fix.engine.loadString(R"( + speed = 1 + function onUpdate(eid, dt) + local t = caffeine.world.getTransform(eid) + caffeine.world.setTransform(eid, {x = speed, y = t.y}) + end + )", "props.lua")); + + ScriptSystem system(&fix.engine); + auto on = fix.createEntity("props.lua"); + on.get()->properties = "speed=7"; + auto off = fix.createEntity("props.lua"); + off.get()->enabled = false; + off.add(transformAt(0, 0)); + on.add(transformAt(0, 0)); + + system.onUpdate(fix.world, 0.016f); + + REQUIRE(on.get()->position.x == Approx(7.0f)); + REQUIRE(off.get()->position.x == Approx(0.0f)); // disabled: never ran +} + +TEST_CASE("ScriptComponent fields survive a scene round trip", "[script][component][scene]") { + ECS::World world; + auto e = world.create("Scripted"); + ScriptComponent sc; + sc.scriptPath = "scripts/a.lua"; + sc.enabled = false; + sc.executionOrder = -5; + sc.properties = "speed=2"; + e.add(std::move(sc)); + + std::vector bytes; + Editor::SceneSerializer out(world); + REQUIRE(out.serializeToMemory(bytes)); + + ECS::World restored; + Editor::SceneSerializer in(restored); + REQUIRE(in.deserializeFromMemory(bytes)); + + bool found = false; + ECS::ComponentQuery q; + q.with(); + restored.forEach(q, [&](ECS::Entity, ScriptComponent& r) { + found = true; + REQUIRE(r.scriptPath == "scripts/a.lua"); + REQUIRE_FALSE(r.enabled); + REQUIRE(r.executionOrder == -5); + REQUIRE(r.properties == "speed=2"); + }); + REQUIRE(found); +} + +TEST_CASE("Isolated scripts keep private state per entity", "[script][component]") { + ScriptTestFixture fix; + REQUIRE(fix.engine.loadString("", "unused.lua")); + { + std::ofstream f("iso_test.lua"); + f << "count = 0\nfunction onUpdate(eid, dt)\n count = count + 1\n" + " caffeine.world.setTransform(eid, {x = count, y = 0})\nend\n"; + } + ScriptSystem system(&fix.engine); + auto a = fix.createEntity("iso_test.lua"); + auto b = fix.createEntity("iso_test.lua"); + a.add(transformAt(0, 0)); + b.add(transformAt(0, 0)); + a.get()->isolated = true; + b.get()->isolated = true; + system.onUpdate(fix.world, 0.016f); + system.onUpdate(fix.world, 0.016f); + // Shared state would give 2 and 4; private state gives 2 and 2. + REQUIRE(a.get()->position.x == Approx(2.0f)); + REQUIRE(b.get()->position.x == Approx(2.0f)); + std::remove("iso_test.lua"); +} + +TEST_CASE("Script catalog groups scripts by header tag or folder", "[script][catalog]") { + const auto tagged = parseScriptMeta("scripts/x.lua", + "-- @group Gameplay/Combat/Melee\n-- @name Sword\n-- @tags weapon, player\n-- @description Hits.\nfoo=1\n"); + REQUIRE(tagged.group == std::vector{"Gameplay", "Combat", "Melee"}); + REQUIRE(tagged.name == "Sword"); + REQUIRE(tagged.tags.size() == 2); + REQUIRE(tagged.description == "Hits."); + + const auto byFolder = parseScriptMeta("scripts/AI/Patrol/walk.dyd", "// plain\n"); + REQUIRE(byFolder.group == std::vector{"AI", "Patrol"}); + REQUIRE(byFolder.name == "walk"); + + const auto loose = parseScriptMeta("scripts/solo.lua", ""); + REQUIRE(loose.group.empty()); + + const auto tree = buildScriptTree({tagged, byFolder, loose}); + REQUIRE(tree.find("Gameplay/Combat/Melee")->scripts.size() == 1); + REQUIRE(tree.find("Gameplay")->totalScripts() == 1); + REQUIRE(tree.find("AI/Patrol")->scripts[0].name == "walk"); + REQUIRE(tree.find("Ungrouped")->scripts.size() == 1); + REQUIRE(tree.find("Nope") == nullptr); +} + +TEST_CASE("Dump script API names", "[.apidump]") { + ScriptTestFixture fix; + std::ofstream out("/tmp/lua_api.txt"); + for (const auto& n : fix.engine.apiNames()) out << n << "\n"; +#ifdef CF_HAS_DRYAD + std::ofstream d("/tmp/dryad_api.txt"); + for (const auto& n : DryadHost::nativeNames()) d << n << "\n"; +#endif +} + +TEST_CASE("Entity names, hierarchy and random work from Lua", "[script][world]") { + ScriptTestFixture fix; + const char* code = R"( + function onCreate(eid) + local a = caffeine.world.create() + local b = caffeine.world.create() + caffeine.entity.setName(a, "Boss") + caffeine.entity.setName(b, "Minion") + local ok = caffeine.hierarchy.setParent(b, a) + local cycle = caffeine.hierarchy.setParent(a, b) -- refused: cycle + local kids = caffeine.hierarchy.children(a) + local found = caffeine.entity.find("Minion") + caffeine.random.setSeed(42) + local r1 = caffeine.random.range(0, 1) + caffeine.random.setSeed(42) + local r2 = caffeine.random.range(0, 1) + local n = caffeine.random.int(3, 3) + local score = 0 + if ok then score = score + 1 end + if not cycle then score = score + 10 end + if #kids == 1 and kids[1] == b and found == b then score = score + 100 end + if r1 == r2 then score = score + 1000 end + if caffeine.hierarchy.root(b) == a and n == 3 then score = score + 10000 end + caffeine.world.setTransform(eid, {x = score, y = 0}) + end + )"; + REQUIRE(fix.engine.loadString(code, "world_api.lua")); + auto entity = fix.world.create("Test"); + REQUIRE(fix.engine.callOnCreate("world_api.lua", entity)); + REQUIRE(entity.get()->position.x == Approx(11111.0f)); +} + +// ---------------------------------------------------------------------------- +// Every scriptable function must be documented, and every documented function must exist. +// The reference lives in src/caffeine/script/api/*.json (see scripts/generate-script-api-docs.py). +// ---------------------------------------------------------------------------- + +static std::set registryNames(const char* key) { + namespace fs = std::filesystem; + std::set names; + const std::string needle = std::string("\"") + key + "\": \""; + for (const auto& file : fs::directory_iterator(CF_SCRIPT_API_DIR)) { + if (file.path().extension() != ".json") continue; + std::ifstream in(file.path()); + std::stringstream ss; + ss << in.rdbuf(); + const std::string text = ss.str(); + for (size_t pos = text.find(needle); pos != std::string::npos; pos = text.find(needle, pos + 1)) { + const size_t start = pos + needle.size(); + names.insert(text.substr(start, text.find('"', start) - start)); + } + } + // A namespace header ("lua": "caffeine.world") is a prefix of its functions, not a function. + for (auto it = names.begin(); it != names.end();) { + const std::string prefix = *it + "."; + const bool isNamespace = std::any_of(names.begin(), names.end(), [&](const std::string& other) { + return other.size() > prefix.size() && other.compare(0, prefix.size(), prefix) == 0; + }); + it = isNamespace ? names.erase(it) : std::next(it); + } + return names; +} + +TEST_CASE("Lua API is fully documented", "[script][api-docs]") { + ScriptTestFixture fix; + const auto documented = registryNames("lua"); + std::set actual; + for (const auto& n : fix.engine.apiNames()) actual.insert(n); + for (const auto& n : actual) { INFO("undocumented Lua function: " << n); CHECK(documented.count(n) == 1); } + for (const auto& n : documented) { INFO("documented but missing in Lua: " << n); CHECK(actual.count(n) == 1); } +} + +#ifdef CF_HAS_DRYAD +TEST_CASE("Dryad natives are fully documented", "[dryad][api-docs]") { + const auto documented = registryNames("dryad"); + std::set actual; + for (const auto& n : DryadHost::nativeNames()) actual.insert(n); + for (const auto& n : actual) { INFO("undocumented Dryad native: " << n); CHECK(documented.count(n) == 1); } + for (const auto& n : documented) { INFO("documented but missing in Dryad: " << n); CHECK(actual.count(n) == 1); } +} +#endif + +TEST_CASE("physics3d queries and forces work from Lua", "[script][physics3d]") { + ScriptTestFixture fix; + Physics3D::PhysicsWorld3D physics; + if (!physics.isAvailable()) { WARN("Bullet3 not enabled in this build"); return; } + fix.engine.setPhysics3D(&physics); + + Physics3D::BodyDesc ground; + ground.entityId = 1; + ground.shape = Physics3D::ColliderShape3D::Box; + ground.halfExtents = Vec3(5.0f, 0.5f, 5.0f); + ground.bodyType = Physics3D::BodyType3D::Static; + ground.mass = 0.0f; + physics.upsertBody(ground); + Physics3D::BodyDesc ball; + ball.entityId = 2; + ball.position = Vec3(0.0f, 3.0f, 0.0f); + ball.shape = Physics3D::ColliderShape3D::Sphere; + ball.halfExtents = Vec3(0.5f, 0.5f, 0.5f); + physics.upsertBody(ball); + physics.step(1.0f / 60.0f); + + const char* code = R"( + function onCreate(eid) + local hit = caffeine.physics3d.raycast(0, 10, 0, 0, -1, 0, 50) -- hits the ball first + local miss = caffeine.physics3d.raycast(0, 10, 0, 0, 1, 0, 50) -- nothing above + local ok = caffeine.physics3d.setVelocity(2, 4, 0, 0) + local v = caffeine.physics3d.velocity(2) + local nope = caffeine.physics3d.addForce(1, 0, 10, 0) -- static: refused + local score = 0 + if hit and hit.entity == 2 and hit.distance > 6 and hit.distance < 7.5 then score = score + 1 end + if miss == nil then score = score + 10 end + if ok and v and v.x > 3.9 then score = score + 100 end + if not nope then score = score + 1000 end + caffeine.world.setTransform(eid, {x = score, y = 0}) + end + )"; + REQUIRE(fix.engine.loadString(code, "phys3d.lua")); + auto entity = fix.world.create("Test"); + REQUIRE(fix.engine.callOnCreate("phys3d.lua", entity)); + REQUIRE(entity.get()->position.x == Approx(1111.0f)); +} + // ============================================================================ // 11. Math binding — add, sub, dot, scale // ============================================================================ From 37eab191cb64d6d872d877897f34f2dbb2ed3a96 Mon Sep 17 00:00:00 2001 From: lyeepedro Date: Thu, 19 Nov 2026 17:50:54 +0000 Subject: [PATCH 3/6] Scripting: audio, scene and session APIs; runtime handles scene requests - AudioService: WAV decode/cache, handles, positional 2D; runtime creates and updates it - SceneRequests (deferred load/reload) and SessionStore (data across scenes) - Lua caffeine.audio/scene/session and Dryad caffeine_audio_*/scene_*/session_* natives - API registry: 232 functions in 29 namespaces Co-Authored-By: Claude Sonnet 5.5 --- CMakeLists.txt | 3 + apps/runtime/main.cpp | 35 ++ caffeine-website | 2 +- src/caffeine/audio/AudioService.cpp | 187 +++++++++++ src/caffeine/audio/AudioService.hpp | 63 ++++ src/caffeine/script/AudioSceneBindings.cpp | 61 ++++ .../script/DryadAudioSceneBindings.cpp | 78 +++++ src/caffeine/script/DryadHost.cpp | 8 + src/caffeine/script/DryadHost.hpp | 4 + src/caffeine/script/ScriptEngine.cpp | 11 + src/caffeine/script/ScriptEngine.hpp | 8 + src/caffeine/script/ScriptHostServices.hpp | 60 ++++ src/caffeine/script/ScriptSystem.cpp | 2 + src/caffeine/script/api/audio.json | 317 ++++++++++++++++++ src/caffeine/script/api/scene.json | 75 +++++ src/caffeine/script/api/session.json | 117 +++++++ tests/test_dryad_host.cpp | 30 ++ tests/test_script.cpp | 59 ++++ 18 files changed, 1119 insertions(+), 1 deletion(-) create mode 100644 src/caffeine/audio/AudioService.cpp create mode 100644 src/caffeine/audio/AudioService.hpp create mode 100644 src/caffeine/script/AudioSceneBindings.cpp create mode 100644 src/caffeine/script/DryadAudioSceneBindings.cpp create mode 100644 src/caffeine/script/ScriptHostServices.hpp create mode 100644 src/caffeine/script/api/audio.json create mode 100644 src/caffeine/script/api/scene.json create mode 100644 src/caffeine/script/api/session.json diff --git a/CMakeLists.txt b/CMakeLists.txt index 48a26ff5..68159037 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -464,6 +464,8 @@ if(CAFFEINE_ENABLE_SCRIPTING) src/caffeine/script/NativeModuleHost.cpp src/caffeine/script/WorldApiBindings.cpp src/caffeine/script/Physics3DBindings.cpp + src/caffeine/script/AudioSceneBindings.cpp + src/caffeine/audio/AudioService.cpp ) if(DRYAD_AVAILABLE) target_sources(caffeine-core PRIVATE @@ -472,6 +474,7 @@ if(CAFFEINE_ENABLE_SCRIPTING) src/caffeine/script/DryadRuntimeBindings.cpp src/caffeine/script/DryadWorldBindings.cpp src/caffeine/script/DryadPhysics3DBindings.cpp + src/caffeine/script/DryadAudioSceneBindings.cpp src/caffeine/script/nodes/NodeGraph.cpp src/caffeine/script/nodes/NodeCatalog.cpp src/caffeine/script/nodes/NodeEmitter.cpp diff --git a/apps/runtime/main.cpp b/apps/runtime/main.cpp index 3dde95f7..3faf7ff4 100644 --- a/apps/runtime/main.cpp +++ b/apps/runtime/main.cpp @@ -6,6 +6,7 @@ #include "events/Events.hpp" #include "input/InputManager.hpp" #include "physics/PhysicsSystem2D.hpp" +#include "audio/AudioService.hpp" #include "physics/PhysicsSystem3D.hpp" #include "script/ScriptEngine.hpp" #include "script/ScriptSystem.hpp" @@ -463,6 +464,9 @@ int main(int argc, char** argv) { Caffeine::Events::EventBus eventBus; Caffeine::Physics2D::PhysicsSystem2D physics(&eventBus); Caffeine::Physics3D::PhysicsSystem3D physics3d; + Caffeine::Audio::AudioService audio; + audio.setSearchRoot(buildRoot.string()); + if (!audio.init()) std::fprintf(stderr, "caffeine-runtime: no audio device, sound disabled\n"); Caffeine::Animation::AnimationSystem animation; Caffeine::UI::UISystem uiSystem(&eventBus); Caffeine::Script::ScriptEngine scriptEngine; @@ -472,8 +476,10 @@ int main(int argc, char** argv) { scriptParams.events = &eventBus; scriptParams.ui = &uiSystem; scriptParams.physics3d = &physics3d.world(); + scriptParams.audio = &audio; const bool scriptsReady = scriptEngine.init(scriptParams); scriptEngine.setSearchRoot(buildRoot.string()); + scriptEngine.sceneRequests().setCurrent(config.LastScene); Caffeine::Script::ScriptSystem scriptSystem(scriptsReady ? &scriptEngine : nullptr, &eventBus); if (!config.RootPath.empty()) { scriptSystem.setProjectRoot(config.RootPath.string()); @@ -557,7 +563,36 @@ int main(int argc, char** argv) { scriptEngine.setWorld(&world); scriptEngine.setInput(&input); scriptSystem.onUpdate(world, dt); + + // A script asked for another scene: swap it now, between frames' scripts. + auto& sceneRequests = scriptEngine.sceneRequests(); + if (sceneRequests.hasPending()) { + const std::string requested = sceneRequests.take(); + std::filesystem::path next(requested); + if (!std::filesystem::exists(next)) next = buildRoot / requested; + if (std::filesystem::exists(next)) { + physics3d.reset(); + Caffeine::Editor::SceneSerializer serializer(world); + if (serializer.deserialize(next.string())) { + Caffeine::Scene::resetNaturalFluidRuntime(); + scriptSystem.resetPlayState(); + audio.stopAll(); + sceneRequests.setCurrent(requested); + scenePath = next; + sceneLoaded = true; +#ifdef CF_HAS_IMGUI + editorCtx.currentScenePath = scenePath.string(); +#endif + std::printf("Loaded scene: %s\n", next.string().c_str()); + } else { + std::fprintf(stderr, "caffeine-runtime: scene failed to load: %s\n", next.string().c_str()); + } + } else { + std::fprintf(stderr, "caffeine-runtime: scene not found: %s\n", requested.c_str()); + } + } } + audio.update(dt); Caffeine::Procedural::ProceduralWorldSystem::update(world); uiSystem.onUpdate(world, dt); } diff --git a/caffeine-website b/caffeine-website index 84e4ec5b..f13b4a20 160000 --- a/caffeine-website +++ b/caffeine-website @@ -1 +1 @@ -Subproject commit 84e4ec5bda7817b104136f82f30d502a92be4387 +Subproject commit f13b4a20ae90184b3c269f15b2c61915627b4fc1 diff --git a/src/caffeine/audio/AudioService.cpp b/src/caffeine/audio/AudioService.cpp new file mode 100644 index 00000000..dd45f0fc --- /dev/null +++ b/src/caffeine/audio/AudioService.cpp @@ -0,0 +1,187 @@ +#include "audio/AudioService.hpp" + +#include "debug/LogSystem.hpp" + +#ifdef CF_HAS_SDL3 +#include "audio/AudioSystem.hpp" +#include +#endif + +#include +#include +#include + +namespace Caffeine::Audio { + +#ifdef CF_HAS_SDL3 + +struct AudioService::Impl { + struct Loaded { + std::vector pcm; // signed 16-bit interleaved + AudioClip clip; + }; + + AudioSystem system; + std::string root; + std::unordered_map> clips; + std::unordered_map handles; + u32 nextHandle = 1; + + std::string resolve(const std::string& path) const { + namespace fs = std::filesystem; + std::error_code ec; + if (fs::exists(path, ec)) return path; + if (!root.empty()) { + const fs::path rooted = fs::path(root) / path; + if (fs::exists(rooted, ec)) return rooted.string(); + } + return path; + } + + Loaded* load(const std::string& path, std::string* error) { + auto it = clips.find(path); + if (it != clips.end()) return it->second.get(); + + const std::string file = resolve(path); + SDL_AudioSpec spec{}; + Uint8* data = nullptr; + Uint32 length = 0; + if (!SDL_LoadWAV(file.c_str(), &spec, &data, &length)) { + if (error) *error = std::string("cannot read WAV: ") + file; + return nullptr; + } + auto loaded = std::make_unique(); + SDL_AudioSpec dst = spec; + dst.format = SDL_AUDIO_S16; + if (spec.format == SDL_AUDIO_S16) { + loaded->pcm.assign(data, data + length); + } else { + Uint8* converted = nullptr; + int convertedLength = 0; + if (!SDL_ConvertAudioSamples(&spec, data, static_cast(length), &dst, &converted, &convertedLength)) { + SDL_free(data); + if (error) *error = "cannot convert audio format"; + return nullptr; + } + loaded->pcm.assign(converted, converted + convertedLength); + SDL_free(converted); + } + SDL_free(data); + + const u32 bytesPerFrame = static_cast(dst.channels) * 2u; + loaded->clip.data = loaded->pcm.data(); + loaded->clip.size = loaded->pcm.size(); + loaded->clip.sampleRate = static_cast(dst.freq); + loaded->clip.channels = static_cast(dst.channels); + loaded->clip.bitsPerSample = 16; + loaded->clip.duration = bytesPerFrame && dst.freq + ? static_cast(loaded->pcm.size() / bytesPerFrame) / static_cast(dst.freq) : 0.0f; + Loaded* raw = loaded.get(); + clips.emplace(path, std::move(loaded)); + return raw; + } + + u32 track(AudioSource* source) { + if (!source) return 0; + // Drop handles whose sound ended so the table stays small. + for (auto it = handles.begin(); it != handles.end();) { + it = it->second->isFree() ? handles.erase(it) : std::next(it); + } + const u32 id = nextHandle++; + handles[id] = source; + return id; + } + + AudioSource* find(u32 handle) const { + auto it = handles.find(handle); + if (it == handles.end() || it->second->isFree()) return nullptr; + return it->second; + } +}; + +AudioService::AudioService() : m_impl(new Impl()) {} +AudioService::~AudioService() { shutdown(); } + +bool AudioService::init() { return m_impl->system.init(); } +void AudioService::shutdown() { + if (!m_impl) return; + m_impl->handles.clear(); + m_impl->system.shutdown(); +} +bool AudioService::ready() const { return m_impl->system.isInitialized(); } +void AudioService::setSearchRoot(const std::string& root) { m_impl->root = root; } + +bool AudioService::preload(const std::string& path, std::string* error) { + return m_impl->load(path, error) != nullptr; +} + +f32 AudioService::duration(const std::string& path) const { + auto it = m_impl->clips.find(path); + return it == m_impl->clips.end() ? 0.0f : it->second->clip.duration; +} + +u32 AudioService::play(const std::string& path, f32 volume, f32 pan, bool loop) { + if (!ready()) return 0; + std::string error; + Impl::Loaded* clip = m_impl->load(path, &error); + if (!clip) { CF_WARN("Audio", "%s", error.c_str()); return 0; } + AudioSource* source = m_impl->system.playSFX(&clip->clip, volume, pan); + if (source) source->setLoop(loop); + return m_impl->track(source); +} + +u32 AudioService::playAt(const std::string& path, f32 x, f32 y, f32 maxDistance, f32 volume) { + if (!ready()) return 0; + std::string error; + Impl::Loaded* clip = m_impl->load(path, &error); + if (!clip) { CF_WARN("Audio", "%s", error.c_str()); return 0; } + AudioSource* source = m_impl->system.playSFXAt(&clip->clip, Vec2{x, y}, maxDistance); + if (source) source->setVolume(source->volume() * volume); + return m_impl->track(source); +} + +bool AudioService::stop(u32 h) { auto* s = m_impl->find(h); if (!s) return false; s->stop(); return true; } +bool AudioService::pause(u32 h) { auto* s = m_impl->find(h); if (!s) return false; s->pause(); return true; } +bool AudioService::resume(u32 h) { auto* s = m_impl->find(h); if (!s) return false; s->play(); return true; } +bool AudioService::setVolume(u32 h, f32 v) { auto* s = m_impl->find(h); if (!s) return false; s->setVolume(v); return true; } +bool AudioService::setLoop(u32 h, bool l) { auto* s = m_impl->find(h); if (!s) return false; s->setLoop(l); return true; } +bool AudioService::isPlaying(u32 h) const { auto* s = m_impl->find(h); return s && s->isPlaying(); } + +void AudioService::stopAll() { + for (auto& [_, s] : m_impl->handles) if (!s->isFree()) s->stop(); + m_impl->handles.clear(); +} + +void AudioService::setMasterVolume(f32 v) { m_impl->system.setMasterVolume(v); } +f32 AudioService::masterVolume() const { return m_impl->system.masterVolume(); } +void AudioService::setListener(f32 x, f32 y) { m_impl->system.setListenerPosition(Vec2{x, y}); } +void AudioService::update(f32 dt) { m_impl->system.update(static_cast(dt)); } + +#else // no SDL3: every call is a no-op + +struct AudioService::Impl {}; +AudioService::AudioService() : m_impl(new Impl()) {} +AudioService::~AudioService() = default; +bool AudioService::init() { return false; } +void AudioService::shutdown() {} +bool AudioService::ready() const { return false; } +void AudioService::setSearchRoot(const std::string&) {} +bool AudioService::preload(const std::string&, std::string* error) { if (error) *error = "audio not built in"; return false; } +f32 AudioService::duration(const std::string&) const { return 0.0f; } +u32 AudioService::play(const std::string&, f32, f32, bool) { return 0; } +u32 AudioService::playAt(const std::string&, f32, f32, f32, f32) { return 0; } +bool AudioService::stop(u32) { return false; } +bool AudioService::pause(u32) { return false; } +bool AudioService::resume(u32) { return false; } +bool AudioService::setVolume(u32, f32) { return false; } +bool AudioService::setLoop(u32, bool) { return false; } +bool AudioService::isPlaying(u32) const { return false; } +void AudioService::stopAll() {} +void AudioService::setMasterVolume(f32) {} +f32 AudioService::masterVolume() const { return 1.0f; } +void AudioService::setListener(f32, f32) {} +void AudioService::update(f32) {} + +#endif + +} // namespace Caffeine::Audio diff --git a/src/caffeine/audio/AudioService.hpp b/src/caffeine/audio/AudioService.hpp new file mode 100644 index 00000000..fa00c8b3 --- /dev/null +++ b/src/caffeine/audio/AudioService.hpp @@ -0,0 +1,63 @@ +#pragma once + +// Script-facing audio: loads WAV files from the project, plays them on the shared SFX pool and +// hands out numeric handles, so Lua and Dryad can control a sound after starting it. +// +// Handles are only valid while the sound plays: once it ends, its pool slot can be reused by a +// later sound and an old handle then refers to that one. Without an audio device (CI, headless) +// every call is a safe no-op that returns 0 / false. + +#include "core/Types.hpp" + +#include +#include + +namespace Caffeine::Audio { + +class AudioService { +public: + AudioService(); + ~AudioService(); + AudioService(const AudioService&) = delete; + AudioService& operator=(const AudioService&) = delete; + + /// Opens the default playback device. Returns false when there is none. + bool init(); + void shutdown(); + bool ready() const; + + /// Relative clip paths resolve against this root (and are tried as given first). + void setSearchRoot(const std::string& root); + + /// Decodes a WAV into memory without needing a device (used by tests and preloading). + /// Returns false when the file is missing or not a readable WAV. + bool preload(const std::string& path, std::string* error = nullptr); + /// Duration in seconds of a loaded clip, 0 when unknown. + f32 duration(const std::string& path) const; + + /// Starts a sound; returns a handle (> 0) or 0 when it could not play. + u32 play(const std::string& path, f32 volume = 1.0f, f32 pan = 0.0f, bool loop = false); + /// Positional 2D sound: volume and pan come from the distance to the listener. + u32 playAt(const std::string& path, f32 x, f32 y, f32 maxDistance = 500.0f, f32 volume = 1.0f); + + bool stop(u32 handle); + bool pause(u32 handle); + bool resume(u32 handle); + bool setVolume(u32 handle, f32 volume); + bool setLoop(u32 handle, bool loop); + bool isPlaying(u32 handle) const; + void stopAll(); + + void setMasterVolume(f32 volume); + f32 masterVolume() const; + void setListener(f32 x, f32 y); + + /// Call once per frame. + void update(f32 dt); + +private: + struct Impl; + std::unique_ptr m_impl; +}; + +} // namespace Caffeine::Audio diff --git a/src/caffeine/script/AudioSceneBindings.cpp b/src/caffeine/script/AudioSceneBindings.cpp new file mode 100644 index 00000000..1440dd3e --- /dev/null +++ b/src/caffeine/script/AudioSceneBindings.cpp @@ -0,0 +1,61 @@ +#include "audio/AudioService.hpp" +#include "script/ScriptHostServices.hpp" + +#include + +namespace Caffeine::Script { + +// `caffeine.audio`, `caffeine.scene` and `caffeine.session`. +void registerAudioSceneBindings(sol::state& lua, Audio::AudioService** audioPtr, SceneRequests* scenes) { + auto audio = [audioPtr]() -> Audio::AudioService* { return audioPtr ? *audioPtr : nullptr; }; + + sol::table a = lua["caffeine"]["audio"].get_or_create(); + a["isAvailable"] = [audio]() { auto* s = audio(); return s && s->ready(); }; + a["play"] = [audio](const std::string& path, sol::optional volume, sol::optional pan, sol::optional loop) -> u32 { + auto* s = audio(); + return s ? s->play(path, volume.value_or(1.0f), pan.value_or(0.0f), loop.value_or(false)) : 0u; + }; + a["playAt"] = [audio](const std::string& path, f32 x, f32 y, sol::optional maxDistance, sol::optional volume) -> u32 { + auto* s = audio(); + return s ? s->playAt(path, x, y, maxDistance.value_or(500.0f), volume.value_or(1.0f)) : 0u; + }; + a["stop"] = [audio](u32 h) { auto* s = audio(); return s && s->stop(h); }; + a["pause"] = [audio](u32 h) { auto* s = audio(); return s && s->pause(h); }; + a["resume"] = [audio](u32 h) { auto* s = audio(); return s && s->resume(h); }; + a["setVolume"] = [audio](u32 h, f32 v) { auto* s = audio(); return s && s->setVolume(h, v); }; + a["setLoop"] = [audio](u32 h, bool l) { auto* s = audio(); return s && s->setLoop(h, l); }; + a["isPlaying"] = [audio](u32 h) { auto* s = audio(); return s && s->isPlaying(h); }; + a["stopAll"] = [audio]() { if (auto* s = audio()) s->stopAll(); }; + a["setMasterVolume"] = [audio](f32 v) { if (auto* s = audio()) s->setMasterVolume(v); }; + a["masterVolume"] = [audio]() -> f32 { auto* s = audio(); return s ? s->masterVolume() : 0.0f; }; + a["setListener"] = [audio](f32 x, f32 y) { if (auto* s = audio()) s->setListener(x, y); }; + + sol::table sc = lua["caffeine"]["scene"].get_or_create(); + sc["load"] = [scenes](const std::string& path) { if (scenes && !path.empty()) scenes->requestLoad(path); }; + sc["reload"] = [scenes]() { if (scenes) scenes->requestReload(); }; + sc["current"] = [scenes]() { return scenes ? scenes->current() : std::string(); }; + sc["isLoading"] = [scenes]() { return scenes && scenes->hasPending(); }; + + sol::table ss = lua["caffeine"]["session"].get_or_create(); + ss["set"] = [](const std::string& key, sol::object value) { + auto& store = SessionStore::instance(); + if (value.is()) store.setBoolean(key, value.as()); + else if (value.is()) store.setNumber(key, value.as()); + else if (value.is()) store.setString(key, value.as()); + else store.remove(key); // nil removes + }; + ss["get"] = [](const std::string& key, sol::this_state s) -> sol::object { + const auto* v = SessionStore::instance().get(key); + if (!v) return sol::nil; + switch (v->kind) { + case SessionStore::Value::Kind::Boolean: return sol::make_object(s, v->boolean); + case SessionStore::Value::Kind::Number: return sol::make_object(s, v->number); + default: return sol::make_object(s, v->string); + } + }; + ss["has"] = [](const std::string& key) { return SessionStore::instance().get(key) != nullptr; }; + ss["remove"] = [](const std::string& key) { return SessionStore::instance().remove(key); }; + ss["clear"] = []() { SessionStore::instance().clear(); }; +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/DryadAudioSceneBindings.cpp b/src/caffeine/script/DryadAudioSceneBindings.cpp new file mode 100644 index 00000000..4081a16b --- /dev/null +++ b/src/caffeine/script/DryadAudioSceneBindings.cpp @@ -0,0 +1,78 @@ +// Dryad natives for audio, scene changes and the session store; same behaviour as Lua's +// `caffeine.audio`, `caffeine.scene` and `caffeine.session`. + +#include "audio/AudioService.hpp" +#include "script/DryadNatives.hpp" +#include "script/ScriptHostServices.hpp" + +namespace Caffeine::Script { + +using Args = std::vector; + +namespace { +double num(const Args& a, size_t i, double fallback = 0.0) { + if (i >= a.size()) return fallback; + if (a[i].is_integer()) return static_cast(a[i].as_integer()); + if (a[i].is_float()) return a[i].as_float(); + return fallback; +} +std::string str(const Args& a, size_t i) { return i < a.size() && a[i].is_string() ? a[i].as_string() : std::string(); } +bool flag(const Args& a, size_t i) { return i < a.size() && a[i].is_boolean() && a[i].as_boolean(); } +dryad::Value handle(u32 h) { return dryad::Value(static_cast(h)); } +} // namespace + +void bindAudioSceneNatives(dryad::Interpreter& interp, Audio::AudioService** audioPtr, SceneRequests* scenes) { + auto audio = [audioPtr]() -> Audio::AudioService* { return audioPtr ? *audioPtr : nullptr; }; + + defineNative(interp, "caffeine_audio_available", [=](const Args&) { auto* s = audio(); return dryad::Value(s && s->ready()); }); + defineNative(interp, "caffeine_audio_play", [=](const Args& a) { + auto* s = audio(); + return handle(s ? s->play(str(a, 0), static_cast(num(a, 1, 1.0)), static_cast(num(a, 2, 0.0)), flag(a, 3)) : 0u); }); + defineNative(interp, "caffeine_audio_play_at", [=](const Args& a) { + auto* s = audio(); + return handle(s ? s->playAt(str(a, 0), static_cast(num(a, 1)), static_cast(num(a, 2)), + static_cast(num(a, 3, 500.0)), static_cast(num(a, 4, 1.0))) : 0u); }); + defineNative(interp, "caffeine_audio_stop", [=](const Args& a) { auto* s = audio(); return dryad::Value(s && s->stop(static_cast(num(a, 0)))); }); + defineNative(interp, "caffeine_audio_pause", [=](const Args& a) { auto* s = audio(); return dryad::Value(s && s->pause(static_cast(num(a, 0)))); }); + defineNative(interp, "caffeine_audio_resume", [=](const Args& a) { auto* s = audio(); return dryad::Value(s && s->resume(static_cast(num(a, 0)))); }); + defineNative(interp, "caffeine_audio_set_volume", [=](const Args& a) { auto* s = audio(); return dryad::Value(s && s->setVolume(static_cast(num(a, 0)), static_cast(num(a, 1)))); }); + defineNative(interp, "caffeine_audio_set_loop", [=](const Args& a) { auto* s = audio(); return dryad::Value(s && s->setLoop(static_cast(num(a, 0)), flag(a, 1))); }); + defineNative(interp, "caffeine_audio_is_playing", [=](const Args& a) { auto* s = audio(); return dryad::Value(s && s->isPlaying(static_cast(num(a, 0)))); }); + defineNative(interp, "caffeine_audio_stop_all", [=](const Args&) { if (auto* s = audio()) s->stopAll(); return dryad::Value(); }); + defineNative(interp, "caffeine_audio_set_master_volume", [=](const Args& a) { if (auto* s = audio()) s->setMasterVolume(static_cast(num(a, 0))); return dryad::Value(); }); + defineNative(interp, "caffeine_audio_master_volume", [=](const Args&) { auto* s = audio(); return dryad::Value(s ? static_cast(s->masterVolume()) : 0.0); }); + defineNative(interp, "caffeine_audio_set_listener", [=](const Args& a) { if (auto* s = audio()) s->setListener(static_cast(num(a, 0)), static_cast(num(a, 1))); return dryad::Value(); }); + + defineNative(interp, "caffeine_scene_load", [=](const Args& a) { if (scenes && !str(a, 0).empty()) scenes->requestLoad(str(a, 0)); return dryad::Value(); }); + defineNative(interp, "caffeine_scene_reload", [=](const Args&) { if (scenes) scenes->requestReload(); return dryad::Value(); }); + defineNative(interp, "caffeine_scene_current", [=](const Args&) { return dryad::Value(scenes ? scenes->current() : std::string()); }); + defineNative(interp, "caffeine_scene_is_loading", [=](const Args&) { return dryad::Value(scenes && scenes->hasPending()); }); + + defineNative(interp, "caffeine_session_set", [](const Args& a) { + auto& store = SessionStore::instance(); + const std::string key = str(a, 0); + if (a.size() < 2) { store.remove(key); return dryad::Value(); } + if (a[1].is_boolean()) store.setBoolean(key, a[1].as_boolean()); + else if (a[1].is_integer() || a[1].is_float()) store.setNumber(key, num(a, 1)); + else if (a[1].is_string()) store.setString(key, a[1].as_string()); + else store.remove(key); + return dryad::Value(); }); + defineNative(interp, "caffeine_session_get", [](const Args& a) { + const auto* v = SessionStore::instance().get(str(a, 0)); + if (!v) return dryad::Value(); + switch (v->kind) { + case SessionStore::Value::Kind::Boolean: return dryad::Value(v->boolean); + case SessionStore::Value::Kind::Number: + // Whole numbers come back as integers so `get(k) == 3` works in Dryad. + if (v->number == static_cast(static_cast(v->number))) { + return dryad::Value(static_cast(v->number)); + } + return dryad::Value(v->number); + default: return dryad::Value(v->string); + } }); + defineNative(interp, "caffeine_session_has", [](const Args& a) { return dryad::Value(SessionStore::instance().get(str(a, 0)) != nullptr); }); + defineNative(interp, "caffeine_session_remove", [](const Args& a) { return dryad::Value(SessionStore::instance().remove(str(a, 0))); }); + defineNative(interp, "caffeine_session_clear", [](const Args&) { SessionStore::instance().clear(); return dryad::Value(); }); +} + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/DryadHost.cpp b/src/caffeine/script/DryadHost.cpp index 119d0c28..5c9c9991 100644 --- a/src/caffeine/script/DryadHost.cpp +++ b/src/caffeine/script/DryadHost.cpp @@ -26,6 +26,7 @@ void bindRuntimeNatives(dryad::Interpreter& interp, ECS::World** worldPtr, Input::InputManager** inputPtr); void bindWorldApiNatives(dryad::Interpreter& interp, ECS::World** worldPtr); void bindPhysics3DNatives(dryad::Interpreter& interp, Physics3D::PhysicsWorld3D** physicsPtr); +void bindAudioSceneNatives(dryad::Interpreter& interp, Audio::AudioService** audioPtr, SceneRequests* scenes); namespace { @@ -126,6 +127,8 @@ struct DryadHost::Impl { ECS::World* world = nullptr; Input::InputManager* input = nullptr; Physics3D::PhysicsWorld3D* physics3d = nullptr; + Audio::AudioService* audio = nullptr; + SceneRequests* scenes = nullptr; std::string searchRoot; std::unordered_map sessions; @@ -207,6 +210,7 @@ struct DryadHost::Impl { bindRuntimeNatives(interp, worldPtr, &input); bindWorldApiNatives(interp, worldPtr); bindPhysics3DNatives(interp, &physics3d); + bindAudioSceneNatives(interp, &audio, scenes); interp.set_network_allowed(false); if (const char* stdlib = std::getenv("DRYAD_STDLIB_DIR")) { interp.set_stdlib_root(stdlib); @@ -229,6 +233,10 @@ void DryadHost::setInput(Input::InputManager* input) { m_impl->input = input; } void DryadHost::setPhysics3D(Physics3D::PhysicsWorld3D* physics) { m_impl->physics3d = physics; } +void DryadHost::setAudio(Audio::AudioService* audio) { m_impl->audio = audio; } + +void DryadHost::setSceneRequests(SceneRequests* scenes) { m_impl->scenes = scenes; } + void DryadHost::setSearchRoot(const std::string& root) { m_impl->searchRoot = root; } std::string DryadHost::searchRoot() const { return m_impl->searchRoot; } diff --git a/src/caffeine/script/DryadHost.hpp b/src/caffeine/script/DryadHost.hpp index 00f728a6..8b11c56d 100644 --- a/src/caffeine/script/DryadHost.hpp +++ b/src/caffeine/script/DryadHost.hpp @@ -10,6 +10,7 @@ namespace Caffeine::ECS { class World; } namespace Caffeine::Input { class InputManager; } namespace Caffeine::Physics3D { class PhysicsWorld3D; } +namespace Caffeine::Audio { class AudioService; } namespace Caffeine::Script { @@ -27,6 +28,9 @@ class DryadHost { void setInput(Input::InputManager* input); /// Optional; enables the `caffeine_physics3d_*` natives. void setPhysics3D(Physics3D::PhysicsWorld3D* physics); + /// Optional; enables `caffeine_audio_*`, and `caffeine_scene_*` when `scenes` is set. + void setAudio(Audio::AudioService* audio); + void setSceneRequests(SceneRequests* scenes); /// Project root used to resolve relative script paths (for example /// `scripts/player.dyd`). Relative paths that already exist from the diff --git a/src/caffeine/script/ScriptEngine.cpp b/src/caffeine/script/ScriptEngine.cpp index af06ae7d..e005af15 100644 --- a/src/caffeine/script/ScriptEngine.cpp +++ b/src/caffeine/script/ScriptEngine.cpp @@ -35,6 +35,7 @@ void registerNavigationScriptBindings(sol::state& lua, ECS::World** worldPtr); void registerComponentScriptBindings(sol::state& lua, ECS::World** worldPtr); void registerWorldApiBindings(sol::state& lua, ECS::World** worldPtr); void registerPhysics3DBindings(sol::state& lua, Physics3D::PhysicsWorld3D** physicsPtr); +void registerAudioSceneBindings(sol::state& lua, Audio::AudioService** audioPtr, SceneRequests* scenes); sol::table makePostProcessScriptHandle(sol::state_view lua, ECS::World** worldPtr, u32 entityId); // ============================================================================ @@ -49,6 +50,8 @@ struct ScriptEngine::Impl { Events::EventBus* m_events = nullptr; UI::UISystem* m_ui = nullptr; Physics3D::PhysicsWorld3D* m_physics3d = nullptr; + Audio::AudioService* m_audio = nullptr; + SceneRequests m_scenes; HashMap m_envs; std::string m_searchRoot; @@ -665,6 +668,7 @@ bool ScriptEngine::init(const InitParams& params) { m_impl->m_events = params.events; m_impl->m_ui = params.ui; m_impl->m_physics3d = params.physics3d; + m_impl->m_audio = params.audio; auto& lua = m_impl->m_lua; @@ -756,6 +760,7 @@ bool ScriptEngine::init(const InitParams& params) { registerComponentScriptBindings(lua, &m_impl->m_world); registerWorldApiBindings(lua, &m_impl->m_world); registerPhysics3DBindings(lua, &m_impl->m_physics3d); + registerAudioSceneBindings(lua, &m_impl->m_audio, &m_impl->m_scenes); registerRuntimeScriptBindings( lua, &m_impl->m_world, &m_impl->m_input, &m_impl->m_ui, &m_impl->m_assetText, @@ -844,6 +849,12 @@ void ScriptEngine::setPhysics3D(Physics3D::PhysicsWorld3D* physics) { m_impl->m_ Physics3D::PhysicsWorld3D* ScriptEngine::physics3d() const { return m_impl->m_physics3d; } +void ScriptEngine::setAudio(Audio::AudioService* audio) { m_impl->m_audio = audio; } + +Audio::AudioService* ScriptEngine::audio() const { return m_impl->m_audio; } + +SceneRequests& ScriptEngine::sceneRequests() { return m_impl->m_scenes; } + void ScriptEngine::setInput(Input::InputManager* input) { m_impl->m_input = input; } diff --git a/src/caffeine/script/ScriptEngine.hpp b/src/caffeine/script/ScriptEngine.hpp index 7746883c..4cb24fb7 100644 --- a/src/caffeine/script/ScriptEngine.hpp +++ b/src/caffeine/script/ScriptEngine.hpp @@ -2,6 +2,7 @@ #include "core/Types.hpp" #include "ecs/Entity.hpp" +#include "script/ScriptHostServices.hpp" #include #include @@ -11,6 +12,7 @@ namespace Caffeine { namespace Input { class InputManager; } } namespace Caffeine { namespace Events { class EventBus; } } namespace Caffeine { namespace UI { class UISystem; } } namespace Caffeine { namespace Physics3D { class PhysicsWorld3D; } } +namespace Caffeine { namespace Audio { class AudioService; } } namespace Caffeine::Script { @@ -29,6 +31,8 @@ class ScriptEngine { UI::UISystem* ui = nullptr; /// Optional: enables `caffeine.physics3d` (raycast, forces, velocity). Physics3D::PhysicsWorld3D* physics3d = nullptr; + /// Optional: enables `caffeine.audio`. + Audio::AudioService* audio = nullptr; }; bool init(const InitParams& params); @@ -38,6 +42,10 @@ class ScriptEngine { Input::InputManager* input() const; void setPhysics3D(Physics3D::PhysicsWorld3D* physics); Physics3D::PhysicsWorld3D* physics3d() const; + void setAudio(Audio::AudioService* audio); + Audio::AudioService* audio() const; + /// Scene changes requested by scripts; the host polls `hasPending()` after each frame. + SceneRequests& sceneRequests(); void setSearchRoot(const std::string& root); struct ExposedVar { diff --git a/src/caffeine/script/ScriptHostServices.hpp b/src/caffeine/script/ScriptHostServices.hpp new file mode 100644 index 00000000..ded64000 --- /dev/null +++ b/src/caffeine/script/ScriptHostServices.hpp @@ -0,0 +1,60 @@ +#pragma once + +// Small host-side services scripts talk to. They hold no engine objects: a script only records +// a request (load a scene) or reads/writes plain data (the session store); the host acts on it +// at a safe point of its frame. + +#include "core/Types.hpp" + +#include +#include + +namespace Caffeine::Script { + +/// A scene change requested by a script. It is deferred: the world is replaced after the +/// frame's scripts have finished, never while one is running. +class SceneRequests { +public: + void requestLoad(const std::string& path) { m_pending = path; m_hasPending = true; } + void requestReload() { requestLoad(m_current); } + bool hasPending() const { return m_hasPending; } + /// Returns the requested path and clears the request. + std::string take() { m_hasPending = false; return std::move(m_pending); } + + /// The host reports the scene that is loaded now (a project-relative or absolute path). + void setCurrent(const std::string& path) { m_current = path; } + const std::string& current() const { return m_current; } + +private: + std::string m_pending; + std::string m_current; + bool m_hasPending = false; +}; + +/// Values that survive scene changes for the lifetime of the process: score, settings, the +/// player's choices. Booleans, numbers and text only. +class SessionStore { +public: + struct Value { + enum class Kind { Number, Boolean, String } kind = Kind::Number; + double number = 0.0; + bool boolean = false; + std::string string; + }; + static SessionStore& instance() { static SessionStore s; return s; } + + void setNumber(const std::string& k, double v) { Value x; x.kind = Value::Kind::Number; x.number = v; m_values[k] = x; } + void setBoolean(const std::string& k, bool v) { Value x; x.kind = Value::Kind::Boolean; x.boolean = v; m_values[k] = x; } + void setString(const std::string& k, const std::string& v) { Value x; x.kind = Value::Kind::String; x.string = v; m_values[k] = x; } + const Value* get(const std::string& k) const { + auto it = m_values.find(k); + return it == m_values.end() ? nullptr : &it->second; + } + bool remove(const std::string& k) { return m_values.erase(k) > 0; } + void clear() { m_values.clear(); } + +private: + std::unordered_map m_values; +}; + +} // namespace Caffeine::Script diff --git a/src/caffeine/script/ScriptSystem.cpp b/src/caffeine/script/ScriptSystem.cpp index 5d49dcb1..f3fabbc4 100644 --- a/src/caffeine/script/ScriptSystem.cpp +++ b/src/caffeine/script/ScriptSystem.cpp @@ -141,6 +141,8 @@ void ScriptSystem::processDryadScripts(ECS::World& world, f32 dt) { if (m_engine) { m_dryad->setInput(m_engine->input()); m_dryad->setPhysics3D(m_engine->physics3d()); + m_dryad->setAudio(m_engine->audio()); + m_dryad->setSceneRequests(&m_engine->sceneRequests()); } if (!m_projectRoot.empty()) m_dryad->setSearchRoot(m_projectRoot); diff --git a/src/caffeine/script/api/audio.json b/src/caffeine/script/api/audio.json new file mode 100644 index 00000000..c2f37965 --- /dev/null +++ b/src/caffeine/script/api/audio.json @@ -0,0 +1,317 @@ +{ + "namespace": "audio", + "group": "Game", + "lua": "caffeine.audio", + "dryad_prefix": "caffeine_audio_", + "title": { + "en": "Audio", + "pt": "Áudio" + }, + "summary": { + "en": "Plays WAV files from the project. Play returns a handle you use to control that sound while it is playing. Without an audio device every call is a safe no-op (0 or false). Handles are only valid while the sound plays: after it ends, the slot may be reused by another sound.", + "pt": "Reproduz ficheiros WAV do projeto. O play devolve um handle para controlar esse som enquanto toca. Sem dispositivo de áudio, todas as chamadas são no-ops seguros (0 ou false). Os handles só são válidos enquanto o som toca: depois de acabar, o espaço pode ser reutilizado por outro som." + }, + "functions": [ + { + "name": "isAvailable", + "lua": "caffeine.audio.isAvailable", + "dryad": "caffeine_audio_available", + "signature": "isAvailable() -> boolean", + "params": [], + "returns": { + "type": "boolean", + "en": "true when a playback device is open.", + "pt": "true quando há um dispositivo de reprodução aberto." + }, + "en": "Tells whether sound can be played.", + "pt": "Indica se é possível reproduzir som.", + "example": "if not caffeine.audio.isAvailable() then caffeine.debug.warn(\"no sound\") end" + }, + { + "name": "play", + "lua": "caffeine.audio.play", + "dryad": "caffeine_audio_play", + "signature": "play(path[, volume[, pan[, loop]]]) -> number", + "params": [ + { + "name": "path", + "type": "string", + "en": "WAV file, relative to the project root.", + "pt": "Ficheiro WAV, relativo à raiz do projeto." + }, + { + "name": "volume", + "type": "number", + "en": "0 to 1, default 1.", + "pt": "0 a 1, por omissão 1." + }, + { + "name": "pan", + "type": "number", + "en": "-1 left to 1 right, default 0.", + "pt": "-1 esquerda a 1 direita, por omissão 0." + }, + { + "name": "loop", + "type": "boolean", + "en": "Repeat until stopped, default false.", + "pt": "Repetir até parar, por omissão false." + } + ], + "returns": { + "type": "number", + "en": "A handle greater than 0, or 0 when the sound could not play (no device, missing file, all 32 channels busy).", + "pt": "Um handle maior que 0, ou 0 quando o som não pôde tocar (sem dispositivo, ficheiro em falta, 32 canais ocupados)." + }, + "en": "Plays a sound. The file is decoded once and cached.", + "pt": "Toca um som. O ficheiro é descodificado uma vez e fica em cache.", + "example": "local h = caffeine.audio.play(\"audio/jump.wav\", 0.8)" + }, + { + "name": "playAt", + "lua": "caffeine.audio.playAt", + "dryad": "caffeine_audio_play_at", + "signature": "playAt(path, x, y[, maxDistance[, volume]]) -> number", + "params": [ + { + "name": "path", + "type": "string", + "en": "WAV file, relative to the project root.", + "pt": "Ficheiro WAV, relativo à raiz do projeto." + }, + { + "name": "x, y", + "type": "number", + "en": "Sound position in the 2D world.", + "pt": "Posição do som no mundo 2D." + }, + { + "name": "maxDistance", + "type": "number", + "en": "Distance at which the sound is silent, default 500.", + "pt": "Distância a que o som fica mudo, por omissão 500." + }, + { + "name": "volume", + "type": "number", + "en": "Extra gain, default 1.", + "pt": "Ganho extra, por omissão 1." + } + ], + "returns": { + "type": "number", + "en": "A handle, or 0 when it could not play.", + "pt": "Um handle, ou 0 se não pôde tocar." + }, + "en": "Plays a sound whose volume and left/right pan follow its distance to the listener (see setListener).", + "pt": "Toca um som cujo volume e panning esquerda/direita seguem a distância ao ouvinte (ver setListener).", + "example": "caffeine.audio.playAt(\"audio/boom.wav\", 120, 40, 300)" + }, + { + "name": "stop", + "lua": "caffeine.audio.stop", + "dryad": "caffeine_audio_stop", + "signature": "stop(handle) -> boolean", + "params": [ + { + "name": "handle", + "type": "number", + "en": "Handle returned by play or playAt.", + "pt": "Handle devolvido por play ou playAt." + } + ], + "returns": { + "type": "boolean", + "en": "false when the handle is unknown or the sound has already ended.", + "pt": "false se o handle for desconhecido ou o som já tiver terminado." + }, + "en": "Stops a sound.", + "pt": "Para um som.", + "example": "caffeine.audio.stop(h)" + }, + { + "name": "pause", + "lua": "caffeine.audio.pause", + "dryad": "caffeine_audio_pause", + "signature": "pause(handle) -> boolean", + "params": [ + { + "name": "handle", + "type": "number", + "en": "Handle returned by play or playAt.", + "pt": "Handle devolvido por play ou playAt." + } + ], + "returns": { + "type": "boolean", + "en": "false when the handle is unknown or the sound has already ended.", + "pt": "false se o handle for desconhecido ou o som já tiver terminado." + }, + "en": "Pauses a sound; resume continues it.", + "pt": "Pausa um som; o resume continua-o.", + "example": "caffeine.audio.pause(h)" + }, + { + "name": "resume", + "lua": "caffeine.audio.resume", + "dryad": "caffeine_audio_resume", + "signature": "resume(handle) -> boolean", + "params": [ + { + "name": "handle", + "type": "number", + "en": "Handle returned by play or playAt.", + "pt": "Handle devolvido por play ou playAt." + } + ], + "returns": { + "type": "boolean", + "en": "false when the handle is unknown or the sound has already ended.", + "pt": "false se o handle for desconhecido ou o som já tiver terminado." + }, + "en": "Resumes a paused sound.", + "pt": "Retoma um som em pausa.", + "example": "caffeine.audio.resume(h)" + }, + { + "name": "setVolume", + "lua": "caffeine.audio.setVolume", + "dryad": "caffeine_audio_set_volume", + "signature": "setVolume(handle, volume) -> boolean", + "params": [ + { + "name": "handle", + "type": "number", + "en": "Handle returned by play or playAt.", + "pt": "Handle devolvido por play ou playAt." + }, + { + "name": "volume", + "type": "number", + "en": "0 to 1.", + "pt": "0 a 1." + } + ], + "returns": { + "type": "boolean", + "en": "false when the handle is unknown or the sound has already ended.", + "pt": "false se o handle for desconhecido ou o som já tiver terminado." + }, + "en": "Changes the volume of a playing sound.", + "pt": "Altera o volume de um som a tocar.", + "example": "caffeine.audio.setVolume(h, 0.3)" + }, + { + "name": "setLoop", + "lua": "caffeine.audio.setLoop", + "dryad": "caffeine_audio_set_loop", + "signature": "setLoop(handle, loop) -> boolean", + "params": [ + { + "name": "handle", + "type": "number", + "en": "Handle returned by play or playAt.", + "pt": "Handle devolvido por play ou playAt." + }, + { + "name": "loop", + "type": "boolean", + "en": "true to repeat.", + "pt": "true para repetir." + } + ], + "returns": { + "type": "boolean", + "en": "false when the handle is unknown or the sound has already ended.", + "pt": "false se o handle for desconhecido ou o som já tiver terminado." + }, + "en": "Turns looping on or off for a playing sound.", + "pt": "Liga ou desliga a repetição de um som a tocar.", + "example": "caffeine.audio.setLoop(h, false)" + }, + { + "name": "isPlaying", + "lua": "caffeine.audio.isPlaying", + "dryad": "caffeine_audio_is_playing", + "signature": "isPlaying(handle) -> boolean", + "params": [ + { + "name": "handle", + "type": "number", + "en": "Handle returned by play or playAt.", + "pt": "Handle devolvido por play ou playAt." + } + ], + "returns": { + "type": "boolean", + "en": "true while the sound plays (not paused, not ended).", + "pt": "true enquanto o som toca (não em pausa, não terminado)." + }, + "en": "Tells whether a sound is still playing.", + "pt": "Indica se um som ainda está a tocar.", + "example": "if not caffeine.audio.isPlaying(h) then h = caffeine.audio.play(\"audio/loop.wav\") end" + }, + { + "name": "stopAll", + "lua": "caffeine.audio.stopAll", + "dryad": "caffeine_audio_stop_all", + "signature": "stopAll()", + "params": [], + "returns": null, + "en": "Stops every sound. Scene changes do this automatically.", + "pt": "Para todos os sons. As mudanças de cena fazem-no automaticamente.", + "example": "caffeine.audio.stopAll()" + }, + { + "name": "setMasterVolume", + "lua": "caffeine.audio.setMasterVolume", + "dryad": "caffeine_audio_set_master_volume", + "signature": "setMasterVolume(volume)", + "params": [ + { + "name": "volume", + "type": "number", + "en": "0 to 1.", + "pt": "0 a 1." + } + ], + "returns": null, + "en": "Sets the volume applied to sounds started afterwards.", + "pt": "Define o volume aplicado aos sons iniciados depois.", + "example": "caffeine.audio.setMasterVolume(0.5)" + }, + { + "name": "masterVolume", + "lua": "caffeine.audio.masterVolume", + "dryad": "caffeine_audio_master_volume", + "signature": "masterVolume() -> number", + "params": [], + "returns": { + "type": "number", + "en": "The master volume, 0 to 1 (0 without audio).", + "pt": "O volume geral, 0 a 1 (0 sem áudio)." + }, + "en": "Reads the master volume.", + "pt": "Lê o volume geral.", + "example": "local v = caffeine.audio.masterVolume()" + }, + { + "name": "setListener", + "lua": "caffeine.audio.setListener", + "dryad": "caffeine_audio_set_listener", + "signature": "setListener(x, y)", + "params": [ + { + "name": "x, y", + "type": "number", + "en": "Listener position in the 2D world.", + "pt": "Posição do ouvinte no mundo 2D." + } + ], + "returns": null, + "en": "Sets where playAt measures distance from, usually the player or camera.", + "pt": "Define o ponto de onde o playAt mede a distância, normalmente o jogador ou a câmara.", + "example": "caffeine.audio.setListener(player_x, player_y)" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/scene.json b/src/caffeine/script/api/scene.json new file mode 100644 index 00000000..4f8ea5c7 --- /dev/null +++ b/src/caffeine/script/api/scene.json @@ -0,0 +1,75 @@ +{ + "namespace": "scene", + "group": "Game", + "lua": "caffeine.scene", + "dryad_prefix": "caffeine_scene_", + "title": { + "en": "Scene", + "pt": "Cena" + }, + "summary": { + "en": "Switching between scenes. A request is deferred: the world is replaced after the current frame's scripts finish, so call it freely from any hook. The runtime app handles requests; other hosts may not. A scene change removes every entity, so keep data you need in `caffeine.session`.", + "pt": "Mudança entre cenas. O pedido é diferido: o mundo é substituído depois dos scripts do frame atual, por isso pode chamá-lo de qualquer hook. A aplicação runtime trata os pedidos; outros hosts podem não tratar. Uma mudança de cena remove todas as entidades, por isso guarde em `caffeine.session` os dados de que precisa." + }, + "functions": [ + { + "name": "load", + "lua": "caffeine.scene.load", + "dryad": "caffeine_scene_load", + "signature": "load(path)", + "params": [ + { + "name": "path", + "type": "string", + "en": "Scene file, relative to the project root or absolute.", + "pt": "Ficheiro de cena, relativo à raiz do projeto ou absoluto." + } + ], + "returns": null, + "en": "Asks the host to load a scene, replacing the current one. A missing or unreadable file is reported and the current scene stays.", + "pt": "Pede ao host para carregar uma cena, substituindo a atual. Um ficheiro em falta ou ilegível é reportado e a cena atual mantém-se.", + "example": "if caffeine.session.get(\"coins\") >= 10 then caffeine.scene.load(\"scenes/win.scene\") end" + }, + { + "name": "reload", + "lua": "caffeine.scene.reload", + "dryad": "caffeine_scene_reload", + "signature": "reload()", + "params": [], + "returns": null, + "en": "Reloads the current scene from disk, resetting it to its saved state.", + "pt": "Recarrega a cena atual do disco, repondo o seu estado guardado.", + "example": "caffeine.scene.reload() -- restart the level" + }, + { + "name": "current", + "lua": "caffeine.scene.current", + "dryad": "caffeine_scene_current", + "signature": "current() -> string", + "params": [], + "returns": { + "type": "string", + "en": "The path of the loaded scene as given to the host (empty when unknown).", + "pt": "O caminho da cena carregada tal como foi dado ao host (vazio se desconhecido)." + }, + "en": "Returns the loaded scene.", + "pt": "Devolve a cena carregada.", + "example": "caffeine.debug.log(caffeine.scene.current())" + }, + { + "name": "isLoading", + "lua": "caffeine.scene.isLoading", + "dryad": "caffeine_scene_is_loading", + "signature": "isLoading() -> boolean", + "params": [], + "returns": { + "type": "boolean", + "en": "true after load or reload was requested and before the host handled it.", + "pt": "true depois de load ou reload serem pedidos e antes de o host os tratar." + }, + "en": "Tells whether a scene change is waiting to happen.", + "pt": "Indica se há uma mudança de cena à espera de acontecer.", + "example": "if caffeine.scene.isLoading() then return end" + } + ] +} \ No newline at end of file diff --git a/src/caffeine/script/api/session.json b/src/caffeine/script/api/session.json new file mode 100644 index 00000000..da2944b8 --- /dev/null +++ b/src/caffeine/script/api/session.json @@ -0,0 +1,117 @@ +{ + "namespace": "session", + "group": "Game", + "lua": "caffeine.session", + "dryad_prefix": "caffeine_session_", + "title": { + "en": "Session", + "pt": "Sessão" + }, + "summary": { + "en": "A key-value store that survives scene changes for as long as the game runs (score, settings, choices). Values are numbers, booleans or text. It is not saved to disk.", + "pt": "Um armazenamento chave-valor que sobrevive às mudanças de cena enquanto o jogo corre (pontuação, definições, escolhas). Os valores são números, booleanos ou texto. Não é gravado em disco." + }, + "functions": [ + { + "name": "set", + "lua": "caffeine.session.set", + "dryad": "caffeine_session_set", + "signature": "set(key, value)", + "params": [ + { + "name": "key", + "type": "string", + "en": "Name of the value.", + "pt": "Nome do valor." + }, + { + "name": "value", + "type": "number | boolean | string | nil", + "en": "The value to keep; nil removes the key.", + "pt": "O valor a guardar; nil remove a chave." + } + ], + "returns": null, + "en": "Stores a value.", + "pt": "Guarda um valor.", + "example": "caffeine.session.set(\"coins\", 12)" + }, + { + "name": "get", + "lua": "caffeine.session.get", + "dryad": "caffeine_session_get", + "signature": "get(key) -> any", + "params": [ + { + "name": "key", + "type": "string", + "en": "Name of the value.", + "pt": "Nome do valor." + } + ], + "returns": { + "type": "number | boolean | string | nil", + "en": "The stored value, or nil when the key does not exist.", + "pt": "O valor guardado, ou nil quando a chave não existe." + }, + "en": "Reads a value.", + "pt": "Lê um valor.", + "example": "local coins = caffeine.session.get(\"coins\") or 0" + }, + { + "name": "has", + "lua": "caffeine.session.has", + "dryad": "caffeine_session_has", + "signature": "has(key) -> boolean", + "params": [ + { + "name": "key", + "type": "string", + "en": "Name of the value.", + "pt": "Nome do valor." + } + ], + "returns": { + "type": "boolean", + "en": "true when the key exists.", + "pt": "true quando a chave existe." + }, + "en": "Tells whether a key exists.", + "pt": "Indica se uma chave existe.", + "example": "if caffeine.session.has(\"checkpoint\") then end" + }, + { + "name": "remove", + "lua": "caffeine.session.remove", + "dryad": "caffeine_session_remove", + "signature": "remove(key) -> boolean", + "params": [ + { + "name": "key", + "type": "string", + "en": "Name of the value.", + "pt": "Nome do valor." + } + ], + "returns": { + "type": "boolean", + "en": "true when the key existed.", + "pt": "true quando a chave existia." + }, + "en": "Deletes a key.", + "pt": "Apaga uma chave.", + "example": "caffeine.session.remove(\"checkpoint\")" + }, + { + "name": "clear", + "lua": "caffeine.session.clear", + "dryad": "caffeine_session_clear", + "signature": "clear()", + "params": [], + "returns": null, + "en": "Deletes every key.", + "pt": "Apaga todas as chaves.", + "example": "caffeine.session.clear() -- new game" + } + ] +} \ No newline at end of file diff --git a/tests/test_dryad_host.cpp b/tests/test_dryad_host.cpp index 65cc3221..b23e401e 100644 --- a/tests/test_dryad_host.cpp +++ b/tests/test_dryad_host.cpp @@ -281,4 +281,34 @@ TEST_CASE("Dryad natives cover names, hierarchy and random", "[dryad][world]") { std::remove(path.c_str()); } +TEST_CASE("Dryad natives cover scenes, session and audio", "[dryad][scene][audio]") { + const std::string path = "dryad_scene_api.dyd"; + { + std::ofstream out(path); + out << "function onUpdate(entity, dt) {\n" + << " let score = 0;\n" + << " caffeine_session_set(\"lives\", 3);\n" + << " if (caffeine_session_get(\"lives\") == 3) { score = score + 1; }\n" + << " if (!caffeine_session_has(\"nope\")) { score = score + 10; }\n" + << " if (caffeine_audio_play(\"x.wav\") == 0) { score = score + 100; }\n" + << " caffeine_scene_load(\"scenes/two.scene\");\n" + << " if (caffeine_scene_is_loading()) { score = score + 1000; }\n" + << " caffeine_set_position(entity, score, 0, 0);\n}\n"; + } + ECS::World world; + SceneRequests scenes; + DryadHost host; + host.setWorld(&world); + host.setSceneRequests(&scenes); + ECS::Entity entity = world.create("DryadScene"); + entity.getOrAdd().position = Vec3(0, 0, 0); + REQUIRE(host.load(path)); + std::string err; + REQUIRE(host.call(path, "onUpdate", entity, 0.016f, &err)); + REQUIRE(entity.get()->position.x == 1111.0f); + REQUIRE(scenes.take() == "scenes/two.scene"); + SessionStore::instance().clear(); + std::remove(path.c_str()); +} + #endif diff --git a/tests/test_script.cpp b/tests/test_script.cpp index e6070dd7..a9500127 100644 --- a/tests/test_script.cpp +++ b/tests/test_script.cpp @@ -8,6 +8,7 @@ #include "../src/caffeine/script/ScriptCatalog.hpp" #include "../src/caffeine/script/DryadHost.hpp" #include "../src/caffeine/physics/PhysicsWorld3D.hpp" +#include "../src/caffeine/audio/AudioService.hpp" #include "../src/caffeine/scene/EditorSceneSerializer.hpp" #include "../src/caffeine/script/ScriptTypes.hpp" #include "../src/caffeine/ecs/World.hpp" @@ -629,6 +630,64 @@ TEST_CASE("physics3d queries and forces work from Lua", "[script][physics3d]") { REQUIRE(entity.get()->position.x == Approx(1111.0f)); } +static void writeTestWav(const std::string& path, int samples, int rate) { + std::ofstream f(path, std::ios::binary); + auto u32le = [&](uint32_t v) { f.write(reinterpret_cast(&v), 4); }; + auto u16le = [&](uint16_t v) { f.write(reinterpret_cast(&v), 2); }; + const uint32_t dataBytes = static_cast(samples) * 2; + f.write("RIFF", 4); u32le(36 + dataBytes); f.write("WAVEfmt ", 8); + u32le(16); u16le(1); u16le(1); u32le(static_cast(rate)); u32le(static_cast(rate) * 2); u16le(2); u16le(16); + f.write("data", 4); u32le(dataBytes); + for (int i = 0; i < samples; ++i) u16le(static_cast((i % 100) * 100)); +} + +TEST_CASE("AudioService decodes WAV and is a safe no-op without a device", "[script][audio]") { + writeTestWav("audio_test.wav", 800, 8000); + Audio::AudioService audio; + std::string error; + REQUIRE(audio.preload("audio_test.wav", &error)); + REQUIRE(audio.duration("audio_test.wav") == Approx(0.1f)); + REQUIRE_FALSE(audio.preload("missing.wav")); + if (!audio.init()) { // no device (CI): nothing plays, nothing crashes + REQUIRE(audio.play("audio_test.wav") == 0); + REQUIRE_FALSE(audio.stop(1)); + } + std::remove("audio_test.wav"); +} + +TEST_CASE("audio, scene and session APIs work from Lua", "[script][audio][scene]") { + ScriptTestFixture fix; + Audio::AudioService audio; // not initialised: the API must still answer + fix.engine.setAudio(&audio); + fix.engine.sceneRequests().setCurrent("scenes/start.scene"); + const char* code = R"( + function onCreate(eid) + local score = 0 + if caffeine.audio.isAvailable() == false then score = score + 1 end + if caffeine.audio.play("nope.wav") == 0 then score = score + 10 end + caffeine.session.set("coins", 7) + caffeine.session.set("name", "Ana") + caffeine.session.set("hard", true) + if caffeine.session.get("coins") == 7 and caffeine.session.get("name") == "Ana" + and caffeine.session.get("hard") == true and caffeine.session.get("zzz") == nil then score = score + 100 end + caffeine.session.remove("coins") + if not caffeine.session.has("coins") then score = score + 1000 end + if caffeine.scene.current() == "scenes/start.scene" and not caffeine.scene.isLoading() then score = score + 10000 end + caffeine.scene.load("scenes/level2.scene") + if caffeine.scene.isLoading() then score = score + 100000 end + caffeine.world.setTransform(eid, {x = score, y = 0}) + end + )"; + REQUIRE(fix.engine.loadString(code, "audio_scene.lua")); + auto entity = fix.world.create("Test"); + REQUIRE(fix.engine.callOnCreate("audio_scene.lua", entity)); + REQUIRE(entity.get()->position.x == Approx(111111.0f)); + REQUIRE(fix.engine.sceneRequests().hasPending()); + REQUIRE(fix.engine.sceneRequests().take() == "scenes/level2.scene"); + REQUIRE_FALSE(fix.engine.sceneRequests().hasPending()); + Script::SessionStore::instance().clear(); +} + // ============================================================================ // 11. Math binding — add, sub, dot, scale // ============================================================================ From 178cc103ca0b1eab913927739bf970202ebce433 Mon Sep 17 00:00:00 2001 From: lyeepedro Date: Thu, 19 Nov 2026 18:07:22 +0000 Subject: [PATCH 4/6] Bump caffeine-website (cafpack docs) Co-Authored-By: Claude Sonnet 5.5 --- caffeine-website | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/caffeine-website b/caffeine-website index f13b4a20..b68996fe 160000 --- a/caffeine-website +++ b/caffeine-website @@ -1 +1 @@ -Subproject commit f13b4a20ae90184b3c269f15b2c61915627b4fc1 +Subproject commit b68996fef2a6b3b38cc99cba140502f4f83c81b3 From 28735afe6d2ce32bfd9b7bda339a9907764d0a38 Mon Sep 17 00:00:00 2001 From: lyeepedro Date: Fri, 20 Nov 2026 16:43:26 +0000 Subject: [PATCH 5/6] Doppio: generator recipes, script editor assistance, more Dryad nodes; engine fixes - PIC for static deps so libcaffeine-capi links; capitalised project folders - generator.* recipe files, kept next to baked products - script editor: hover cards that stay under the pointer, Ctrl+click, completions - Dryad: 58 nodes, 20 caffeine_math_* natives (documented, tested) - bump caffeine-website (static site) Co-Authored-By: Claude Sonnet 5.5 --- CMakeLists.txt | 4 + caffeine-website | 2 +- doppio/Cargo.lock | 1 + doppio/crates/ui/Cargo.toml | 2 +- doppio/crates/ui/src/uikit/asset_wizard.rs | 2 +- .../ui/src/uikit/components/code_editor.rs | 29 +- doppio/crates/ui/src/uikit/dryad.rs | 1470 ++++++++++++++++- doppio/crates/ui/src/uikit/mod.rs | 3 + .../ui/src/uikit/panels/assetmanager.rs | 1 + .../crates/ui/src/uikit/panels/dryad_nodes.rs | 40 +- .../ui/src/uikit/panels/project_manager.rs | 12 +- doppio/crates/ui/src/uikit/panels/script.rs | 10 +- doppio/crates/ui/src/uikit/project.rs | 63 +- doppio/crates/ui/src/uikit/recipe.rs | 354 ++++ doppio/crates/ui/src/uikit/script.rs | 486 +++++- doppio/crates/ui/src/uikit/script_assist.rs | 189 +++ .../crates/ui/src/uikit/script_reference.rs | 1271 ++++++++++++++ doppio/crates/ui/src/windows/main.rs | 101 +- .../crates/ui/src/windows/main/naturegen.rs | 34 +- doppio/crates/ui/src/windows/main/recipes.rs | 154 ++ .../crates/ui/src/windows/main/terraingen.rs | 31 +- doppio/crates/ui/src/windows/main/tests.rs | 133 +- .../crates/ui/src/windows/main/texturegen.rs | 28 +- doppio/crates/ui/src/windows/main/watergen.rs | 24 +- doppio/docs/generator-recipes.md | 60 + doppio/docs/rust-ui.md | 45 +- src/caffeine/capi/EngineAPI.cpp | 9 + src/caffeine/script/DryadRuntimeBindings.cpp | 56 + src/caffeine/script/api/math.json | 258 ++- tests/test_dryad_host.cpp | 27 + 30 files changed, 4707 insertions(+), 192 deletions(-) create mode 100644 doppio/crates/ui/src/uikit/recipe.rs create mode 100644 doppio/crates/ui/src/uikit/script_assist.rs create mode 100644 doppio/crates/ui/src/uikit/script_reference.rs create mode 100644 doppio/crates/ui/src/windows/main/recipes.rs create mode 100644 doppio/docs/generator-recipes.md diff --git a/CMakeLists.txt b/CMakeLists.txt index 68159037..af238143 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -2,6 +2,10 @@ cmake_minimum_required(VERSION 3.20) project(Caffeine VERSION 0.1.0 LANGUAGES CXX C) +# Third-party static libs (Bullet, Lua, ...) end up inside libcaffeine-capi.so, so every +# object must be position independent. +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) diff --git a/caffeine-website b/caffeine-website index b68996fe..75fe8fc1 160000 --- a/caffeine-website +++ b/caffeine-website @@ -1 +1 @@ -Subproject commit b68996fef2a6b3b38cc99cba140502f4f83c81b3 +Subproject commit 75fe8fc17e9fd1d897ba73764a836919063ae860 diff --git a/doppio/Cargo.lock b/doppio/Cargo.lock index 9ee18833..cf7da8ed 100644 --- a/doppio/Cargo.lock +++ b/doppio/Cargo.lock @@ -1723,6 +1723,7 @@ dependencies = [ "iced_aw", "iced_font_awesome", "rust-i18n", + "serde_json", "syntect", "unicode-width", "web-time", diff --git a/doppio/crates/ui/Cargo.toml b/doppio/crates/ui/Cargo.toml index b881f57a..83d9d4c7 100644 --- a/doppio/crates/ui/Cargo.toml +++ b/doppio/crates/ui/Cargo.toml @@ -23,7 +23,7 @@ roxmltree = "0.20" serde = { version = "1", features = ["derive"] } serde_json.workspace = true zip = { version = "9.0", default-features = false, features = ["deflate"] } -iced-code-editor = "0.5.3" +iced-code-editor = { version = "0.5.3", features = ["lsp-process"] } iced_test = { workspace = true, optional = true } fontdue = { version = "0.9", optional = true } diff --git a/doppio/crates/ui/src/uikit/asset_wizard.rs b/doppio/crates/ui/src/uikit/asset_wizard.rs index 0af363b4..b2b17218 100644 --- a/doppio/crates/ui/src/uikit/asset_wizard.rs +++ b/doppio/crates/ui/src/uikit/asset_wizard.rs @@ -4,7 +4,7 @@ //! be tested with temp directories and never touches the engine. The wizard //! panel and `App` only translate messages into these calls. //! -//! Raw assets live under the project asset root (`assets/raw`). The engine +//! Raw assets live under the project asset root (`Assets/Raw`). The engine //! recognises them by extension (see `assetKind` in the C ABI); `caf-pack` //! turns that raw tree into the `.cap` archive shipped with a game. diff --git a/doppio/crates/ui/src/uikit/components/code_editor.rs b/doppio/crates/ui/src/uikit/components/code_editor.rs index fadb867b..836ee262 100644 --- a/doppio/crates/ui/src/uikit/components/code_editor.rs +++ b/doppio/crates/ui/src/uikit/components/code_editor.rs @@ -5,8 +5,9 @@ //! pane on a stable component boundary and gives the editor a queryable id. use crate::uikit::theme; -use iced::widget::container; -use iced::{Element, Length}; +use iced::widget::{container, stack}; +use iced::{Element, Length, Theme}; +use std::sync::OnceLock; pub fn view<'a, Message: Clone + 'a>( id: impl Into, @@ -21,3 +22,27 @@ pub fn view<'a, Message: Clone + 'a>( .style(theme::surface) .into() } + +fn overlay_theme() -> &'static Theme { + static THEME: OnceLock = OnceLock::new(); + THEME.get_or_init(|| Theme::Dark) +} + +/// The editor with a floating reference card (hover tooltip) above it. +pub fn view_with_reference<'a, Message: Clone + 'a>( + id: impl Into, + editor: &'a iced_code_editor::CodeEditor, + overlay: &'a iced_code_editor::LspOverlayState, + on_action: impl Fn(iced_code_editor::Message) -> Message + 'a, + on_overlay: impl Fn(iced_code_editor::LspOverlayMessage) -> Message + 'a, +) -> Element<'a, Message> { + let card = iced_code_editor::view_lsp_overlay( + overlay, + editor, + overlay_theme(), + 14.0, + 20.0, + on_overlay, + ); + stack![view(id, editor, on_action), card].into() +} diff --git a/doppio/crates/ui/src/uikit/dryad.rs b/doppio/crates/ui/src/uikit/dryad.rs index 50c67883..5fc2a812 100644 --- a/doppio/crates/ui/src/uikit/dryad.rs +++ b/doppio/crates/ui/src/uikit/dryad.rs @@ -32,11 +32,59 @@ pub enum NodeKind { Log, Constant, Branch, + KeyDown, + ActionDown, + Axis, + TotalTime, + DestroySelf, + Add, + Subtract, + Multiply, + Divide, + Negate, + Less, + Greater, + Equal, + And, + Or, + Not, + SelfEntity, + IsAlive, + Distance, + RandomValue, + RandomRange, + RandomInt, + RandomChance, + MouseX, + MouseY, + MouseDeltaX, + MouseDeltaY, + MouseDown, + FixedDelta, + FrameCount, + Min, + Max, + Abs, + Floor, + Ceil, + Round, + Sqrt, + Pow, + Sin, + Cos, + Radians, + Degrees, + Sign, + Clamp, + Clamp01, + Lerp, + InverseLerp, + Smoothstep, } impl NodeKind { /// Every kind, in catalog order. - pub const ALL: [NodeKind; 10] = [ + pub const ALL: [NodeKind; 58] = [ NodeKind::Constant, NodeKind::Branch, NodeKind::OnUpdate, @@ -47,6 +95,54 @@ impl NodeKind { NodeKind::GetScale, NodeKind::DeltaTime, NodeKind::Log, + NodeKind::KeyDown, + NodeKind::ActionDown, + NodeKind::Axis, + NodeKind::TotalTime, + NodeKind::DestroySelf, + NodeKind::Add, + NodeKind::Subtract, + NodeKind::Multiply, + NodeKind::Divide, + NodeKind::Negate, + NodeKind::Less, + NodeKind::Greater, + NodeKind::Equal, + NodeKind::And, + NodeKind::Or, + NodeKind::Not, + NodeKind::SelfEntity, + NodeKind::IsAlive, + NodeKind::Distance, + NodeKind::RandomValue, + NodeKind::RandomRange, + NodeKind::RandomInt, + NodeKind::RandomChance, + NodeKind::MouseX, + NodeKind::MouseY, + NodeKind::MouseDeltaX, + NodeKind::MouseDeltaY, + NodeKind::MouseDown, + NodeKind::FixedDelta, + NodeKind::FrameCount, + NodeKind::Min, + NodeKind::Max, + NodeKind::Abs, + NodeKind::Floor, + NodeKind::Ceil, + NodeKind::Round, + NodeKind::Sqrt, + NodeKind::Pow, + NodeKind::Sin, + NodeKind::Cos, + NodeKind::Radians, + NodeKind::Degrees, + NodeKind::Sign, + NodeKind::Clamp, + NodeKind::Clamp01, + NodeKind::Lerp, + NodeKind::InverseLerp, + NodeKind::Smoothstep, ]; /// The `type` field written to `.node.json` (`"OnUpdate"`, `"Branch"`…). @@ -62,6 +158,26 @@ impl NodeKind { NodeKind::Log => "Log", NodeKind::Constant => "Constant", NodeKind::Branch => "Branch", + NodeKind::KeyDown => "KeyDown", + NodeKind::ActionDown => "ActionDown", + NodeKind::Axis => "Axis", + NodeKind::TotalTime => "TotalTime", + NodeKind::DestroySelf => "DestroySelf", + NodeKind::Add => "Add", + NodeKind::Subtract => "Subtract", + NodeKind::Multiply => "Multiply", + NodeKind::Divide => "Divide", + NodeKind::Negate => "Negate", + NodeKind::Less => "Less", + NodeKind::Greater => "Greater", + NodeKind::Equal => "Equal", + NodeKind::And => "And", + NodeKind::Or => "Or", + NodeKind::Not => "Not", + NodeKind::SelfEntity => "SelfEntity", + NodeKind::IsAlive => "IsAlive", + NodeKind::Distance => "Distance", + other => native_row(other).map_or("", |row| row.type_name), } } @@ -78,6 +194,12 @@ impl NodeKind { NodeKind::Log => "Log", NodeKind::Constant => "Constant", NodeKind::Branch => "If / Else", + NodeKind::KeyDown => "Key Down", + NodeKind::ActionDown => "Action Down", + NodeKind::Axis => "Input Axis", + NodeKind::TotalTime => "Total Time", + NodeKind::DestroySelf => "Destroy Self", + other => extra(other).1, } } @@ -94,6 +216,10 @@ impl NodeKind { | NodeKind::GetScale => "Engine / Transform", NodeKind::DeltaTime => "Engine / Time", NodeKind::Log => "Engine / Debug", + NodeKind::KeyDown | NodeKind::ActionDown | NodeKind::Axis => "Engine / Input", + NodeKind::TotalTime => "Engine / Time", + NodeKind::DestroySelf => "Engine / World", + other => extra(other).2, } } @@ -111,6 +237,12 @@ impl NodeKind { NodeKind::GetScale => "Read the entity scale.", NodeKind::DeltaTime => "Seconds elapsed since the previous frame.", NodeKind::Log => "Write a message to the Doppio console.", + NodeKind::KeyDown => "True while the named key is held (Space, W, LShift...).", + NodeKind::ActionDown => "True while the named action is held (Jump, Attack...).", + NodeKind::Axis => "Input axis in -1..1 (Horizontal, Vertical, LookX, LookY).", + NodeKind::TotalTime => "Scaled seconds since play started.", + NodeKind::DestroySelf => "Destroy the entity that runs this script.", + other => extra(other).3, } } @@ -127,6 +259,12 @@ impl NodeKind { NodeKind::Log => "console message", NodeKind::DeltaTime => "frame delta", NodeKind::Constant => "fixed value", + NodeKind::KeyDown => "keyboard", + NodeKind::ActionDown => "input action", + NodeKind::Axis => "input axis", + NodeKind::TotalTime => "time since play", + NodeKind::DestroySelf => "removes the entity", + other => extra(other).4, } } @@ -140,13 +278,538 @@ impl NodeKind { /// `true` for nodes that only produce data and have no exec pins. pub fn is_data_only(self) -> bool { - matches!( - self, - NodeKind::GetPosition | NodeKind::GetScale | NodeKind::DeltaTime | NodeKind::Constant - ) + self.call_native().is_some() + || matches!( + self, + NodeKind::GetPosition + | NodeKind::GetScale + | NodeKind::DeltaTime + | NodeKind::Constant + | NodeKind::KeyDown + | NodeKind::ActionDown + | NodeKind::Axis + | NodeKind::TotalTime + | NodeKind::Add + | NodeKind::Subtract + | NodeKind::Multiply + | NodeKind::Divide + | NodeKind::Negate + | NodeKind::Less + | NodeKind::Greater + | NodeKind::Equal + | NodeKind::And + | NodeKind::Or + | NodeKind::Not + | NodeKind::SelfEntity + | NodeKind::IsAlive + | NodeKind::Distance + ) + } + + /// Infix or prefix operator emitted for a math, compare or logic node. + pub fn operator(self) -> Option { + let (symbol, unary, input, output) = match self { + NodeKind::Add => ("+", false, PinKind::Number, PinKind::Number), + NodeKind::Subtract => ("-", false, PinKind::Number, PinKind::Number), + NodeKind::Multiply => ("*", false, PinKind::Number, PinKind::Number), + NodeKind::Divide => ("/", false, PinKind::Number, PinKind::Number), + NodeKind::Negate => ("-", true, PinKind::Number, PinKind::Number), + NodeKind::Less => ("<", false, PinKind::Number, PinKind::Bool), + NodeKind::Greater => (">", false, PinKind::Number, PinKind::Bool), + NodeKind::Equal => ("==", false, PinKind::Number, PinKind::Bool), + NodeKind::And => ("&&", false, PinKind::Bool, PinKind::Bool), + NodeKind::Or => ("||", false, PinKind::Bool, PinKind::Bool), + NodeKind::Not => ("!", true, PinKind::Bool, PinKind::Bool), + _ => return None, + }; + Some(Operator { + symbol, + unary, + input, + output, + }) + } + + /// Native called by a node that wraps one engine function, with its argument count. + pub fn call_native(self) -> Option<(&'static str, usize)> { + match self { + NodeKind::IsAlive => Some(("caffeine_world_is_alive", 1)), + NodeKind::Distance => Some(("caffeine_world_distance", 2)), + other => native_row(other).map(|row| (row.native, row.arity)), + } } } +/// A data node that wraps one engine native taking up to three number inputs `a`, `b`, `c`. +#[derive(Debug, Clone, Copy)] +struct NativeNode { + kind: NodeKind, + type_name: &'static str, + display_name: &'static str, + category: &'static str, + description: &'static str, + subtitle: &'static str, + native: &'static str, + arity: usize, + boolean: bool, +} + +fn native_row(kind: NodeKind) -> Option<&'static NativeNode> { + NATIVE_NODES.iter().find(|row| row.kind == kind) +} + +const NATIVE_NODES: [NativeNode; 29] = [ + NativeNode { + kind: NodeKind::RandomValue, + type_name: "RandomValue", + display_name: "Random Value", + category: "Engine / Random", + description: "A random number from 0 up to 1.", + subtitle: "random 0..1", + native: "caffeine_random_value", + arity: 0, + boolean: false, + }, + NativeNode { + kind: NodeKind::RandomRange, + type_name: "RandomRange", + display_name: "Random Range", + category: "Engine / Random", + description: "A random number between a and b.", + subtitle: "between a and b", + native: "caffeine_random_range", + arity: 2, + boolean: false, + }, + NativeNode { + kind: NodeKind::RandomInt, + type_name: "RandomInt", + display_name: "Random Int", + category: "Engine / Random", + description: "A random whole number between a and b, both included.", + subtitle: "whole number", + native: "caffeine_random_int", + arity: 2, + boolean: false, + }, + NativeNode { + kind: NodeKind::RandomChance, + type_name: "RandomChance", + display_name: "Random Chance", + category: "Engine / Random", + description: "True with the probability a (0 never, 1 always).", + subtitle: "coin flip", + native: "caffeine_random_chance", + arity: 1, + boolean: true, + }, + NativeNode { + kind: NodeKind::MouseX, + type_name: "MouseX", + display_name: "Mouse X", + category: "Engine / Input", + description: "Mouse horizontal position in pixels.", + subtitle: "pointer x", + native: "caffeine_input_mouse_x", + arity: 0, + boolean: false, + }, + NativeNode { + kind: NodeKind::MouseY, + type_name: "MouseY", + display_name: "Mouse Y", + category: "Engine / Input", + description: "Mouse vertical position in pixels.", + subtitle: "pointer y", + native: "caffeine_input_mouse_y", + arity: 0, + boolean: false, + }, + NativeNode { + kind: NodeKind::MouseDeltaX, + type_name: "MouseDeltaX", + display_name: "Mouse Delta X", + category: "Engine / Input", + description: "Horizontal mouse movement since the previous frame.", + subtitle: "pointer dx", + native: "caffeine_input_mouse_dx", + arity: 0, + boolean: false, + }, + NativeNode { + kind: NodeKind::MouseDeltaY, + type_name: "MouseDeltaY", + display_name: "Mouse Delta Y", + category: "Engine / Input", + description: "Vertical mouse movement since the previous frame.", + subtitle: "pointer dy", + native: "caffeine_input_mouse_dy", + arity: 0, + boolean: false, + }, + NativeNode { + kind: NodeKind::MouseDown, + type_name: "MouseDown", + display_name: "Mouse Button", + category: "Engine / Input", + description: "True while the mouse button a is held (1 left, 2 middle, 3 right).", + subtitle: "mouse button", + native: "caffeine_input_mouse_down", + arity: 1, + boolean: true, + }, + NativeNode { + kind: NodeKind::FixedDelta, + type_name: "FixedDelta", + display_name: "Fixed Delta", + category: "Engine / Time", + description: "The fixed simulation step in seconds.", + subtitle: "fixed step", + native: "caffeine_time_fixed_delta", + arity: 0, + boolean: false, + }, + NativeNode { + kind: NodeKind::FrameCount, + type_name: "FrameCount", + display_name: "Frame Count", + category: "Engine / Time", + description: "Frames elapsed since play started.", + subtitle: "frame number", + native: "caffeine_time_frame", + arity: 0, + boolean: false, + }, + NativeNode { + kind: NodeKind::Min, + type_name: "Min", + display_name: "Min", + category: "Language / Math", + description: "The smaller of a and b.", + subtitle: "smaller", + native: "caffeine_math_min", + arity: 2, + boolean: false, + }, + NativeNode { + kind: NodeKind::Max, + type_name: "Max", + display_name: "Max", + category: "Language / Math", + description: "The larger of a and b.", + subtitle: "larger", + native: "caffeine_math_max", + arity: 2, + boolean: false, + }, + NativeNode { + kind: NodeKind::Abs, + type_name: "Abs", + display_name: "Abs", + category: "Language / Math", + description: "Absolute value of a.", + subtitle: "absolute", + native: "caffeine_math_abs", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Floor, + type_name: "Floor", + display_name: "Floor", + category: "Language / Math", + description: "Rounds a down to a whole number.", + subtitle: "round down", + native: "caffeine_math_floor", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Ceil, + type_name: "Ceil", + display_name: "Ceil", + category: "Language / Math", + description: "Rounds a up to a whole number.", + subtitle: "round up", + native: "caffeine_math_ceil", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Round, + type_name: "Round", + display_name: "Round", + category: "Language / Math", + description: "Rounds a to the nearest whole number.", + subtitle: "nearest", + native: "caffeine_math_round", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Sqrt, + type_name: "Sqrt", + display_name: "Square Root", + category: "Language / Math", + description: "Square root of a; negative input gives 0.", + subtitle: "square root", + native: "caffeine_math_sqrt", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Pow, + type_name: "Pow", + display_name: "Power", + category: "Language / Math", + description: "a raised to the power b.", + subtitle: "a to the b", + native: "caffeine_math_pow", + arity: 2, + boolean: false, + }, + NativeNode { + kind: NodeKind::Sin, + type_name: "Sin", + display_name: "Sine", + category: "Language / Trigonometry", + description: "Sine of an angle a in radians.", + subtitle: "radians", + native: "caffeine_math_sin", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Cos, + type_name: "Cos", + display_name: "Cosine", + category: "Language / Trigonometry", + description: "Cosine of an angle a in radians.", + subtitle: "radians", + native: "caffeine_math_cos", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Radians, + type_name: "Radians", + display_name: "Degrees to Radians", + category: "Language / Trigonometry", + description: "Converts degrees a to radians.", + subtitle: "deg to rad", + native: "caffeine_math_radians", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Degrees, + type_name: "Degrees", + display_name: "Radians to Degrees", + category: "Language / Trigonometry", + description: "Converts radians a to degrees.", + subtitle: "rad to deg", + native: "caffeine_math_degrees", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Sign, + type_name: "Sign", + display_name: "Sign", + category: "Language / Math", + description: "-1, 0 or 1 by the sign of a.", + subtitle: "sign", + native: "caffeine_math_sign", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Clamp, + type_name: "Clamp", + display_name: "Clamp", + category: "Language / Math", + description: "Limits a to the range b..c.", + subtitle: "limit range", + native: "caffeine_math_clamp", + arity: 3, + boolean: false, + }, + NativeNode { + kind: NodeKind::Clamp01, + type_name: "Clamp01", + display_name: "Clamp 0..1", + category: "Language / Math", + description: "Limits a to 0..1.", + subtitle: "limit 0..1", + native: "caffeine_math_clamp01", + arity: 1, + boolean: false, + }, + NativeNode { + kind: NodeKind::Lerp, + type_name: "Lerp", + display_name: "Lerp", + category: "Language / Math", + description: "Blend from a to b by the factor c.", + subtitle: "blend", + native: "caffeine_math_lerp", + arity: 3, + boolean: false, + }, + NativeNode { + kind: NodeKind::InverseLerp, + type_name: "InverseLerp", + display_name: "Inverse Lerp", + category: "Language / Math", + description: "Where c sits between a and b (0 at a, 1 at b).", + subtitle: "position in range", + native: "caffeine_math_inverse_lerp", + arity: 3, + boolean: false, + }, + NativeNode { + kind: NodeKind::Smoothstep, + type_name: "Smoothstep", + display_name: "Smoothstep", + category: "Language / Math", + description: "Smooth 0..1 ramp of c between the edges a and b.", + subtitle: "smooth ramp", + native: "caffeine_math_smoothstep", + arity: 3, + boolean: false, + }, +]; + +/// How an operator node is written in Dryad source. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Operator { + pub symbol: &'static str, + pub unary: bool, + pub input: PinKind, + pub output: PinKind, +} + +/// `(type, display, category, description, subtitle)` of the nodes added after the first ten. +fn extra( + kind: NodeKind, +) -> ( + &'static str, + &'static str, + &'static str, + &'static str, + &'static str, +) { + if let Some(row) = native_row(kind) { + return ( + row.type_name, + row.display_name, + row.category, + row.description, + row.subtitle, + ); + } + EXTRA + .iter() + .copied() + .find(|row| row.0 == kind.type_name()) + .unwrap_or(("", "", "", "", "")) +} + +const EXTRA: [(&str, &str, &str, &str, &str); 14] = [ + ("Add", "Add", "Language / Math", "a + b", "add"), + ( + "Subtract", + "Subtract", + "Language / Math", + "a - b", + "subtract", + ), + ( + "Multiply", + "Multiply", + "Language / Math", + "a * b", + "multiply", + ), + ( + "Divide", + "Divide", + "Language / Math", + "a / b. Dividing by zero gives an error value, guard it with a Compare.", + "divide", + ), + ( + "Negate", + "Negate", + "Language / Math", + "The value with its sign flipped.", + "-a", + ), + ( + "Less", + "Less Than", + "Language / Compare", + "True when a is smaller than b.", + "a < b", + ), + ( + "Greater", + "Greater Than", + "Language / Compare", + "True when a is larger than b.", + "a > b", + ), + ( + "Equal", + "Equal", + "Language / Compare", + "True when a and b are the same value.", + "a == b", + ), + ( + "And", + "And", + "Language / Logic", + "True when both inputs are true.", + "a and b", + ), + ( + "Or", + "Or", + "Language / Logic", + "True when at least one input is true.", + "a or b", + ), + ( + "Not", + "Not", + "Language / Logic", + "The opposite of the input.", + "not a", + ), + ( + "SelfEntity", + "This Entity", + "Engine / World", + "The id of the entity that runs this script.", + "entity id", + ), + ( + "IsAlive", + "Is Alive", + "Engine / World", + "True while the entity with this id still exists.", + "entity exists", + ), + ( + "Distance", + "Distance", + "Engine / World", + "World distance between two entities.", + "between entities", + ), +]; + /// One catalog row shared by the palette, the canvas and the emitter. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CatalogEntry { @@ -159,10 +822,21 @@ pub struct CatalogEntry { /// The catalog. It is static so the palette, tests and agents share one list. pub fn catalog() -> &'static [CatalogEntry] { - &CATALOG + static ALL_ENTRIES: std::sync::OnceLock> = std::sync::OnceLock::new(); + ALL_ENTRIES.get_or_init(|| { + let mut entries = CATALOG.to_vec(); + entries.extend(NATIVE_NODES.iter().map(|row| CatalogEntry { + kind: row.kind, + type_name: row.type_name, + display_name: row.display_name, + category: row.category, + description: row.description, + })); + entries + }) } -const CATALOG: [CatalogEntry; 10] = [ +const CATALOG: [CatalogEntry; 29] = [ CatalogEntry { kind: NodeKind::Constant, type_name: "Constant", @@ -233,6 +907,139 @@ const CATALOG: [CatalogEntry; 10] = [ category: "Engine / Debug", description: "Write a message to the Doppio console.", }, + CatalogEntry { + kind: NodeKind::KeyDown, + type_name: "KeyDown", + display_name: "Key Down", + category: "Engine / Input", + description: "True while the named key is held (Space, W, LShift...).", + }, + CatalogEntry { + kind: NodeKind::ActionDown, + type_name: "ActionDown", + display_name: "Action Down", + category: "Engine / Input", + description: "True while the named action is held (Jump, Attack...).", + }, + CatalogEntry { + kind: NodeKind::Axis, + type_name: "Axis", + display_name: "Input Axis", + category: "Engine / Input", + description: "Input axis in -1..1 (Horizontal, Vertical, LookX, LookY).", + }, + CatalogEntry { + kind: NodeKind::TotalTime, + type_name: "TotalTime", + display_name: "Total Time", + category: "Engine / Time", + description: "Scaled seconds since play started.", + }, + CatalogEntry { + kind: NodeKind::DestroySelf, + type_name: "DestroySelf", + display_name: "Destroy Self", + category: "Engine / World", + description: "Destroy the entity that runs this script.", + }, + CatalogEntry { + kind: NodeKind::Add, + type_name: "Add", + display_name: "Add", + category: "Language / Math", + description: "a + b", + }, + CatalogEntry { + kind: NodeKind::Subtract, + type_name: "Subtract", + display_name: "Subtract", + category: "Language / Math", + description: "a - b", + }, + CatalogEntry { + kind: NodeKind::Multiply, + type_name: "Multiply", + display_name: "Multiply", + category: "Language / Math", + description: "a * b", + }, + CatalogEntry { + kind: NodeKind::Divide, + type_name: "Divide", + display_name: "Divide", + category: "Language / Math", + description: "a / b. Dividing by zero gives an error value, guard it with a Compare.", + }, + CatalogEntry { + kind: NodeKind::Negate, + type_name: "Negate", + display_name: "Negate", + category: "Language / Math", + description: "The value with its sign flipped.", + }, + CatalogEntry { + kind: NodeKind::Less, + type_name: "Less", + display_name: "Less Than", + category: "Language / Compare", + description: "True when a is smaller than b.", + }, + CatalogEntry { + kind: NodeKind::Greater, + type_name: "Greater", + display_name: "Greater Than", + category: "Language / Compare", + description: "True when a is larger than b.", + }, + CatalogEntry { + kind: NodeKind::Equal, + type_name: "Equal", + display_name: "Equal", + category: "Language / Compare", + description: "True when a and b are the same value.", + }, + CatalogEntry { + kind: NodeKind::And, + type_name: "And", + display_name: "And", + category: "Language / Logic", + description: "True when both inputs are true.", + }, + CatalogEntry { + kind: NodeKind::Or, + type_name: "Or", + display_name: "Or", + category: "Language / Logic", + description: "True when at least one input is true.", + }, + CatalogEntry { + kind: NodeKind::Not, + type_name: "Not", + display_name: "Not", + category: "Language / Logic", + description: "The opposite of the input.", + }, + CatalogEntry { + kind: NodeKind::SelfEntity, + type_name: "SelfEntity", + display_name: "This Entity", + category: "Engine / World", + description: "The id of the entity that runs this script.", + }, + CatalogEntry { + kind: NodeKind::IsAlive, + type_name: "IsAlive", + display_name: "Is Alive", + category: "Engine / World", + description: "True while the entity with this id still exists.", + }, + CatalogEntry { + kind: NodeKind::Distance, + type_name: "Distance", + display_name: "Distance", + category: "Engine / World", + description: "World distance between two entities.", + }, ]; /// Look up a catalog entry by `type` name. @@ -310,6 +1117,62 @@ const VALUE_OUTPUT: [PinDef; 1] = [PinDef { label: "value", kind: PinKind::Number, }]; +const BOOL_VALUE_OUTPUT: [PinDef; 1] = [PinDef { + name: "value", + label: "value", + kind: PinKind::Bool, +}]; +const NUMBER_AB: [PinDef; 2] = [ + PinDef { + name: "a", + label: "a", + kind: PinKind::Number, + }, + PinDef { + name: "b", + label: "b", + kind: PinKind::Number, + }, +]; +const NUMBER_ABC: [PinDef; 3] = [ + PinDef { + name: "a", + label: "a", + kind: PinKind::Number, + }, + PinDef { + name: "b", + label: "b", + kind: PinKind::Number, + }, + PinDef { + name: "c", + label: "c", + kind: PinKind::Number, + }, +]; +const NUMBER_A: [PinDef; 1] = [PinDef { + name: "a", + label: "a", + kind: PinKind::Number, +}]; +const BOOL_AB: [PinDef; 2] = [ + PinDef { + name: "a", + label: "a", + kind: PinKind::Bool, + }, + PinDef { + name: "b", + label: "b", + kind: PinKind::Bool, + }, +]; +const BOOL_A: [PinDef; 1] = [PinDef { + name: "a", + label: "a", + kind: PinKind::Bool, +}]; const LOG_INPUTS: [PinDef; 1] = [EXEC_IN]; const BRANCH_INPUTS: [PinDef; 2] = [ EXEC_IN, @@ -335,28 +1198,82 @@ const BRANCH_OUTPUTS: [PinDef; 3] = [ /// Input pins for a kind, in canvas order. pub fn inputs(kind: NodeKind) -> &'static [PinDef] { + if let Some(row) = native_row(kind) { + return match row.arity { + 0 => &[], + 1 => &NUMBER_A, + 2 => &NUMBER_AB, + _ => &NUMBER_ABC, + }; + } match kind { NodeKind::SetPosition | NodeKind::Translate | NodeKind::SetScale => &VECTOR_INPUTS, - NodeKind::Log => &LOG_INPUTS, + NodeKind::Log | NodeKind::DestroySelf => &LOG_INPUTS, NodeKind::Branch => &BRANCH_INPUTS, - NodeKind::OnUpdate + NodeKind::Add + | NodeKind::Subtract + | NodeKind::Multiply + | NodeKind::Divide + | NodeKind::Less + | NodeKind::Greater + | NodeKind::Equal + | NodeKind::Distance => &NUMBER_AB, + NodeKind::Negate | NodeKind::IsAlive => &NUMBER_A, + NodeKind::And | NodeKind::Or => &BOOL_AB, + NodeKind::Not => &BOOL_A, + NodeKind::SelfEntity + | NodeKind::OnUpdate | NodeKind::GetPosition | NodeKind::DeltaTime | NodeKind::GetScale - | NodeKind::Constant => &[], + | NodeKind::Constant + | NodeKind::KeyDown + | NodeKind::ActionDown + | NodeKind::Axis + | NodeKind::TotalTime => &[], + // Native-call nodes returned above. + _ => &[], } } /// Output pins for a kind. `Constant` always reports a number here; the /// canvas and connection checks use [`outputs_for`] to honour `bool`. pub fn outputs(kind: NodeKind) -> &'static [PinDef] { + if let Some(row) = native_row(kind) { + return if row.boolean { + &BOOL_VALUE_OUTPUT + } else { + &VALUE_OUTPUT + }; + } match kind { NodeKind::OnUpdate => std::slice::from_ref(&EXEC_OUT), NodeKind::SetPosition | NodeKind::Translate | NodeKind::SetScale => &VECTOR_OUTPUTS, NodeKind::GetPosition | NodeKind::GetScale => &VECTOR_DATA_OUTPUTS, - NodeKind::DeltaTime | NodeKind::Constant => &VALUE_OUTPUT, - NodeKind::Log => std::slice::from_ref(&EXEC_OUT), + NodeKind::DeltaTime + | NodeKind::Constant + | NodeKind::Axis + | NodeKind::TotalTime + | NodeKind::Add + | NodeKind::Subtract + | NodeKind::Multiply + | NodeKind::Divide + | NodeKind::Negate + | NodeKind::SelfEntity + | NodeKind::Distance => &VALUE_OUTPUT, + NodeKind::KeyDown + | NodeKind::ActionDown + | NodeKind::Less + | NodeKind::Greater + | NodeKind::Equal + | NodeKind::And + | NodeKind::Or + | NodeKind::Not + | NodeKind::IsAlive => &BOOL_VALUE_OUTPUT, + NodeKind::Log | NodeKind::DestroySelf => std::slice::from_ref(&EXEC_OUT), NodeKind::Branch => &BRANCH_OUTPUTS, + // Native-call nodes returned above. + _ => &[], } } @@ -406,7 +1323,13 @@ impl GraphNode { input_y: 0.0, input_z: 0.0, input_condition: false, - text_value: "Hello from Dryad".to_owned(), + text_value: match kind { + NodeKind::KeyDown => "Space", + NodeKind::ActionDown => "Jump", + NodeKind::Axis => "Horizontal", + _ => "Hello from Dryad", + } + .to_owned(), } } @@ -865,6 +1788,16 @@ impl<'a> Emitter<'a> { } Ok(()) } + NodeKind::DestroySelf => { + Self::line(out, depth, &format!("// @node {}", node.id)); + Self::line(out, depth, "caffeine_world_destroy(entity);"); + if let Some(next) = self.exec_edge_from(&node.id, "out") { + let (next_id, _) = parse_pin_ref(&next.to) + .ok_or_else(|| "invalid exec edge from DestroySelf".to_owned())?; + self.emit_exec_chain(next_id, out, depth)?; + } + Ok(()) + } NodeKind::Log => { Self::line(out, depth, &format!("// @node {}", node.id)); Self::line( @@ -906,7 +1839,26 @@ impl<'a> Emitter<'a> { NodeKind::GetPosition | NodeKind::GetScale | NodeKind::DeltaTime + | NodeKind::KeyDown + | NodeKind::ActionDown + | NodeKind::Axis + | NodeKind::TotalTime + | NodeKind::Add + | NodeKind::Subtract + | NodeKind::Multiply + | NodeKind::Divide + | NodeKind::Negate + | NodeKind::Less + | NodeKind::Greater + | NodeKind::Equal + | NodeKind::And + | NodeKind::Or + | NodeKind::Not + | NodeKind::SelfEntity + | NodeKind::IsAlive + | NodeKind::Distance | NodeKind::Constant => Err(format!("data-only node in exec chain: {node_id}")), + _ => Err(format!("data-only node in exec chain: {node_id}")), } } @@ -917,6 +1869,13 @@ impl<'a> Emitter<'a> { return self.resolve_data_output(source_node, source_pin); } if let Some(node) = self.graph.find_node(node_id) { + if node + .kind + .operator() + .is_some_and(|op| op.input == PinKind::Bool) + { + return Ok("false".to_owned()); + } match pin { "x" => return Ok(format_number(node.input_x)), "y" => return Ok(format_number(node.input_y)), @@ -965,6 +1924,26 @@ impl<'a> Emitter<'a> { } "dt".to_owned() } + NodeKind::KeyDown | NodeKind::ActionDown | NodeKind::Axis => { + if pin != "value" { + return Err(format!( + "{} only exposes pin 'value'", + node.kind.type_name() + )); + } + let native = match node.kind { + NodeKind::KeyDown => "caffeine_input_key_down", + NodeKind::ActionDown => "caffeine_input_action_down", + _ => "caffeine_input_axis", + }; + format!("{native}(\"{}\")", json_escape(&node.text_value)) + } + NodeKind::TotalTime => { + if pin != "value" { + return Err("TotalTime only exposes pin 'value'".to_owned()); + } + "caffeine_time_total()".to_owned() + } NodeKind::GetPosition => match pin { "x" => "caffeine_get_position_x(entity)".to_owned(), "y" => "caffeine_get_position_y(entity)".to_owned(), @@ -977,6 +1956,29 @@ impl<'a> Emitter<'a> { "z" => "caffeine_get_scale_z(entity)".to_owned(), _ => return Err("GetScale exposes x, y, z pins".to_owned()), }, + NodeKind::SelfEntity => "entity".to_owned(), + kind if kind.operator().is_some() => { + let Some(op) = kind.operator() else { + return Err(format!("node {node_id} is not an operator")); + }; + let a = self.resolve_data_input(node_id, "a")?; + if op.unary { + format!("({}{a})", op.symbol) + } else { + let b = self.resolve_data_input(node_id, "b")?; + format!("({a} {} {b})", op.symbol) + } + } + kind if kind.call_native().is_some() => { + let Some((native, arity)) = kind.call_native() else { + return Err(format!("node {node_id} is not a call")); + }; + let mut arguments = Vec::new(); + for pin in ["a", "b", "c"].into_iter().take(arity) { + arguments.push(self.resolve_data_input(node_id, pin)?); + } + format!("{native}({})", arguments.join(", ")) + } _ => return Err(format!("node {node_id} is not a data source")), }; self.cache.insert(key, expression.clone()); @@ -984,6 +1986,140 @@ impl<'a> Emitter<'a> { } } +/// Split `(a + b)`, `(!a)` or `caffeine_world_distance(a, b)` into a node kind and its operand +/// expressions. The emitter parenthesises every operator, so each has exactly one at depth 0. +fn parse_operator_expression(expression: &str) -> Option<(NodeKind, Vec)> { + let expression = expression.trim(); + for kind in NodeKind::ALL { + let Some((native, arity)) = kind.call_native() else { + continue; + }; + let Some(rest) = expression + .strip_prefix(native) + .and_then(|rest| rest.strip_prefix('(')) + else { + continue; + }; + let inner = rest.strip_suffix(')')?; + let parts = if inner.trim().is_empty() { + Vec::new() + } else { + split_top_level(inner, ',') + }; + return (parts.len() == arity).then_some((kind, parts)); + } + let inner = expression.strip_prefix('(')?.strip_suffix(')')?; + // The leading `(` must close at the very end, not earlier (`(a) + (b)`). + let mut depth = 0i32; + for (index, character) in expression.char_indices() { + match character { + '(' => depth += 1, + ')' => { + depth -= 1; + if depth == 0 && index + 1 != expression.len() { + return None; + } + } + _ => {} + } + } + let inner = inner.trim(); + if let Some(operand) = inner.strip_prefix('!') { + return Some((NodeKind::Not, vec![operand.trim().to_owned()])); + } + if let Some(operand) = inner.strip_prefix('-') { + // `-5` is a constant; only `-` before an expression is a Negate node. + if operand.trim_start().starts_with(['(', '_']) + || operand.trim_start().starts_with(char::is_alphabetic) + { + return Some((NodeKind::Negate, vec![operand.trim().to_owned()])); + } + } + for (symbol, kind) in [ + (" && ", NodeKind::And), + (" || ", NodeKind::Or), + (" == ", NodeKind::Equal), + (" < ", NodeKind::Less), + (" > ", NodeKind::Greater), + (" + ", NodeKind::Add), + (" - ", NodeKind::Subtract), + (" * ", NodeKind::Multiply), + (" / ", NodeKind::Divide), + ] { + let parts = split_top_level(inner, symbol); + if parts.len() == 2 { + return Some((kind, parts)); + } + } + None +} + +/// Split `text` at the separator where it appears outside parentheses and quotes. +fn split_top_level(text: &str, separator: P) -> Vec { + let mut parts = Vec::new(); + let mut depth = 0i32; + let mut quoted = false; + let mut start = 0usize; + let mut index = 0usize; + while index < text.len() { + let rest = &text[index..]; + let character = rest.chars().next().unwrap_or(' '); + match character { + '"' => quoted = !quoted, + '(' if !quoted => depth += 1, + ')' if !quoted => depth -= 1, + _ => {} + } + if depth == 0 && !quoted { + if let Some(width) = separator.matches_at(rest) { + parts.push(text[start..index].trim().to_owned()); + index += width; + start = index; + continue; + } + } + index += character.len_utf8(); + } + parts.push(text[start..].trim().to_owned()); + parts +} + +trait SplitPattern { + fn matches_at(&self, rest: &str) -> Option; +} + +impl SplitPattern for char { + fn matches_at(&self, rest: &str) -> Option { + rest.starts_with(*self).then(|| self.len_utf8()) + } +} + +impl SplitPattern for &str { + fn matches_at(&self, rest: &str) -> Option { + rest.starts_with(*self).then_some(self.len()) + } +} + +/// Recognise `caffeine_input_key_down("Space")` style calls and return the node kind +/// plus the quoted name. +fn input_call(expression: &str) -> Option<(NodeKind, String)> { + for (native, kind) in [ + ("caffeine_input_key_down", NodeKind::KeyDown), + ("caffeine_input_action_down", NodeKind::ActionDown), + ("caffeine_input_axis", NodeKind::Axis), + ] { + let Some(rest) = expression.strip_prefix(native) else { + continue; + }; + let inner = rest.strip_prefix("(\"")?.strip_suffix("\")")?; + if inner.contains('"') { + return None; + } + return Some((kind, inner.replace("\\\\", "\\"))); + } + None +} + fn json_escape(text: &str) -> String { let mut out = String::with_capacity(text.len() + 8); for character in text.chars() { @@ -1056,7 +2192,10 @@ fn serialize_json(graph: &Graph) -> String { } )); } - if node.kind == NodeKind::Log { + if matches!( + node.kind, + NodeKind::Log | NodeKind::KeyDown | NodeKind::ActionDown | NodeKind::Axis + ) { json.push_str(&format!( ", \"text\": \"{}\"", json_escape(&node.text_value) @@ -1147,7 +2286,10 @@ fn parse_json(source: &str) -> Result { node.number_value = number; } } - if kind == NodeKind::Log { + if matches!( + kind, + NodeKind::Log | NodeKind::KeyDown | NodeKind::ActionDown | NodeKind::Axis + ) { if let Some(text) = entry.get("text").and_then(|text| text.as_str()) { node.text_value = text.to_owned(); } @@ -1402,6 +2544,8 @@ impl<'a> DydImporter<'a> { exec_out = self.parse_vector_call(&node_id, NodeKind::Translate, &exec_out)?; } else if self.consume("caffeine_set_scale") { exec_out = self.parse_vector_call(&node_id, NodeKind::SetScale, &exec_out)?; + } else if self.consume("caffeine_world_destroy") { + exec_out = self.parse_destroy(&node_id, &exec_out)?; } else if self.consume("caffeine_log") { exec_out = self.parse_log(&node_id, &exec_out)?; } else if self.consume("if") { @@ -1450,6 +2594,20 @@ impl<'a> DydImporter<'a> { Ok(format!("{node_id}.out")) } + fn parse_destroy(&mut self, node_id: &str, exec_out: &str) -> Result { + self.ensure_node(node_id, NodeKind::DestroySelf); + if exec_out.is_empty() { + return Err("DestroySelf without exec input".to_owned()); + } + self.add_edge(exec_out.to_owned(), format!("{node_id}.in")); + for expected in ["(", "entity", ")", ";"] { + if !self.consume(expected) { + return Err(format!("expected {expected} after caffeine_world_destroy")); + } + } + Ok(format!("{node_id}.out")) + } + fn parse_log(&mut self, node_id: &str, exec_out: &str) -> Result { self.ensure_node(node_id, NodeKind::Log); if exec_out.is_empty() { @@ -1625,6 +2783,24 @@ impl<'a> DydImporter<'a> { self.add_edge(format!("{source}.{pin_name}"), format!("{to_node}.{pin}")); return Ok(()); } + if expression == "entity" { + let id = format!("import_self{}", self.serial); + self.serial += 1; + self.ensure_node(&id, NodeKind::SelfEntity); + self.add_edge(format!("{id}.value"), format!("{to_node}.{pin}")); + return Ok(()); + } + if let Some((kind, parts)) = parse_operator_expression(expression) { + let id = format!("import_op{}", self.serial); + self.serial += 1; + self.ensure_node(&id, kind); + let inputs = ["a", "b", "c"]; + for (part, input) in parts.iter().zip(inputs) { + self.wire_data_expr(part, &id, input)?; + } + self.add_edge(format!("{id}.value"), format!("{to_node}.{pin}")); + return Ok(()); + } if expression == "dt" { if self.delta_time_id.is_none() { let id = format!("import_dt{}", self.serial); @@ -1636,6 +2812,37 @@ impl<'a> DydImporter<'a> { self.add_edge(format!("{source}.value"), format!("{to_node}.{pin}")); return Ok(()); } + if let Some((kind, text)) = input_call(expression) { + let source = match self.expr_to_constant.get(expression).cloned() { + Some(existing) => existing, + None => { + let id = format!("import_i{}", self.serial); + self.serial += 1; + let node = self.ensure_node(&id, kind); + node.text_value = text; + self.expr_to_constant + .insert(expression.to_owned(), id.clone()); + id + } + }; + self.add_edge(format!("{source}.value"), format!("{to_node}.{pin}")); + return Ok(()); + } + if expression == "caffeine_time_total()" { + let source = match self.expr_to_constant.get(expression).cloned() { + Some(existing) => existing, + None => { + let id = format!("import_tt{}", self.serial); + self.serial += 1; + self.ensure_node(&id, NodeKind::TotalTime); + self.expr_to_constant + .insert(expression.to_owned(), id.clone()); + id + } + }; + self.add_edge(format!("{source}.value"), format!("{to_node}.{pin}")); + return Ok(()); + } if let Some(constant) = self.expr_to_constant.get(expression).cloned() { self.add_edge(format!("{constant}.value"), format!("{to_node}.{pin}")); return Ok(()); @@ -2457,4 +3664,237 @@ mod tests { assert_eq!(format_f32(1234567.0), "1.23457e+06"); assert_eq!(format_f32(0.001), "0.001"); } + + #[test] + fn math_compare_and_logic_nodes_emit_and_round_trip() { + let mut graph = Graph::new("logic.dyd"); + let root = graph.add_node(NodeKind::OnUpdate, 0.0, 0.0); + let branch = graph.add_node(NodeKind::Branch, 100.0, 0.0); + let log = graph.add_node(NodeKind::Log, 200.0, 0.0); + let and = graph.add_node(NodeKind::And, 0.0, 100.0); + let key = graph.add_node(NodeKind::KeyDown, 0.0, 200.0); + let less = graph.add_node(NodeKind::Less, 0.0, 300.0); + let total = graph.add_node(NodeKind::TotalTime, 0.0, 400.0); + let add = graph.add_node(NodeKind::Add, 0.0, 500.0); + let dt = graph.add_node(NodeKind::DeltaTime, 0.0, 600.0); + let not = graph.add_node(NodeKind::Not, 0.0, 700.0); + let alive = graph.add_node(NodeKind::IsAlive, 0.0, 800.0); + let me = graph.add_node(NodeKind::SelfEntity, 0.0, 900.0); + let c = |g: &mut Graph, a: &str, b: &str| g.connect(a, b).unwrap(); + c(&mut graph, &format!("{root}.out"), &format!("{branch}.in")); + c(&mut graph, &format!("{branch}.then"), &format!("{log}.in")); + c( + &mut graph, + &format!("{and}.value"), + &format!("{branch}.condition"), + ); + c(&mut graph, &format!("{key}.value"), &format!("{and}.a")); + c(&mut graph, &format!("{less}.value"), &format!("{not}.a")); + c(&mut graph, &format!("{not}.value"), &format!("{and}.b")); + c(&mut graph, &format!("{total}.value"), &format!("{less}.a")); + c(&mut graph, &format!("{add}.value"), &format!("{less}.b")); + c(&mut graph, &format!("{dt}.value"), &format!("{add}.a")); + c(&mut graph, &format!("{me}.value"), &format!("{alive}.a")); + // A number cannot feed a bool input, and a bool cannot feed math. + assert!(graph + .connect(&format!("{total}.value"), &format!("{and}.a")) + .is_err()); + assert!(graph + .connect(&format!("{key}.value"), &format!("{add}.b")) + .is_err()); + + let out = graph.emit().unwrap(); + assert!( + out.dyd.contains( + "if ((caffeine_input_key_down(\"Space\") && (!(caffeine_time_total() < (dt + 0))))) {" + ), + "{}", + out.dyd + ); + let imported = import_from_dyd(&out.dyd, "logic.dyd", None).unwrap(); + let count = |kind: NodeKind| imported.nodes.iter().filter(|n| n.kind == kind).count(); + for kind in [NodeKind::And, NodeKind::Not, NodeKind::Less, NodeKind::Add] { + assert_eq!(count(kind), 1, "{kind:?}"); + } + assert_eq!(imported.emit().unwrap().dyd, out.dyd); + + // A graph with a call node and `entity` also survives the trip. + let mut calls = Graph::new("calls.dyd"); + let root = calls.add_node(NodeKind::OnUpdate, 0.0, 0.0); + let branch = calls.add_node(NodeKind::Branch, 100.0, 0.0); + let log = calls.add_node(NodeKind::Log, 200.0, 0.0); + let alive = calls.add_node(NodeKind::IsAlive, 0.0, 100.0); + let me = calls.add_node(NodeKind::SelfEntity, 0.0, 200.0); + c(&mut calls, &format!("{root}.out"), &format!("{branch}.in")); + c(&mut calls, &format!("{branch}.then"), &format!("{log}.in")); + c( + &mut calls, + &format!("{alive}.value"), + &format!("{branch}.condition"), + ); + c(&mut calls, &format!("{me}.value"), &format!("{alive}.a")); + let text = calls.emit().unwrap().dyd; + assert!( + text.contains("if (caffeine_world_is_alive(entity)) {"), + "{text}" + ); + let again = import_from_dyd(&text, "calls.dyd", None).unwrap(); + assert_eq!(again.emit().unwrap().dyd, text); + } + + #[test] + fn input_and_world_nodes_emit_and_round_trip() { + let mut graph = Graph::new("input.dyd"); + let root = graph.add_node(NodeKind::OnUpdate, 0.0, 0.0); + let branch = graph.add_node(NodeKind::Branch, 100.0, 0.0); + let key = graph.add_node(NodeKind::KeyDown, 0.0, 100.0); + let destroy = graph.add_node(NodeKind::DestroySelf, 200.0, 0.0); + let mv = graph.add_node(NodeKind::Translate, 200.0, 100.0); + let axis = graph.add_node(NodeKind::Axis, 0.0, 200.0); + let total = graph.add_node(NodeKind::TotalTime, 0.0, 300.0); + graph.find_node_mut(&axis).unwrap().text_value = "Vertical".to_owned(); + graph + .connect(&format!("{root}.out"), &format!("{branch}.in")) + .unwrap(); + graph + .connect(&format!("{key}.value"), &format!("{branch}.condition")) + .unwrap(); + graph + .connect(&format!("{branch}.then"), &format!("{destroy}.in")) + .unwrap(); + graph + .connect(&format!("{branch}.else"), &format!("{mv}.in")) + .unwrap(); + graph + .connect(&format!("{axis}.value"), &format!("{mv}.x")) + .unwrap(); + graph + .connect(&format!("{total}.value"), &format!("{mv}.y")) + .unwrap(); + + let out = graph.emit().unwrap(); + assert!(out + .dyd + .contains("if (caffeine_input_key_down(\"Space\")) {")); + assert!(out.dyd.contains("caffeine_world_destroy(entity);")); + assert!(out + .dyd + .contains("caffeine_translate(entity, caffeine_input_axis(\"Vertical\"), caffeine_time_total(), 0);")); + + // A bool pin cannot feed a number input. + assert!(graph + .connect(&format!("{key}.value"), &format!("{mv}.z")) + .is_err()); + + let imported = import_from_dyd(&out.dyd, "input.dyd", None).unwrap(); + let count = |kind: NodeKind| imported.nodes.iter().filter(|n| n.kind == kind).count(); + assert_eq!(count(NodeKind::KeyDown), 1); + assert_eq!(count(NodeKind::DestroySelf), 1); + assert_eq!(count(NodeKind::TotalTime), 1); + assert!(imported + .nodes + .iter() + .any(|n| n.kind == NodeKind::Axis && n.text_value == "Vertical")); + assert_eq!(imported.emit().unwrap().dyd, out.dyd); + + let reloaded = Graph::from_json(&out.node_json).unwrap(); + assert!(reloaded + .nodes + .iter() + .any(|n| n.kind == NodeKind::Axis && n.text_value == "Vertical")); + assert_eq!(reloaded.emit().unwrap().dyd, out.dyd); + } + + #[test] + fn every_native_node_emits_calls_and_round_trips() { + let natives: Vec = NodeKind::ALL + .iter() + .copied() + .filter(|kind| native_row(*kind).is_some()) + .collect(); + assert!(natives.len() >= 29, "the native table feeds the catalog"); + for kind in natives { + let row = native_row(kind).unwrap(); + let mut graph = Graph::new("native.dyd"); + let root = graph.add_node(NodeKind::OnUpdate, 0.0, 0.0); + let node = graph.add_node(kind, 0.0, 100.0); + let mv = graph.add_node(NodeKind::Translate, 200.0, 0.0); + if row.boolean { + let branch = graph.add_node(NodeKind::Branch, 100.0, 0.0); + graph + .connect(&format!("{root}.out"), &format!("{branch}.in")) + .unwrap(); + graph + .connect(&format!("{node}.value"), &format!("{branch}.condition")) + .unwrap(); + graph + .connect(&format!("{branch}.then"), &format!("{mv}.in")) + .unwrap(); + } else { + graph + .connect(&format!("{root}.out"), &format!("{mv}.in")) + .unwrap(); + graph + .connect(&format!("{node}.value"), &format!("{mv}.x")) + .unwrap(); + } + let out = graph.emit().unwrap_or_else(|e| panic!("{kind:?}: {e}")); + let zeros = vec!["0"; row.arity].join(", "); + assert!( + out.dyd.contains(&format!("{}({zeros})", row.native)), + "{kind:?} emits its native: {}", + out.dyd + ); + let imported = import_from_dyd(&out.dyd, "native.dyd", None) + .unwrap_or_else(|e| panic!("{kind:?} import: {e}")); + assert_eq!( + imported.nodes.iter().filter(|n| n.kind == kind).count(), + 1, + "{kind:?} survives the import" + ); + assert_eq!(imported.emit().unwrap().dyd, out.dyd, "{kind:?}"); + } + } + + #[test] + fn nested_native_nodes_keep_their_arguments() { + let mut graph = Graph::new("nested.dyd"); + let root = graph.add_node(NodeKind::OnUpdate, 0.0, 0.0); + let mv = graph.add_node(NodeKind::Translate, 300.0, 0.0); + let clamp = graph.add_node(NodeKind::Clamp, 200.0, 0.0); + let clamp01 = graph.add_node(NodeKind::Clamp01, 100.0, 0.0); + let sin = graph.add_node(NodeKind::Sin, 0.0, 0.0); + graph + .connect(&format!("{root}.out"), &format!("{mv}.in")) + .unwrap(); + graph + .connect(&format!("{sin}.value"), &format!("{clamp01}.a")) + .unwrap(); + graph + .connect(&format!("{clamp01}.value"), &format!("{clamp}.a")) + .unwrap(); + graph + .connect(&format!("{clamp}.value"), &format!("{mv}.y")) + .unwrap(); + let out = graph.emit().unwrap(); + assert!(out + .dyd + .contains("caffeine_math_clamp(caffeine_math_clamp01(caffeine_math_sin(0)), 0, 0)")); + let imported = import_from_dyd(&out.dyd, "nested.dyd", None).unwrap(); + assert!(imported.nodes.iter().any(|n| n.kind == NodeKind::Clamp)); + assert!(imported.nodes.iter().any(|n| n.kind == NodeKind::Clamp01)); + assert_eq!(imported.emit().unwrap().dyd, out.dyd); + } + + #[test] + fn catalog_lists_every_kind_once() { + assert_eq!(catalog().len(), NodeKind::ALL.len()); + for kind in NodeKind::ALL { + let entry = catalog_entry(kind.type_name()).expect("catalog row"); + assert_eq!(entry.kind, kind); + assert_eq!(entry.display_name, kind.display_name()); + assert_eq!(entry.category, kind.category()); + assert_eq!(entry.description, kind.description()); + } + } } diff --git a/doppio/crates/ui/src/uikit/mod.rs b/doppio/crates/ui/src/uikit/mod.rs index e12134b3..7154c66b 100644 --- a/doppio/crates/ui/src/uikit/mod.rs +++ b/doppio/crates/ui/src/uikit/mod.rs @@ -15,7 +15,10 @@ pub mod panels; pub mod prefabs; pub mod procedural; pub mod project; +pub mod recipe; pub mod script; +pub mod script_assist; +pub mod script_reference; pub mod terrain; pub mod texture_graph; pub mod texture_set; diff --git a/doppio/crates/ui/src/uikit/panels/assetmanager.rs b/doppio/crates/ui/src/uikit/panels/assetmanager.rs index 904c4b15..e391fc90 100644 --- a/doppio/crates/ui/src/uikit/panels/assetmanager.rs +++ b/doppio/crates/ui/src/uikit/panels/assetmanager.rs @@ -116,6 +116,7 @@ fn entry_icon(kind: &str, is_directory: bool) -> Icon { "script" => Icon::Script, "asset" => Icon::Scene, "animation" => Icon::Player, + "generator" => Icon::Generic, _ => Icon::File, } } diff --git a/doppio/crates/ui/src/uikit/panels/dryad_nodes.rs b/doppio/crates/ui/src/uikit/panels/dryad_nodes.rs index 9909aad9..e8d5f5f4 100644 --- a/doppio/crates/ui/src/uikit/panels/dryad_nodes.rs +++ b/doppio/crates/ui/src/uikit/panels/dryad_nodes.rs @@ -554,12 +554,18 @@ fn properties_panel<'a, Message: Clone + 'a>( .color(theme::TEXT_MUTED), ); } - NodeKind::Log => { + NodeKind::Log | NodeKind::KeyDown | NodeKind::ActionDown | NodeKind::Axis => { let emit = emit_text.clone(); let id = node_id.clone(); + let label = match kind { + NodeKind::KeyDown => "Key", + NodeKind::ActionDown => "Action", + NodeKind::Axis => "Axis", + _ => "Message", + }; body = body.push(text_field::property( (ids.property)("text"), - "Message", + label, &node.text_value, move |value| emit(id.clone(), value), )); @@ -574,7 +580,14 @@ fn properties_panel<'a, Message: Clone + 'a>( body = body.push(status::chip("No exec link yet", theme::ChipTone::Warning)); } } - NodeKind::GetPosition | NodeKind::GetScale | NodeKind::DeltaTime => { + NodeKind::DestroySelf => { + body = body.push( + text("Removes the entity when this exec chain reaches it.") + .size(9) + .color(theme::TEXT_MUTED), + ); + } + _ => { body = body.push( text("Read-only data node: drag one of its pins into an input.") .size(9) @@ -652,6 +665,27 @@ fn accent(kind: NodeKind) -> iced::Color { NodeKind::Log => theme::TEXT_MUTED, NodeKind::Constant => theme::BORDER_STRONG, NodeKind::Branch => theme::WARNING, + NodeKind::KeyDown | NodeKind::ActionDown | NodeKind::Axis => theme::ICON_CYAN, + NodeKind::TotalTime => theme::ICON_PURPLE, + NodeKind::DestroySelf => theme::DANGER, + NodeKind::Add + | NodeKind::Subtract + | NodeKind::Multiply + | NodeKind::Divide + | NodeKind::Negate => theme::ICON_TEAL, + NodeKind::Less | NodeKind::Greater | NodeKind::Equal => theme::WARNING, + NodeKind::And | NodeKind::Or | NodeKind::Not => theme::ICON_PURPLE, + NodeKind::SelfEntity | NodeKind::IsAlive | NodeKind::Distance => theme::DANGER, + other => { + let category = other.category(); + if category.contains("Input") { + theme::ICON_CYAN + } else if category.contains("Random") || category.contains("Time") { + theme::ICON_PURPLE + } else { + theme::ICON_TEAL + } + } } } diff --git a/doppio/crates/ui/src/uikit/panels/project_manager.rs b/doppio/crates/ui/src/uikit/panels/project_manager.rs index bc55b9b8..0cf3280d 100644 --- a/doppio/crates/ui/src/uikit/panels/project_manager.rs +++ b/doppio/crates/ui/src/uikit/panels/project_manager.rs @@ -318,12 +318,7 @@ pub fn view<'a, Message: Clone + 'a>( )); } column![ - text_field::stacked( - id::PROJECT_NAME, - "Project name", - &state.name, - on_name, - ), + text_field::stacked(id::PROJECT_NAME, "Project name", &state.name, on_name,), row![location, default_location] .spacing(4) .align_y(iced::Alignment::End), @@ -335,10 +330,11 @@ pub fn view<'a, Message: Clone + 'a>( space().height(Length::Fixed(8.0)), button::primary(id::PROJECT_CREATE, "Create & Open", on_create), text(if state.name.trim().is_empty() { - "Enter a name to create project.caffeine with assets/raw, scenes, materials and texture_sets.".to_owned() + "Enter a name to create project.caffeine with Assets, Scripts and Scenes." + .to_owned() } else { format!( - "Creates {}/{}/project.caffeine with assets/raw, scenes, materials and texture_sets.", + "Creates {}/{}/project.caffeine with Assets, Scripts and Scenes.", state.location.trim_end_matches(['/', '\\']), state.name.trim() ) diff --git a/doppio/crates/ui/src/uikit/panels/script.rs b/doppio/crates/ui/src/uikit/panels/script.rs index 7ff1be34..1f862dff 100644 --- a/doppio/crates/ui/src/uikit/panels/script.rs +++ b/doppio/crates/ui/src/uikit/panels/script.rs @@ -46,6 +46,7 @@ pub struct Callbacks<'a, Message> { pub on_select: Box Message + 'a>, pub on_tab_close: Box Message + 'a>, pub on_action: Box Message + 'a>, + pub on_overlay: Box Message + 'a>, pub on_save: Message, pub on_revert: Message, pub on_close: Message, @@ -62,6 +63,7 @@ pub fn view<'a, Message: Clone + 'a>( on_select, on_tab_close, on_action, + on_overlay, on_save, on_revert, on_close, @@ -139,7 +141,13 @@ pub fn view<'a, Message: Clone + 'a>( } let body: Element<'a, Message> = match active { - Some(document) => code_editor::view(ids.editor, &document.editor, on_action), + Some(document) => code_editor::view_with_reference( + ids.editor, + &document.editor, + &document.overlay, + on_action, + on_overlay, + ), None => container( text("Select a script tab.") .size(10) diff --git a/doppio/crates/ui/src/uikit/project.rs b/doppio/crates/ui/src/uikit/project.rs index 3182b5e7..771eff7f 100644 --- a/doppio/crates/ui/src/uikit/project.rs +++ b/doppio/crates/ui/src/uikit/project.rs @@ -1,8 +1,9 @@ //! Project manifest and recent-project storage. //! //! The format matches the existing `project.caffeine` convention: a small JSON -//! file at the project root plus `assets/raw`, `assets/processed`, `scripts`, -//! `scenes`, `materials`, `texture_sets` and `build` folders. +//! file at the project root plus `Assets/Raw`, `Assets/Processed`, `Scripts`, +//! `Scenes` and `Build` folders. Folders the editor creates are capitalised +//! (`Materials`, `Textures`, `Generators`); a user may rename them freely. use serde::{Deserialize, Serialize}; use std::path::{Path, PathBuf}; @@ -30,15 +31,15 @@ impl Default for ProjectPaths { } fn default_assets_raw() -> String { - "assets/raw".to_owned() + "Assets/Raw".to_owned() } fn default_assets_processed() -> String { - "assets/processed".to_owned() + "Assets/Processed".to_owned() } fn default_scripts() -> String { - "scripts".to_owned() + "Scripts".to_owned() } fn default_engine_version() -> String { @@ -88,7 +89,7 @@ impl ProjectInfo { pub fn scene_path(&self) -> Option { if self.last_scene.is_empty() { - let default = self.root.join("scenes").join("main.caf"); + let default = scenes_dir(&self.root).join("main.caf"); return default.exists().then_some(default); } let relative = Path::new(&self.last_scene); @@ -101,6 +102,16 @@ impl ProjectInfo { } } +/// Scene folder of a project: `Scenes`, or a legacy lowercase `scenes` that already exists. +pub fn scenes_dir(root: &Path) -> PathBuf { + let legacy = root.join("scenes"); + if legacy.is_dir() && !root.join("Scenes").is_dir() { + legacy + } else { + root.join("Scenes") + } +} + /// `$CAFFEINE_PROJECTS_DIR`, then `~/Documents/CaffeineProjects`. pub fn default_projects_directory() -> PathBuf { if let Some(directory) = std::env::var_os("CAFFEINE_PROJECTS_DIR") { @@ -164,21 +175,20 @@ pub fn create_project(location: &Path, name: &str, template: &str) -> Result