goverlay Documentation

Goverlay is an easy graphical interface to configure linux gaming applications

1,633 stars Pascal 24 files · ~124,295 tokens
RAW Doc

Technical Documentation: benjamimgois/goverlay

ℹ️ Provenance: Multi-Tier Ingestion · CodeWiki Reference

Overview (`README.md`)


Goverlay is a modern Qt6 GUI for Linux gamers to configure performance overlays, post-processing shaders, upscalers, frame generation, and Proton tweaks—globally or per game—in a few clicks.


Table of Contents


Features

  • Games & Per-Game Profiles: Auto-detects Steam and non-Steam games (with Bottles support in the Apply Configuration dialog). Switch between Global and Game Mode with one-click launch command generation (bgmod ... %command%) and a non-blocking launch splash (bgmod-splash).
  • MangoHud + PasPlot: Configure presets, layouts, and hardware metrics, and inspect benchmark logs directly in the integrated PasPlot viewer with summary cards and metric chips.
  • Unified Post-Processing: Manage vkBasalt (including 3D .cube/.png LUTs), vkSumi, and native ReShade (32/64-bit Windows DLL deployment, shader packs, hotkey capture, and d3dcompiler_47 automation) from a single tab.
  • Upscalers & Frame Generation: Built-in setup and per-game configuration for OptiScaler (including official nightlies, custom FSR 4 builds, and fakenvapi), DLSS-Enabler, DLSS-NR 0.0.9 (including RDNA3/4), HelixSR 3.1, Lossless Scaling (lsfg-vk), MAKO, and AFMF (afmf-linux).
  • Tweaks: Streamlined Material Design 3 tab for Proton/Wine overrides, Controllers, GE/ZLUDA tweaks, custom launch arguments, and environment variables.
  • PasCube Vulkan Preview & Benchmark: Real-time Vulkan preview powered by PasVulkan, featuring a Ray Tracing benchmark suite, community insights, hardware-isolated comparisons via PasCubeDB, and web run submission.

Screenshots

Click to view screenshots

MangoHud presets & layout configuration vkBasalt post-processing & 3D LUTs
vkSumi post-processing effects Native ReShade shader packs & hotkeys
OptiScaler upscaling & fakenvapi Frame Generation (LSFG-VK, MAKO, AFMF, DLSS-NR & HelixSR)
Tweaks: Custom launch arguments Tweaks: Environment variables & overrides

Installation

Universal Packages

Official .deb (Debian / Ubuntu), .rpm (Fedora), AppImage, and tarball builds for both amd64 and aarch64 are provided on the Releases page:

bash
chmod +x goverlay*.AppImage
./goverlay*.AppImage

Flatpak

Install from Flathub or via terminal (MangoHud and vkBasalt layers are bundled automatically):

bash
flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo
flatpak install flathub io.github.benjamimgois.goverlay

Distributions

  • Debian / Ubuntu: Download the .deb package (amd64 or aarch64) from Releases.
  • Fedora: Download the .rpm package (amd64 or aarch64) from Releases.
  • Arch & derivatives: sudo pacman -S goverlay (or yay -S goverlay-git from AUR)
  • openSUSE: sudo zypper install goverlay
  • Solus: sudo eopkg it goverlay

[!IMPORTANT]
Fedora / Debian / Ubuntu users: Official distribution repositories often ship outdated versions. Use the official .deb / .rpm release packages, AppImage, or Flatpak instead.

If your distro lacks libqt6pas, grab it from David Bannon’s releases.


Prerequisites

Required

  • mangohud — Performance overlay
  • qt6pas — Qt6 bindings for Free Pascal / Lazarus
  • git — Clones shader and component repositories
  • gamemode — Feral GameMode daemon
  • Nerd Fonts — Sidebar and game badge glyphs

Optional (Managed via Setup Wizard)

Goverlay includes a built-in Setup Wizard to install and update optional tools on demand:

  • vkBasalt / vksumi — Vulkan post-processing
  • ReShade, OptiScaler, DLSS-NR, HelixSR, MAKO, AFMF, lsfg-vk — Post-processing, upscaling, and frame generation
  • zenergy — AMD CPU power metrics in MangoHud
  • protontricks — Proton prefix helper (native builds only; host-dependent features are hidden in Flatpak)

Building from Source

Requires Lazarus IDE (with Qt6 widgetset), Qt6 development libraries (qt6-base-dev or equivalent), make, and git.

bash
git clone https://github.com/benjamimgois/goverlay.git
cd goverlay
make
./start_goverlay.sh

make compiles goverlay, pascube, bgmod, bgmod-uninstaller, and bgmod-splash. To install system-wide:

bash
sudo make install
goverlay

Architecture & How It Works

Technical details: How bgmod works, per-game XDG configs, and tech stack

How `bgmod` Works

mermaid
flowchart TD
    A["Steam / Lutris / Heroic<br/>(bgmod &lt;game&gt; %command%)"] --> B["Load Per-Game Config<br/>(bgmod.conf, env vars, Wine DLL overrides)"]
    B --> C{"Detect Executable Type<br/>(skips intermediate launchers)"}
    C -->|"Native Linux ELF"| D["Skip DLL Injection<br/>Apply MangoHud, vkBasalt, vkSumi &amp; LSFG-VK"]
    C -->|"Windows EXE (Proton / Wine)"| E["Deploy 32/64-bit Plugins<br/>Copy OptiScaler, ReShade, DLSS-NR, HelixSR + backups"]
    D --> F["Launch Game + bgmod-splash<br/>Logs saved to ~/.local/share/goverlay/logs/"]
    E --> F

Per-Game Config Architecture

When a game is selected, Goverlay switches to Game Mode and manages an isolated XDG-compliant config directory per game containing:

  • MangoHud.conf
  • vkBasalt.conf
  • vkSumi.conf
  • OptiScaler.ini
  • fakenvapi.ini
  • bgmod.conf and the bgmod wrapper binary

bgmod is a compiled Free Pascal binary replacing legacy bash scripts. It keeps game directories anti-cheat safe by storing logs in /tmp/bgmod.log and ~/.local/share/goverlay/logs/[Game Name]/. To remove injected files and restore original backups, run bgmod-uninstaller.

Tech Stack

Component Technology
Language Free Pascal (ObjFPC mode)
GUI Framework Lazarus LCL with Qt6 widgetset
Build System make (wrapping lazbuild & fpc)
Preview / Benchmark Integrated Vulkan demo (pascube, PasVulkan engine)
Game Wrapper Compiled Free Pascal binaries (bgmod, bgmod-uninstaller, bgmod-splash)

Credits

Goverlay builds on the work of the Linux gaming and open-source community:


Donations

If Goverlay has been useful to you, consider supporting its development ❤️



Overview (`pascube_src/README.md`)

PasCube

A simple vulkan spinning cube in pascal


Overview (`tests/README.md`)

GOverlay Local Test Suite

Automated regression tests for GOverlay, designed to run locally before every
commit. No X server, no display, no mouse synthesis: tests run in-process
against the real application code.

Architecture

text
tests/
  common/   test_isolation.pas  - shared sandbox: fresh mock HOME, seed
                                  config, re-exec so the FPC runtime sees
                                  the mocked environment from process start
  logic/    logic_tests         - headless fpcunit tests for config logic
                                  (driver preference, OptiScaler INI
                                  round-trips). No GUI needed.
  gui/      gui_tests           - instantiates the real Tgoverlayform with
                                  Qt6 offscreen platform, drives controls
                                  programmatically (OnClick invocations,
                                  TRadioButton.Checked) and asserts on
                                  config files + control state.

Key properties:

  • Deterministic: GOVERLAY_TEST=1 makes the app skip network update
    checks, background download threads, and the changelog fetch on startup.
  • Isolated: every run uses a fresh temporary $HOME. Real user
    configuration is never touched. The sandbox is deleted on success and
    preserved (path printed) on failure.
  • Falsifiable: toggle tests assert both transitions, so pre-seeded
    fixture values can never satisfy an assertion by accident.

Running

bash
make test          # builds and runs both layers
make test-logic    # logic layer only
make test-gui      # GUI wiring layer only

Commit gate

Install the pre-commit hook to block commits when tests fail:

bash
sh tests/install-hook.sh

Bypass in emergencies with git commit --no-verify.

Writing new tests

  • Logic tests: add a TTestCase in logic/logic_test_cases.pas and
    RegisterTest it. Runs in milliseconds, no display.
  • GUI tests: add to gui/gui_test_cases.pas. The form is created once
    before the suite runs; access controls via goverlayform.<controlName>
    and invoke .OnClick(control) / set .Checked to exercise the real
    .lfm event bindings.

Overview (`data/bgmod/README.md`)

bgmod — Agent Context & Architecture

bgmod is a native compiled Free Pascal wrapper (bgmod.lpr) designed to replace the legacy fgmod bash script inside GOverlay. It intercepts game execution arguments, configures environment variables, handles Wine DLL overrides, manages upscale plugins, and executes the target game.

Architecture & Workflow

  1. Resolution: On startup, it resolves the target game directory from execution arguments, Lutris game IDs, or STEAM_COMPAT_INSTALL_PATH.
  2. Configuration: It parses configuration values and environment variables from bgmod.conf.
  3. Upscaler Setup: If OptiScaler is toggled, it backs up original system/game DLLs, copies dynamic link libraries (OptiScaler.dll, XeSS, FidelityFX, fake-nvapi), and sets up the plugins directory.
  4. Execution: Exports active environment variables and launches the target game subprocess using execvp.

Key Files & Structure

File Type Purpose
bgmod Binary Main compiled wrapper executable.
bgmod-uninstaller Binary Native uninstaller. Restores backed up files and cleans game folders.
bgmod.conf INI Config Configuration file containing [Config], [Env], and [Launchers] sections.

Configuration Format (`bgmod.conf`)

bgmod.conf is stored next to the wrapper binary (either globally or inside game-specific config directories).

`[Config]` Section

  • GOVERLAY_MANGOHUD (0/1): Toggles MangoHud overlay.
  • GOVERLAY_VKBASALT (0/1): Toggles vkBasalt overlay.
  • GOVERLAY_VKSUMI (0/1): Toggles vkSumi color grading post-processor.
  • GOVERLAY_OPTISCALER (0/1): Toggles OptiScaler.
  • GOVERLAY_TWEAKS (0/1): Toggles Proton tweaks and env vars.
  • DLL (string): Target DLL name to load (default: dxgi.dll).
  • PRESERVE_INI (true/false): Toggles persistence of OptiScaler.ini.

`[Env]` Section

Standard environment variables to export before running the game (e.g. PROTON_ENABLE_HDR=1).

`[Launchers]` Section

Dynamic rules to match launcher EXEs and redirect them to target game EXEs.
Format: GameSubstring = LauncherEXE|ActualGameEXE
Example:

ini
[Launchers]
Cyberpunk 2077 = REDprelauncher.exe|bin/x64/Cyberpunk2077.exe
Witcher 3 = REDprelauncher.exe|bin/x64_dx12/witcher3.exe

If the launchers section or file is missing, the binary falls back to its built-in default launchers list.


Uninstallation Model

The uninstaller bgmod-uninstaller resolves the game directory, and:

  1. Deletes copied upscaler and overlay DLLs and configuration files.
  2. Removes the plugins/ directory recursively.
  3. Restores original game files from .b backups.
  4. Deletes the wrapper symlinks, wrapper logs, and itself.
  5. Supports the -g / --global flag to clean up the central GOverlay config directory.

Logging

Execution logs are written to:

  1. /tmp/bgmod.log (wrapper) and /tmp/bgmod-uninstaller.log (uninstaller).
  2. Central GOverlay logs directory: ~/.local/share/goverlay/logs/[Game Name]/bgmod.log.

Game directories remain clean and free of log files to ensure compatibility with anti-cheat software and integrity checkers.


Overview (`data/fgmod/README.md`)

Credit

This mod is an installation script for Artur's DLSS Enabler which itself is a combination of multiple other projects.

Installation

Run this command in the terminal

sh
curl https://raw.githubusercontent.com/FakeMichau/fgmod/main/prepare.sh | bash --

This will create a folder called fgmod in your home directory with a wrapper fgmod inside of it.

Before running it, at least take a look at prepare.sh and fgmod.sh, piping stuff blindly into sh is not wise.

Usage

After running the script, you will be given the exact command. In case you missed it, look below.

Replace USERNAME with your own.
For Steam, add this to the launch options /home/USERNAME/fgmod/fgmod %COMMAND%
For Heroic, add this as a new wrapper /home/USERNAME/fgmod/fgmod
For Bottles, add this as pre-run script in the launch options /home/USERNAME/fgmod/fgmod
For Lutris, go to system options then add this to command prefix /home/USERNAME/fgmod/fgmod

AUR package

There is PKGBUILD, download that and fgmod.sh, you know what to do with it - makepkg. Usage is simpler, just add fgmod as a wrapper.

Uninstallation

1. For a single game

  • Remove /home/USERNAME/fgmod/fgmod from the launch options
  • Run fgmod-uninstaller.sh found in the game folder, it will not always be the main folder

2. The whole fgmod

  • Remove the /home/USERNAME/fgmod folder
  • Do the steps for a single game for every game you've used fgmod with

Overview (`pascube_src/pasvulkan/README.md`)

[!IMPORTANT]
The primary repository has moved to git.rosseaux.net/BeRo1985/pasvulkan.
This GitHub repository is kept up-to-date via push mirroring.

pasvulkan

Vulkan header generator and Vulkan OOP-style API wrapper for Object Pascal (FreePascal >= 3.3.1 FPC trunk and any recent current Delphi version)

The Vulkan.pas binding header unit itself (including the vkxml2pas.dpr converter) is and stays also compatible with the old Delphi 7 version, but the PasVulkan.*.pas framework units are no more Delphi 7 compatible, because they are using new Object Pascal syntax features, as such as generics, operator overloading, advanced records and so on, which for these the old Delphi 7 compiler version have no support for.

Support me

Creating is my passion, and with your support, I can keep it alive. Support my work and help me continue innovating. Every contribution makes a difference: You can donate and support me here. Thank you!

About me / My contact details

Important repository checkout information

If you've problems with the git clone command, because the repository is too large for you or you don't need the full history of the repository, you can try to use the following command instead:

bash
git clone --single-branch --depth 1 --recursive https://github.com/BeRo1985/pasvulkan.git pasvulkan

or respectively for the SSH variant:

bash
git clone --single-branch --depth 1 --recursive [email protected]:BeRo1985/pasvulkan.git pasvulkan

or alternatively, you can try to turn off the compression, which can also help in some cases, but aware, it is a global setting for all git repositories on your system:

bash
git config --global core.compression 0

Important information

You must first compile the (yet incomplete) PasVulkan project manager using compileprojectmanager (*nix) or compileprojectmanager.bat (Windows) so that you can then use the PasVulkan project manager as a command line tool named projectmanager(.exe) .

And you do need either the most current Delphi version or the most current SVN trunk version of the FreePascal compiler (and not just the stable version of the FreePascal compiler), including correct paths in your PATH environment variable to these compiler binaries. And if you also want to use the Android target, the same applies to Android Studio, the Java SDK, the Android SDK and the Android NDK, that these must be installed at their default locations (as Google prescribes or specifies these default locations, without exceptions) and must be correctly exist in the system environment variables.

And for the Android target you do need all FreePascal cross compiler installations for all from Android official supported CPU targets without any exception, and these are: x86_32/i386, x86_64/AMD64, ARM32 and AArch64/ARM64

How to build and to run the example project

After you've compiled the projectmanager binary, you need to do the following:

Step Windows *nix Description
1. projectmanager compileassets examples ./projectmanager compileassets examples It compiles the asset files
2. projectmanager build examples ./projectmanager build examples It compiles the example code itself
3. projectmanager run examples ./projectmanager run examples It starts the example binary

How to create a new project

After you've compiled the projectmanager binary, you need to do the following:

Step Windows *nix Description
1. projectmanager create [yourprojectname] ./projectmanager create [yourprojectname] It creates the new project

Important: Where the project name must be a valid lowercase pascal and java identifier and even a valid file name at the same time!

For further information regarding the project manager

After you've compiled the projectmanager binary, just execute projectmanager -h in your shell or console for a detailed help output.

Features

  • C-API-style Vulkan header (Vulkan.pas which is generated by vkxml2pas.dpr)
    • It's always up-to-date, since it's auto-generated through the vkxml2pas.dpr
    • Supported platforms:
      • Windows (x86-32, x86-64)
      • Android (x86-32, x86-64, ARM32, ARM64/AArch64)
      • Linux (x86-32, x86-64, ARM)
        • X11
        • Wayland
      • MoltenVK wrapper (untested)
        • iOS
        • MacOS
  • OOP-based Vulkan Framework (PasVulkan.Framework.pas)
    • Object oriented Vulkan API abstraction
    • Best-fit red-black-tree based memory manager for the Vulkan memory management, for to manage the sub-allocations in the allocated buffers and for to keep the total count of simultaneous live allocations as much low as possible and less than TVkPhysicalDeviceLimits.maxMemoryAllocationCount.
    • Texture loaders with own ObjectPascal-native loader implementations, so it is independent of external third-party image loaders, even independent of the VCL, LCL and FCL.
      • BMP (untested, but it should work)
      • DDS
      • HDR
      • KTX
      • JPG / JPEG (only baseline, only Huffman-coded and only YCrCb at the moment now)
      • PNG (all types, including 16-bit channel PNGs)
      • TGA
    • Features swap chain screenshot API functions
      • including an own ObjectPascal-native minimal PNG writer implementation (including an own minimal static-huffman only deflate implementation)
      • including an own ObjectPascal-native JPEG writer implementation
    • Optional automatic GPU-based texture mipmap generation (with help of vkCmdBlitImage)
    • Own ObjectPascal-native TrueType/OpenType Font loader implementation
      • With experimental PostScript-flavoured OpenType Font support (CFF Type 2)
      • With semi-working TrueType-flavoured OpenType Font hinting byte code interpreter as an optional option
      • With automatic on-the-fly high-quality fast parallizied signed distance field generation (based on the implementation ideas from Practical Analytic 2D Signed Distance Field Generation and with PasMP )
      • A font vector textures feature is also planned for the future, for an own combined signed-distance-field + vector-texture hybrid font rendering technology implementation, dependently by the font size and so on, where the RGB channels of a texel would be then the together OR'ed 24-bit first-bezier-linked-list-index (to a Vulkan buffer with the bezier data, 0xffffff = no (next) bezier), and the alpha channel of a texel would be just the 8-bit signed distance field.
    • Sprite batch class
    • Sprite atlases
      • With automatic fast on-the-fly sprite atlas constructions with optional automatic cropping/trimming, so that you don't need external sprite atlas generation tools, but nevertheless, the output of the TexturePacker tool is also supported by PasVulkan
    • and more useful utils and stuff for Vulkan-programming
    • Supported platforms:
      • Windows (x86-32, x86-64)
      • Android (x86-32, x86-64, ARM32, ARM64/AArch64)
      • Linux (x86-32, x86-64, ARM)
        • X11
        • Mir
        • Wayland
      • MoltenVK wrapper (untested)
        • iOS
        • MacOS
  • OOP-style Vulkan-optimized Application framework (PasVulkan.Application.pas PasVulkan.Android.pas PasVulkan.SDL2.pas PasVulkan.StarticLinking.pas)
    • The overall design of this Vulkan-optimized Application framework is mixture between the VCL/LCL/FCL and libGDX design concepts (and some of my own design ideas, of course).
    • It uses SDL 2.x as OS-API abstraction layer API
    • Single-window-only, so it is cross-platform-friendly to the maximum, as far as it is possible.
      • For multi-window applications, you must do your own stuff (for example, own framework or using the VCL/LCL etc.), because it is out of the focus of the targets from this Vulkan-optimized Application framework
    • Automatic recovery for:
      • VK_ERROR_SURFACE_LOST_KHR
      • VK_ERROR_OUT_OF_DATE_KHR
      • VK_SUBOPTIMAL_KHR
      • but not for, for example, VK_ERROR_DEVICE_LOST, VK_ERROR_OUT_OF_DEVICE_MEMORY or VK_ERROR_OUT_OF_HOST_MEMORY, because that are critical situations, which you must handle yourself.
    • Automatic Swap Chain creation and recreation
    • Re-abstraction of the SDL2 abstraction, for the possible future case, when this Vulkan-optimized Application framework will be not SDL 2.0 based for possible further following target platforms, the Nintendo Switch as example, or when this Vulkan-optimized Application framework will be no more SDL 2.0 based for some already supported target platforms.
    • Supported platforms:
      • Windows (x86-32, x86-64)
      • Android (x86-32, x86-64, ARM32, ARM64/AArch64)
      • Linux (x86-32, x86-64, ARM)
        • X11
        • Mir
        • Wayland
      • But no MoltenVK yet (since SDL 2.x has no support for it yet, so far I know)

License (zlib)

text
Copyright (C) 2016-2017, Benjamin Rosseaux ([email protected])          
                                                                         
This software is provided 'as-is', without any express or implied          
warranty. In no event will the authors be held liable for any damages      
arising from the use of this software.                                     
                                                                         
Permission is granted to anyone to use this software for any purpose,     
including commercial applications, and to alter it and redistribute it    
freely, subject to the following restrictions:                            

1. The origin of this software must not be misrepresented; you must not    
   claim that you wrote the original software. If you use this software    
   in a product, an acknowledgement in the product documentation would be  
   appreciated but is not required.                                        
2. Altered source versions must be plainly marked as such, and must not be 
   misrepresented as being the original software.                          
3. This notice may not be removed or altered from any source distribution.

General guidelines for code contributors

  1. Make sure you are legally allowed to make a contribution under the zlib license.
  2. The zlib license header goes at the top of each source file, with appropriate copyright notice.
  3. This PasVulkan wrapper may be used only with the PasVulkan-own Vulkan Pascal header.
  4. After a pull request, check the status of your pull request on https://github.com/BeRo1985/pasvulkan
  5. Write code which's compatible with Delphi >= 2009 and FreePascal >= 3.1.1
  6. Don't use Delphi-only, FreePascal-only or Lazarus-only libraries/units, but if needed, make it out-ifdef-able.
  7. No use of third-party libraries/units as possible, but if needed, make it out-ifdef-able.
  8. Try to use const when possible.
  9. Make sure to comment out writeln, used while debugging.
  10. Make sure the code compiles on 32-bit and 64-bit platforms (x86-32, x86-64, ARM, ARM64, etc.).
  11. Make sure the code runs on all platforms with Vulkan support

Showcase videos

  • For more recent showcase videos see Youtube playlist

  • PasVulkan on Android 7.0 on a NVIDIA Shield K1 Tablet

  • PasVulkan on a NVIDIA Geforce GTX 970 under Windows 10 Pro


Overview (`data/icons/buttons/README.md`)

Button Icons for Goverlay

This directory contains icons for the main buttons in Goverlay's interface.

Icon Files

All icons are available in three sizes: 16x16, 24x24, and 32x32 pixels.

Available Icons

Icon File Description Suggested Use
save.svg / save.png Floppy disk icon Save configuration buttons
test.svg / test.png Play button Test/launch buttons (vkcube, demos)
update.svg / update.png Refresh/sync arrows Update/check for updates buttons
copy.svg / copy.png Clipboard copy Copy to clipboard buttons
download.svg / download.png Download arrow Download/install buttons
folder.svg / folder.png Folder icon Browse folder/log path buttons
help.svg / help.png Question mark Help/how-to buttons
check.svg / check.png Check mark Verify/check status buttons
theme-light.svg / theme-light.png Sun icon Light theme toggle button
theme-dark.svg / theme-dark.png Moon icon Dark theme toggle button
doc.svg / doc.png Document icon Open config file menu item
eye.svg / eye.png Eye icon Floating action dock preview button

Button Mapping

Main Buttons (from overlayunit.pas)

  • saveBitBtn → save.png - Save MangoHud configuration
  • copyBitBtn → copy.png - Copy OptiScaler command to clipboard
  • updateBitBtn → update.png - Update OptiScaler
  • checkupdBitBtn → check.png - Check for OptiScaler updates
  • gupdateBitBtn → download.png - Update Goverlay
  • howtoBitBtn → help.png - How to use OptiScaler
  • logfolderBitBtn → folder.png - Browse log folder
  • reshaderefreshBitBtn → download.png - Download ReShade shaders
  • blacklistBitBtn → Similar buttons (settings icon could be added)

Preset Buttons

  • fullBitBtn, basicBitBtn, fpsonlyBitBtn, etc. → Could use preset-specific icons

Usage in Lazarus

To add these icons to buttons in Lazarus IDE:

  1. Open the form in Lazarus IDE
  2. Select the ImageList component (already exists: iconsImageList)
  3. Add the PNG icons from the appropriate size folder (24x24 recommended)
  4. For each button:
    • Set Images property to the ImageList
    • Set ImageIndex property to the correct icon index
    • Optionally set Layout to position icon relative to text

Style Guide

  • Icons use a minimalist line style (2px stroke)
  • All icons are designed to work well on dark backgrounds
  • SVG source files are provided for easy modification
  • Colors can be adjusted in the SVG files if needed

Adding New Icons

To add new icons:

  1. Create/download an SVG file and place it in this directory
  2. Run the conversion script:
    bash
    cd data/icons/buttons
    for size in 16 24 32; do
      magick -background none -density 300 newicon.svg -resize ${size}x${size} ${size}x${size}/newicon.png
    done
  3. Add the PNG to the ImageList in Lazarus
  4. Update this README with the new icon

Credits

Icons based on the Lucide icon set style (MIT License compatible).


Overview (`openspec/changes/archive/2026-09-08-open-config-and-log-folders/README.md`)

open-config-and-log-folders

Open config and log folders in file manager from hamburger menu


Overview (`openspec/changes/archive/2026-09-19-lossless-scaling-dynamic-card-heights/README.md`)

lossless-scaling-dynamic-card-heights

Anchor status card to bottom and dynamically scale middle cards on window resize in Lossless Scaling tab


Overview (`openspec/changes/archive/2026-09-19-mako-toggles-single-row/README.md`)

mako-toggles-single-row

Move Live FG Switch to same row as other toggles in MAKO mode to avoid vertical scrolling


Overview (`openspec/changes/archive/2026-09-19-optiscaler-options-height/README.md`)

optiscaler-options-height

Reduce OptiScaler Options card height to prevent vertical scrolling


Overview (`pascube_src/pasvulkan/externals/pasdblstrutils/README.md`)

[!IMPORTANT]
The primary repository has moved to git.rosseaux.net/BeRo1985/pasdblstrutils.
This GitHub repository is kept up-to-date via push mirroring.

PasDblStrUtils

Pascal library for cross-compiler consistent and exact conversion between double-precision floating point number values and strings

License

zlib licensed


Overview (`pascube_src/pasvulkan/externals/pasjson/README.md`)

[!IMPORTANT]
The primary repository has moved to git.rosseaux.net/BeRo1985/pasjson.
This GitHub repository is kept up-to-date via push mirroring.

PasJSON

A unified JSON library for both Object-Pascal ecosystems (Delphi and FreePascal)

Requirements

License

zlib

Support me

Support me at Patreon


Overview (`pascube_src/pasvulkan/externals/pasmp/README.md`)

[!IMPORTANT]
The primary repository has moved to git.rosseaux.net/BeRo1985/pasmp.
This GitHub repository is kept up-to-date via push mirroring.

PasMP

PasMP - a parallel-processing/multi-processing library for Object Pascal

License: zlib

Support me

Support me at Patreon

Features

  • Low-level-based design with optional high-level-based constructs
  • Designed for fully-strict fork-join model in mind (because it's less error-prone to work with it than with terminally-strict fork-join for my taste), but it can be also abused for more flexible models, the only important thing is, that you're releasing the jobs again as soon as they are completed (the simplest weay would be by calling TPasMP.Reset per workload-frame), otherwise you'll have memory leaks, or just use the PasMPJobFlagReleaseOnFinish flag.
  • It can be used as a job scheduler for multithreaded game engines and so on
  • Work-first lock-free work-stealing dynamic-sized Chase-Lev queue/deque (where only the resizing code part of it isn't lock-free, so that on the other hand it is garbage-collector-free)
  • Lock-free job memory allocator (al least lock-free on x86-32 and x86-64 targets)
  • Parallel-for pattern
  • Parallel intro sort (direct and indirect)
  • Parellel merge sort (direct and indirect)
  • Thread-safe single producer single consumer queue (untyped and typed, bounded-only, lock-free)
  • Thread-safe multiple producer multiple consumer stack (untyped and typed, bounded and unbounded, lock-free on x86-32/x86-64/ARM32, lock-based on another CPU targets)
  • Thread-safe multiple producer multiple consumer queue (untyped and typed, bounded and unbounded, lock-free on x86-32/x86-64/ARM32, lock-based on another CPU targets)
  • Thread-safe hash table (untyped and typed, hybrid-implementation of lock-free and fine-graded lock-based single-operation code parts)
  • Thread-safe dynamic-sized array (untyped and typed, fine-graded lock-based)
  • TPasMPMath class with class static useful (primary bit-twiddling) math function methods
  • TPasMPInterlocked class with class static atomic function methods
  • TPasMPMemoryBarrier class with class static memory barrier function methods
  • TPasMPMemory class with class static aligned memory allocation function methods
  • Synchronisation primitives:
    • TPasMPEvent
    • TPasMPSimpleEvent
    • TPasMPCriticalSection
    • TPasMPMutex
    • TPasMPConditionVariableLock
    • TPasMPConditionVariable
    • TPasMPSemaphore
    • TPasMPInvertedSemaphore
    • TPasMPMultipleReaderSingleWriterLock
    • TPasMPMultipleReaderSingleWriterSpinLock
    • TPasMPSlimReaderWriterLock
    • TPasMPSpinLock
    • TPasMPBarrier
  • Optional strict singleton usage option per global PasMPUseAsStrictSingletonInstance define (besides the option of usage of multiple PasMP instances)
  • Compatible with FreePascal >= 3.0.0 and Delphi >= 7
  • Cross platform (Windows (needs Vista or higher, so no XP, no 9x, no NT 3.x, no NT 4.x), Linux, etc.)

Target informations (i.e. System requirements)

  • 32-bit x86 targets must support the cmpxchg8b instruction (it present on most all post-80486 processors, so >= Pentium 1 and newer)
  • 64-bit x86 targets must support the cmpxchg16b instruction (early AMD64 processors before Revision F and some early stepping D Intel Nocona processors lacked the CMPXCHG16B instruction, otherwise all 64-bit x86 processors should have support for the cmpxchg16b instruction)
  • ARM targets must support the ldrexd and strexd instructions (it present on ARMv6k and ARMv7 and higher ARM processors)
  • MIPS targets aren't supported in the lock-free PasMP build variant (only as lock-based PasMP build variant), until I've found a way to do Double-Compare-And-Swap on the MIPS target. I would be most pleased to have your hints and suggestions to help up me to implement DCAS (or a lock-free ABA-free multiple producer multiple consumer queue and stack) on the MIPS target.
  • PowerPC targets aren't supported in the lock-free PasMP build variant (only as lock-based PasMP build variant), until I've found a way to do Double-Compare-And-Swap on the PowerPC target. I would be most pleased to have your hints and suggestions to help up me to implement DCAS (or a lock-free ABA-free multiple producer multiple consumer queue and stack) on the PowerPC target.

Overview (`pascube_src/pasvulkan/externals/pucu/README.md`)

[!IMPORTANT]
The primary repository has moved to git.rosseaux.net/BeRo1985/pucu.
This GitHub repository is kept up-to-date via push mirroring.

PUCU Pascal UniCode Utils Libary

You do need only the src\PUCU.pas file for the normal usage of this Library


Pascube Src Pasvulkan Docs Canvas Transparency Rendering (`pascube_src/pasvulkan/docs/canvas_transparency_rendering.md`)

This document provides a comprehensive technical analysis and comparison of the Coverage-Mask-Then-Cover technique used in TpvCanvas in PasVulkan for rendering transparent shapes, against other mainstream approaches in the field of 2D graphics rendering. It also explores alternative solutions for handling complex transparency scenarios, delves into specific technical questions, and presents a trade-off analysis to guide implementation decisions.


🆚 1. Coverage Buffer Technique Comparison

The TpvCanvas method Coverage-Mask-Then-Cover is essentially a Coverage-based Depth Sorting Alternative. Its core idea is: The shape with the highest 32-bit stamp+coverage value to "own" a pixel determines that pixel's final color, thereby avoiding complex depth sorting or depth peeling. Many modern engines use similar ideas, but implementation details vary. In the following text, TpvCanvas's stamp ID is referred to as "Shape ID / Stamp ID" for clarity to those familiar with other engines.

1. Technical Implementation Comparison

The table below compares the core mechanisms of TpvCanvas against other mainstream implementation approaches.

Feature Dimension TpvCanvas (PasVulkan) Pathfinder piet-gpu / vello NanoVG (Vulkan) Skia Ganesh (Vulkan)
Core Idea Atomic Ops + Highest Stamp+Coverage Wins Geometry Decomposition + Depth Sorting Tile/Warp Parallel + Local Atomics Two-Pass Rendering (Geometry+Composite) Multi-pass Depth Peeling Variant
Coverage Data 32-bit Atomic: ShapeID/StampID(24b) + Coverage(8b) Coverage Buffer (Count or Depth) Tile/Warp Local Buffer Intermediate Color Buffer Depth Buffer + Color Buffer
Atomic Operations Yes (imageAtomicCompSwap) No (Based on Pre-sorting) Yes (In Compute Shader) No (Based on Pre-sorting or Blending) No (Based on Pass Sorting)
Antialiasing Analytical/SDF (High Quality) Analytical/SDF Analytical/SDF MSAA (Optional) Analytical/MSAA
Render Passes 1 Pass Interrupt + Restart (For Barrier) 1 Pass (Or a few) 1 Pass (Compute Shader Main) 2 Passes (Geometry + Composite) Multiple Passes (Depth Peeling)
Shape ID Management 24-bit, Periodic Buffer Reset at overflows Depth Value replaces ID Local ID within Tile/Warp No Direct ID Management No Direct ID Management
Dependencies fragmentStoresAndAtomics Basic Vulkan VK_KHR_shader_subgroup Basic Vulkan Basic Vulkan
Main Advantage Simple Implementation, Single Write Order Independent, High Quality Extreme Parallelism, No Global Atomics Good Compatibility, Traditional Pipeline High Quality, Mature Engine
Main Challenge Shape ID / Stamp ID Reset Overhead, Intra Render Pass Barriers with Render Pass Restart CPU Sorting Overhead High Complexity, New Hardware Needed Potentially High Fill Rate High Pass Count, Overhead

2. Detailed Implementation Comparison

**TpvCanvas: Coverage-Mask-Then-Cover**

mermaid
flowchart LR
    A[Submit Shape Geometry] --> B[Pass 1: Coverage Mask<br>Atomic Write ShapeID/StampID+Coverage<br>Highest Value Wins]
    B --> C[Pass 2: MaskBarrier<br>EndRenderPass<br>PipelineBarrier<br>Sync Storage Image Writes]
    C --> D[Pass 3: Coverage Cover<br>Bounding-box Quad per Shape<br>Read ShapeID/StampID & Match<br>Output Color]
    D --> E[Pass 4: CoverBarrier<br>EndRenderPass<br>PipelineBarrier<br>Sync Framebuffer Writes]
    E --> F[Composite Final Image]

    style B fill:#e3f2fd,stroke:#2196f3,color:#0d47a1
    style D fill:#bbdefb,stroke:#2196f3,color:#0d47a1
  • Method: In the first pass (Mask), each fragment attempts to write its shape ID / stamp ID and coverage to a storage image using imageAtomicCompSwap. The fragment with the highest UINT32 value (24-bit stamp + 8-bit coverage) to write "wins" for that pixel. After a memory barrier (MaskBarrier) to sync writes, the third pass (Cover) renders a bounding-box quad for each shape that reads the coverage buffer, retrieves the shape ID / stamp ID, and outputs the corresponding color with antialiased coverage. A final barrier (CoverBarrier) ensures all framebuffer writes complete before the next shape's operations, preventing race conditions on overlapped shapes.
  • Core of Atomic Operations: imageAtomicCompSwap ensures O(1) time complexity to determine the "owner" of each pixel, avoiding O(N) depth sorting. This fits scenarios where many shapes (dense text, complex paths) might overlap a single pixel.
  • Advantage of SDF-AA: Calculating Signed Distance Field (SDF) in the fragment shader and converting it to coverage (0-255) provides extremely smooth, high-quality edges without the overhead of MSAA multi-sampling. This is crucial for text rendering.
  • Inevitability of Pass Interruptions: As noted, vkCmdPipelineBarrier is necessary because Vulkan specs have strict restrictions on read/write synchronization of storage images inside traditional render passes. Interrupting the pass and inserting memory barriers is the standard and safest way to ensure all fragment shader writes are visible to subsequent reads, and to prevent race conditions on overlapped shapes. The overhead is usually lower than the potential performance loss of using VK_EXT_fragment_shader_interlock on some hardware, and compatibility is better. Two barriers are now used: one after the Mask pass (MaskBarrier) and one after the Cover pass (CoverBarrier).
  • Shape ID / Stamp ID and Reset: The 24-bit ID (~16.7 million) is sufficient for most scenes. When approaching the limit, clearing the entire coverage buffer is necessary. This overhead can be amortized by batch processing shapes (i.e., accumulating a large number of shapes until a reset is needed).
  • Coverage: Coverage Image Buffer is a single 32-bit unsigned integer per pixel, leading to a fixed memory footprint (e.g., ~4MB for 1080p). This is extremely memory efficient compared to A-Buffer or depth peeling methods. The 8-bit coverage from the lower bits of the 32-bit value alongside the 24-bit stamp allows for 256 levels of antialiased coverage, which is generally sufficient for high-quality rendering.
  • Advantage: Simplicity, Efficiency, and Quality. The method is easy to implement, has low computational overhead (single atomic write/read), and provides high-quality antialiased results suitable for UI and text rendering.
  • Challenge: The main challenges are managing the shape ID / stamp space (requiring periodic resets) and the overhead of render pass interruption due to Vulkan's synchronization requirements of barriers in render passes. However, these can be mitigated through careful batching and design.

**Pathfinder: Geometry Decomposition + Depth Sorting**

Pathfinder employs a different Order-Independent Transparency (OIT) strategy. It does not rely on atomic operations but rather depth-sorts geometry on the CPU or in a compute shader to render front-to-back.

  • Method: Decomposes complex paths into simple triangles. By calculating a depth value for each triangle and sorting based on it, triangles closer to the camera are rendered last.
  • Coverage: May use a coverage count buffer recording how many triangles cover each pixel, but the final pixel color is determined by the last (front-most) rendered triangle.
  • Advantage: Avoids atomic operation and storage image synchronization overhead, potentially more efficient when depth complexity is extremely high (e.g., thousands of overlapping layers). Antialiasing quality is also top-tier.
  • Challenge: CPU-side sorting overhead can become a bottleneck, especially for dynamically changing content. It cannot solve the "owner" problem with a single atomic operation like TpvCanvas.

**piet-gpu / vello: Tile/Warp Parallel Computing**

This is the cutting edge of next-gen 2D renderers, completely stepping outside the traditional rasterization pipeline.

  • Method: Works in compute shaders. It divides the rendering area into small tiles or utilizes the GPU Wavefront/Warp SIMD nature. Each tile/warp processes all fragments in parallel and resolves overlaps and sorting locally (shared memory/registers).
  • Coverage: Each tile maintains a local fragment list or uses local atomic operations to merge coverage information, finally outputting a single final color.
  • Advantage: Ultimate parallelism, no global atomic operations, low bandwidth pressure, highly suitable for modern GPU architectures. Can easily handle massive overlapping shapes.
  • Challenge: Extremely high implementation complexity, requires specific hardware (e.g., subgroup operation support), and has a high barrier to entry.

**NanoVG (Vulkan) & Skia Ganesh (Vulkan): Traditional & Mixed**

These mature engines offer more "traditional" but highly compatible solutions.

  • NanoVG: Usually employs two-pass rendering. The first pass renders all opaque objects. The second pass renders all transparent objects, often requiring manual sorting or enabling depth testing (though this affects transparency). Its Vulkan backend might use Framebuffer Objects (FBOs) to store intermediate results rather than storage images.
  • Skia Ganesh: Its Vulkan backend implements a variant of Depth Peeling. It uses multiple render passes, "peeling" the front-most transparent layer one by one, then compositing. This requires multiple Passes, but ensures correct visual results.
  • Commonality: They are more likely to rely on traditional blend modes (like premultiplied alpha blending) and depth testing (with limitations), and usually require CPU-side coarse sorting for complex overlapping scenes, which can be a performance bottleneck. Antialiasing mostly relies on MSAA or analytical methods.

⚙️ 2. Alternative Technical Solutions Analysis

In addition to coverage buffers, there are other classic and modern solutions for handling complex transparency.

1. A-Buffer & Per-Pixel Linked Lists (PPLL)

  • Principle: Maintains a linked list for each pixel, storing all fragments covering that pixel (color, depth). In the final pass, the list is traversed, sorted by depth, and composited.
  • Vulkan Implementation: Usually requires large amounts of video memory (storing list heads and nodes) and uses atomic operations to manage list insertion.
  • Comparison to TpvCanvas: Highest visual quality, perfectly handling all overlaps. But huge memory overhead, complex implementation, and list traversal can be a performance bottleneck. TpvCanvas's solution is a "Highest-Stamp+Coverage-Wins" simplification of this, using a single atomic operation to determine the pixel owner (highest 32-bit value wins) for extremely low memory and computational cost.

2. Depth Peeling & Variants

  • Principle: Uses multiple render passes. The first pass renders the nearest depth layer, the second renders the second-nearest (ignoring the first pass fragments), and so on. Finally, all layers are blended in correct order.
  • Comparison to TpvCanvas: High quality, order-independent. But Pass count scales linearly with depth complexity, leading to massive performance overhead. Skia's solution is a simplified version, peeling only a limited number of layers. TpvCanvas's single-pass atomic operation is far more efficient.

3. Stencil-based Techniques

  • Principle: Uses the Stencil Buffer to record pixel coverage. Each shape render updates the stencil value, and subsequent shapes decide whether to render based on the stencil value.
  • Comparison to TpvCanvas: Only suitable for limited numbers of layers (e.g., 2-3 layers). Cannot handle arbitrary overlaps, and antialiasing is difficult. TpvCanvas's coverage buffer is a more powerful and flexible version.

The following table summarizes the key trade-offs of these solutions.

Solution Memory Overhead Computational Overhead Implementation Complexity Visual Quality Best Scenario
Coverage-Mask-Then-Cover Low (1 Storage Image) Low (1 Atomic Write/Read) Medium High (SDF-AA) General High Performance, Text/UI
A-Buffer/PPLL Extremely High (List Storage) High (List Traversal/Sorting) Extremely High Perfect Offline/High-end Rendering with Extreme Quality Demands
Depth Peeling Medium (Multiple Depth/Color Buffers) Extremely High (Multiple Passes) Medium Perfect Scenes with Controllable High Depth Complexity
Stencil-based Low (Stencil Buffer) Low Simple Low (No AA) Very Simple 2-3 Layer Transparency

🔍 3. Deep Dive into Technical Questions

1. Storage Image & Layout

  • TpvCanvas: Uses VK_IMAGE_LAYOUT_GENERAL. This is the simplest layout, allowing read/write and arbitrary access, but may not be optimal. Transitioning to VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL (if read-only) in the barrier might offer minor performance gains, but is more complex.
  • Other Engines:
    • Pathfinder: Might use Sampled Images instead of storage images, since it often only needs to read pre-calculated coverage.
    • piet-gpu/vello: In compute shaders, might use Storage Buffers or Shared Memory for tile-local data, avoiding image layout issues entirely.

2. Shape ID Management and Wrapping

  • TpvCanvas: The 24-bit ID is compact and efficient. Periodic buffer clearing is acceptable, because the clear operation (vkCmdClearColorImage) is very fast, and when amortized over many shapes, the overhead is negligible. The key is to avoid frequent resets.
  • Alternatives:
    • Pathfinder: Uses depth values instead of IDs, avoiding ID space exhaustion, but requires depth sorting.
    • piet-gpu/vello: Uses local, short-lived IDs within tiles/warps, which never run out.
    • A-Buffer: Each fragment node stores full info; no ID concept.

3. Antialiasing Techniques (AA)

Technique Principle Quality Performance Difficulty Applicability
SDF-AA (TpvCanvas, Pathfinder, piet-gpu) Calculate Signed Distance Field, map to coverage ⭐⭐⭐⭐⭐ Very High ⭐⭐⭐⭐⭐ High (Calc once) ⭐⭐⭐⭐ Medium (Need geometry analysis) Top Choice for Vector Graphics, Text
MSAA (NanoVG, Skia) Multi-sample, resolve coverage ⭐⭐⭐⭐ High ⭐⭐⭐ Medium (High fill rate pressure) ⭐⭐⭐⭐⭐ Low (Hardware support) Traditional 3D Pipeline, Good Compatibility
Analytical AA (Pathfinder, Skia) Analyze geometry equations, calculate coverage area ⭐⭐⭐⭐ High ⭐⭐⭐⭐⭐ High (Analytical calc) ⭐⭐⭐⭐⭐ High (Math heavy) Simple Geometry, High Quality Requirements

TpvCanvas's SDF-AA is a core advantage. It generates perfect antialiased coverage for a shape in a single pass, integrates perfectly with the coverage mask, and is the best balance of performance and quality.

4. Render Pass & Barrier Overhead

  • Overhead of Pass Interruption: This concern is valid. vkCmdEndRenderPass and vkCmdBeginRenderPass are not zero-cost; they involve resource transitions and state setting inside the driver.
  • Amortizing Overhead: The key is batching. Do not interrupt the pass for every shape. Accumulate a batch of shapes (e.g., all transparent shapes in a frame), then execute the Mask -> Barrier -> Cover flow once. This way, the pass interruption overhead is amortized over thousands of shapes, becoming negligible.
  • Alternative with VK_EXT_fragment_shader_interlock: This extension allows fragment shaders to synchronize on a pixel region, theoretically avoiding pass interruption. However:
    • Hardware Support: Not all GPUs support this, especially mobile GPUs.
    • Performance Not Necessarily Better: Interlocking itself can introduce serialization and stalling; its benefit is highly hardware/workload dependent. For a simple "highest value wins" mode, global atomic operations (like TpvCanvas) are usually more efficient and simpler than fine-grained interlocking.
    • Complexity: Using extensions adds code complexity and compatibility testing burden.
    • Conclusion: For the specific algorithm of TpvCanvas, the current Pass Interruption + Barrier approach is the more pragmatic, efficient, and compatible choice.

5. Blending Modes

  • TpvCanvas: Uses Premultiplied Alpha Blending (VK_BLEND_FACTOR_ONE, VK_BLEND_FACTOR_ONE_MINUS_SRC_ALPHA). This is the standard best practice for handling transparency because it guarantees correct blending order (unpremultiplied alpha results vary by order).
  • Other Engines: Most also use premultiplied alpha blending. Both Skia and NanoVG use it extensively. A-Buffer and depth peeling also use premultiplied alpha blending in the final compositing stage.

6. Clip Regions

  • TpvCanvas: Calculates the shape's bounding box in the vertex shader and uses ClipRects in the fragment shader for early fragment rejection, avoiding expensive image loads and coverage calculations for fragments outside the clip region. This is a crucial performance optimization.
  • Other Engines:
    • Pathfinder: Applies clipping during the geometry decomposition stage.
    • piet-gpu/vello: Considers clipping during tile allocation, only processing tiles within the clip region.
    • NanoVG/Skia: May use Stencil Tests or Scissor Tests (hardware clipping) for clipping. Scissor Test is the most efficient but only handles axis-aligned rectangle clips. For complex clip paths, they might need intermediate buffers or rasterizing the clip shape.

📊 4. Comprehensive Trade-off Analysis

1. Performance Characteristics

Solution Fill Rate Pressure Geometry Complexity Pressure Memory Bandwidth Pressure Compute Pressure Best Scenario
TpvCanvas Low (Cover pass is bounding-box quad per shape with ClipRect culling) Low (Geometry only once) Medium (Read/Write coverage image) Low (Simple atomics/SDF calc) General 2D UI/Text, High FPS
Pathfinder Low (Ordered rendering) High (Decompose geometry) Low (Read mostly) Medium (Sorting/Analytical AA) Static or Semi-dynamic Content, High Visual Quality
piet-gpu/vello Very Low (Compute shader parallel) Very Low (Geometry handled in compute) Very Low (Local access) High (Parallel compute) Dynamic Content, Massive Parallelism, New Hardware
A-Buffer High (List node writes) Medium Extremely High (List R/W) High (List traversal/sort) Offline Rendering, Unlimited Overlap
Depth Peeling Extremely High (Multiple pass rendering) High (Multiple geometry processing) High (Multiple buffer R/W) Extremely High (Multiple Passes) Controllable Depth Complexity, High Precision

💡 Key Insight: TpvCanvas's design achieves an excellent balance between fill rate (Cover Pass) and compute (SDF-AA). Its performance bottleneck is typically memory bandwidth (reading/writing the coverage image), not compute or fill rate. This is especially friendly for bandwidth-constrained environments like mobile platforms.

2. Memory Footprint

Solution VRAM Usage Characteristics
TpvCanvas ~4MB (1080p) + Color Buffer Very Low. Just one fixed-size coverage image.
Pathfinder Variable (Geometry Buffers) Depends on scene complexity, potentially larger than TpvCanvas.
piet-gpu/vello Variable (Tile Buffers) Usually very efficient, but requires temporary compute memory.
A-Buffer Extremely High (One list per pixel) Can be hundreds of MB or even GB, proportional to depth complexity.
Depth Peeling Medium (Multiple Depth + Color Buffers) Depends on layers peeled (e.g., 3 layers = 3x depth + color buffer).

TpvCanvas's memory footprint is fixed and predictable, which is a huge advantage.

3. GPU Compatibility & Extension Requirements

Solution Vulkan Version/Extensions Required Hardware Requirements Compatibility
TpvCanvas Vulkan 1.0 (fragmentStoresAndAtomics) Most modern GPUs ⭐⭐⭐⭐⭐ Very High
Pathfinder Vulkan 1.0 Most modern GPUs ⭐⭐⭐⭐⭐ Very High
piet-gpu/vello Vulkan 1.1+ (VK_KHR_shader_subgroup etc.) Newer GPUs (Support subgroup ops) ⭐⭐⭐ Medium
A-Buffer Vulkan 1.0 GPUs with atomic support ⭐⭐⭐⭐ High
Depth Peeling Vulkan 1.0 Most modern GPUs ⭐⭐⭐⭐⭐ Very High

TpvCanvas has very loose hardware requirements, which is another advantage of it as a practical solution.

4. Mobile GPU Considerations

Mobile GPUs (e.g., Mali, Adreno) are typically Tile-Based Deferred Rendering (TBR) architectures. They have their own optimization strategies.

  • TpvCanvas Pass Interruption: On TBRs, the cost of pass interruption might be higher than on desktop GPUs because it may interrupt the tile rendering process. However, through batch processing, this cost can still be amortized. The access pattern of the coverage image (random read/write) is also a challenge for TBR's on-chip cache.
  • piet-gpu/vello Tile Method: Inherently fits TBR architecture perfectly because it organizes data by tiles in compute shaders, maximizing data reuse and on-chip cache efficiency. Has huge potential on mobile.
  • Bandwidth Sensitivity: Bandwidth is a scarce resource on mobile platforms. TpvCanvas's fixed memory usage and low bandwidth pressure (compared to A-Buffer) are huge advantages.

🎨 5. GLSL Code

Here is the GLSL fragment shader code snippet for TpvCanvas's Coverage-Mask-Then-Cover technique, illustrating the core logic for both the mask and cover passes, as well as premultiplied alpha handling.

text
/* Detailed source-code truncated for AI context efficiency. */

🎯 6. Conclusions and Recommendations

  1. TpvCanvas's Coverage-Mask-Then-Cover is an extremely efficient, practical, and high-quality solution. By combining atomic operations + SDF-AA, it achieves a near-perfect balance between performance, memory footprint, implementation complexity, and visual quality. It is particularly suitable for User Interfaces, text rendering, and 2D games where high frame rates are required.

  2. The overhead of Pass Interruption is not unacceptable. By batch processing transparent shapes (e.g., all shapes in a frame), the overhead of vkCmdEndRenderPass and vkCmdPipelineBarrier is amortized to a negligible level. This is a more robust choice than using complex extensions.

  3. For next-gen renderers, the compute shader tiling approach of piet-gpu/vello represents the future direction. It maximizes parallel efficiency, especially for dynamic content and new hardware. But its complexity and hardware requirements are current deployment obstacles.

  4. Pathfinder's geometry decomposition sorting offers another high-quality OIT path, avoiding storage image sync, but introducing potential CPU sorting bottlenecks. Suitable for static or semi-static high-quality rendering.

  5. Traditional methods like A-Buffer and Depth Peeling still have value for handling extreme depth complexity, but their performance and memory overhead make them unsuitable for general, real-time 2D rendering.

Recommendations:

  • If building a high-performance general-purpose 2D engine (like a UI framework or 2D game engine part), TpvCanvas's approach is an excellent starting point. It is proven, clear to implement, and highly compatible.
  • If pursuing ultimate mobile efficiency, research piet-gpu/vello's approach to see if one can move some computation (like coverage calc) to compute shaders and tile the data to leverage TBR architecture.
  • For Antialiasing, firmly stick to SDF-AA. It is the "silver bullet" for vector graphics antialiasing: high quality, good performance, and perfectly integrated with the coverage scheme.
  • Optimize ClipRects. Ensure early clipping tests in the fragment shader to avoid invalid image loads.
  • Monitor and optimize coverage buffer access patterns. Ensure shader code accesses images in a coalesced manner to maximize memory bandwidth utilization.

TpvCanvas's design demonstrates deep graphics expertise and a profound understanding of the Vulkan API. It cleverly transforms a complex problem into a simple, efficient, and robust solution, making it one of the exemplary models for modern vector graphics transparency handling.


Pascube Src Pasvulkan Docs Framepacing (`pascube_src/pasvulkan/docs/framepacing.md`)

Frame Pacing, Frame Rate Limiting, and Present Frame Latency in PasVulkan

This document describes the frame timing system in TpvApplication, implemented in PasVulkan.Application.pas. The system governs three orthogonal concerns:

  1. Present Frame Latency — GPU-CPU synchronization to control input-to-display latency
  2. Frame Pacing Mode — where the target frame interval comes from (the interval source)
  3. Frame Pacing Strategy — how the waiting/sleeping at frame end is performed (the timing method)

All three are independently configurable and interact through a well-defined pipeline within the frame loop.

Overview

The frame timing system is split into three orthogonal axes:

  • Present Frame Latency (TpvApplicationPresentFrameLatencyMode) — GPU-CPU synchronization (present wait and/or fence wait) to control input-to-display latency. Runs at frame start.
  • Frame Pacing Mode (TpvApplicationFramePacingMode) — where the target frame interval comes from (the interval source). Also runs at frame start, producing fFramePacingEffectiveInterval.
  • Frame Pacing Strategy (TpvApplicationFramePacingStrategy) — how the waiting/sleeping is performed (the timing method). Runs at frame end in FramePacingAndFrameRateLimiter, consuming the interval.

All three are independently configurable and can be combined freely. For example, one can use a monitor refresh rate query as the interval source together with an absolute time raster strategy for the sleeping, while using combined present+fence wait for latency control. Additionally, MaximumFramesPerSecond provides an explicit FPS cap that overrides the pacing interval when set.

Properties

Property Type Default Description
PresentFrameLatencyMode TpvApplicationPresentFrameLatencyMode CombinedWait GPU-CPU synchronization / latency reduction
PresentFrameLatency TpvUInt64 0 Number of present IDs to lag behind for PresentWait (0 = disabled)
FramePacingMode TpvApplicationFramePacingMode None Selects the interval source
FramePacingStrategy TpvApplicationFramePacingStrategy AbsoluteTimeRaster Selects the sleep/wait method
MaximumFramesPerSecond TpvDouble 0.0 Explicit FPS cap (overrides pacing interval when > 0)

Frame Loop Architecture

The three subsystems run at different points in the frame loop:

text
WaitForSwapChainLatency          ← (1) Present Frame Latency + (2) Interval Estimation
  │
  ├─ Present Wait phase          ← vkWaitForPresentKHR (latency control)
  ├─ Fence Wait phase            ← Pre-previous frame fence (latency control)
  └─ Interval Estimation         ← Computes fFramePacingEffectiveInterval
  │
AcquireVulkanBackBuffer
  │
Update → Draw → Present → PostPresent → inc(FrameCounter)
  │
FramePacingAndFrameRateLimiter   ← (3) Sleep at frame end using Strategy + Interval

WaitForSwapChainLatency runs at frame start (before CPU work begins) and handles both latency management and interval estimation. FramePacingAndFrameRateLimiter runs at frame end (after Present) and performs the actual sleep using the interval computed earlier. This "late pacing" pattern is more accurate than sleeping at frame start because the full frame duration is already known.

Both the Strict and Flexible processing modes call FramePacingAndFrameRateLimiter at the same position.


TpvApplicationPresentFrameLatencyMode — GPU-CPU Synchronization

Controls how the engine synchronizes with the GPU to manage input-to-display latency and frame throughput. This is the first thing that happens each frame, inside WaitForSwapChainLatency.

The mode combines two independent synchronization mechanisms:

Part 1: Present Wait (vkWaitForPresentKHR)

Uses VK_KHR_present_wait / VK_KHR_present_id to wait until a previously submitted frame has actually been presented on screen. This is the most direct way to control output latency.

Requirements: VK_KHR_present_id + VK_KHR_present_wait device support, VSync (FIFO) present mode, PresentFrameLatency > 0.

The wait target is: fVulkanPresentLastID - fPresentFrameLatency. So with PresentFrameLatency = 2, the engine waits until the frame submitted 2 presents ago has been shown.

Part 2: Frame Fence Wait (Pre-Previous Frame Fence)

A GPU fence-based synchronization point based on Sebastian Aaltonen's approach. Instead of waiting for the immediately previous frame's fence (N-1), the code waits for the frame before the previous one (N-2).

Rationale: Waiting for the N-2 fence gives lower overall latency than waiting for N-InFlightFrameCount, while still allowing up to 3 frames in flight. The simulation can write directly to GPU buffer data pointers since two frames of buffering are guaranteed. This is the best compromise between latency and throughput for most scenarios.

Edge case: Spiky CPU frames near 100% CPU+GPU utilization can cause GPU blast effects, but normally there is enough headroom to absorb this.

Enum Values

Value Ordinal Present Wait Fence Wait Description
None -1 No No No latency management. The fence wait is skipped entirely — the CPU runs ahead unconstrained.
Auto 0 Yes (if available) Yes (if PresentWait unavailable) Uses PresentWait when the driver supports it, falls back to fence wait otherwise.
PresentWait 1 Yes No Only vkWaitForPresentKHR. If supported, the fence wait is skipped (PresentWait already constrains the pipeline).
FenceWait 2 No Yes Only the pre-previous frame fence wait. Does not use vkWaitForPresentKHR.
CombinedWait 3 Yes Yes Both mechanisms active. PresentWait runs first, then the fence wait. Maximum latency control.

Decision Logic in WaitForSwapChainLatency

text
1. Present Wait phase:
   if mode in [Auto, PresentWait, CombinedWait]
      AND device supports PresentID + PresentWait
      AND PresentFrameLatency > 0
      AND VSync mode active
   then:
     vkWaitForPresentKHR(lastPresentID - PresentFrameLatency)

2. Fence Wait phase:
   if mode = None
      OR (mode in [Auto, PresentWait] AND PresentWait is available)
   then:
     Skip fence wait (already synchronized or no sync wanted)
   else:
     Wait for pre-previous frame fence (N-2 index)

Interaction with Frame Pacing

WaitForSwapChainLatency also contains the frame pacing interval estimation logic (the repeat...break block). This means the interval source estimation and the latency management both happen in the same function, before the frame's CPU work begins. The estimated interval is then consumed later by FramePacingAndFrameRateLimiter at the end of the frame.

TpvApplicationFramePacingMode — Interval Source

Determines how the target frame interval is obtained. The estimation runs inside WaitForSwapChainLatency, immediately after the latency synchronization phases. The result is stored in fFramePacingEffectiveInterval and consumed later by FramePacingAndFrameRateLimiter.

Enum Values

Value Ordinal Description
None 0 No frame pacing. Only the explicit FPS limiter (MaximumFramesPerSecond) is active, if set.
Auto 1 Tries all sources in priority order: VulkanPresentTiming → MonitorRefreshRate → PresentIntervalEstimation → 60 Hz fallback. Falls through automatically on failure.
MonitorRefreshRate 2 Queries the OS/windowing system for the monitor's refresh rate via GetNativeRefreshRate (SDL2 display mode query or Win32 API). No fallback if the query fails.
PresentIntervalEstimation 3 Estimates the display refresh interval from a running median of recent present-to-present frame intervals. Requires at least 4 history samples. No OS query.
VulkanPresentTiming 4 Uses VK_EXT_present_timing hardware data reported by the Vulkan driver. Most accurate when available.

Auto Mode Fallthrough

When Auto is selected, the estimation logic uses a repeat...break...until false pattern to try each source in order:

  1. VulkanPresentTiming — if the extension is available and reports a refresh duration, use it and stop.
  2. MonitorRefreshRate — query GetNativeRefreshRate. If it returns a valid rate (>= 1.0 Hz), use it and stop.
  3. PresentIntervalEstimation — if at least 4 history samples exist, compute the trimmed median. If the result is within the sanity range (8 ms–50 ms, i.e. 20–125 Hz), use it and stop.
  4. 60 Hz fallback — if nothing else worked, assume 60 Hz to avoid uncapped frame rates.

Present Interval Estimation Details

The software estimation collects frame-to-frame intervals in a ring buffer of 16 samples. It computes a robust interval estimate by:

  1. Copying and sorting the recent samples (insertion sort, max 16 elements).
  2. Computing the trimmed mean over the interquartile range (discarding the lowest and highest quartiles).
  3. Applying a sanity check: only accepting the result if it falls between 8 ms (125 Hz) and 50 ms (20 Hz).

This runs inside WaitForSwapChainLatency, before the frame loop reaches FramePacingAndFrameRateLimiter.

TpvApplicationFramePacingStrategy — Wait Method

Determines how the actual sleeping is performed in FramePacingAndFrameRateLimiter at the end of each frame.

Enum Values

Value Ordinal Description
DeviationCompensation 0 Reactive per-frame sleep with cumulative deviation tracking.
AbsoluteTimeRaster 1 Fixed absolute deadline grid with catch-up skip logic. Default.

DeviationCompensation Strategy

The reactive frame rate limiter. For each frame:

  1. Compute FrameTime = NowTime - LastTime.
  2. Compute SleepDuration = TargetInterval - (FrameTime + AccumulatedDeviation).
  3. If SleepDuration > 0, sleep via TpvHighResolutionTimerSleepWithDriftCompensation.
  4. After waking, recalculate the actual frame time and update the deviation: Deviation := min(TargetInterval/16, Deviation + (ActualFrameTime - TargetInterval)).
  5. If a frame was slow (> ~103% of target adjusted for deviation), reset the deviation to 0 to avoid compensating for genuinely slow frames later.

Characteristics:

  • Adapts to varying frame times reactively.
  • Can accumulate small drift over long periods since the time base is relative (frame-to-frame).
  • Good for scenarios where frame times fluctuate moderately.

AbsoluteTimeRaster Strategy

A fixed-grid temporal schedule. Instead of sleeping for a relative duration, the code maintains an absolute deadline (fFramePacingNextPresentTarget) that advances by exactly TargetInterval each frame.

For each frame:

  1. Advance the deadline: NextDeadline := NextDeadline + TargetInterval.
  2. Frame finished early (NowTime < NextDeadline): Sleep until the absolute deadline via fFramePacingSleepWithDriftCompensation.
  3. Frame finished late (NowTime >= NextDeadline): Compute how many deadline slots were missed: Skipped := (LateAmount div TargetInterval) + 1. Jump the deadline forward: NextDeadline := NextDeadline + (Skipped * TargetInterval). No catch-up bursts.
  4. On first frame or after a reset (swapchain recreate), initialize the deadline to NowTime + TargetInterval.

Characteristics:

  • No cumulative drift — the deadline is anchored to an absolute time base.
  • Provides a stable long-term frame cadence.
  • Gracefully handles slow frames by skipping missed slots rather than accumulating debt.
  • The deadline resets automatically when fFramePacingNextPresentTarget is set to 0 (constructor, swapchain recreate).

Target Interval Priority

FramePacingAndFrameRateLimiter determines the TargetInterval in this priority order:

  1. MaximumFramesPerSecond — if > 0, compute TargetInterval := 1.0 / MaximumFramesPerSecond. This always takes priority.
  2. fFramePacingEffectiveInterval — if > 0, use the interval estimated by the frame pacing mode logic in WaitForSwapChainLatency.
  3. Neither — TargetInterval := 0, no throttling occurs.

Call Position in the Frame Loop

FramePacingAndFrameRateLimiter is called at the end of each frame, after PresentVulkanBackBuffer and PostPresent:

text
Update → Draw → PresentVulkanBackBuffer → PostPresent → inc(FrameCounter) → FramePacingAndFrameRateLimiter

This is the "late pacing" pattern. Because the call happens after Present, the code already knows the full duration of the current frame before deciding how long to sleep. This is more accurate than sleeping at the frame start, where one would have to estimate based on the previous frame.

Both the Strict and Flexible processing modes call FramePacingAndFrameRateLimiter at the same position.

Relevant Fields

Frame Rate Limiter State

Field Type Description
fFrameRateLimiterLastTime TpvHighResolutionTime Timestamp of the previous frame's limiter call
fFrameRateLimiterDeviation TpvHighResolutionTime Accumulated deviation for DeviationCompensation strategy
fFrameLimiterHighResolutionTimerSleepWithDriftCompensation TpvHighResolutionTimerSleepWithDriftCompensation Sleep helper for DeviationCompensation (Welford + busy-wait tail)

Frame Pacing State

Field Type Description
fFramePacingMode TpvApplicationFramePacingMode Current interval source mode
fFramePacingStrategy TpvApplicationFramePacingStrategy Current wait method
fFramePacingEffectiveInterval TpvInt64 Computed pacing interval, consumed by FramePacingAndFrameRateLimiter
fFramePacingNextPresentTarget TpvInt64 Absolute deadline for AbsoluteTimeRaster strategy
fFramePacingLastPresentTime TpvInt64 Last present timestamp for history recording
fFramePacingHistory array[0..15] of TpvInt64 Ring buffer of recent present-to-present intervals
fFramePacingHistoryIndex TpvInt32 Write index into the history ring buffer
fFramePacingHistoryCount TpvInt32 Number of valid samples in the history (max 16)
fFramePacingSleepWithDriftCompensation TpvHighResolutionTimerSleepWithDriftCompensation Sleep helper for AbsoluteTimeRaster strategy
fFramePacingPresentTimingRefreshDuration TpvUInt64 Refresh duration from VK_EXT_present_timing (nanoseconds)
fFramePacingPresentTimingAvailable boolean Whether VK_EXT_present_timing data is available

MaximumFramesPerSecond

Field Type Description
fMaximumFramesPerSecond TpvDouble Explicit FPS cap. 0.0 = disabled. Takes priority over pacing interval.

Present Frame Latency State

Field Type Description
fPresentFrameLatencyMode TpvApplicationPresentFrameLatencyMode Current latency management mode
fPresentFrameLatency TpvUInt64 Number of present IDs to lag behind for PresentWait. 0 = disabled.
fVulkanPresentLastID TpvUInt64 Monotonically increasing present ID, incremented on each vkQueuePresentKHR
fVulkanFrameFences array[0..3] of TpvVulkanFence Ring buffer of 4 frame fences for fence-based latency management
fVulkanFrameFenceCounter TpvUInt32 Write index into the frame fence ring buffer
fVulkanFrameFencesReady TpvUInt32 Bitmask tracking which fences have been signaled

Reset Behavior

The frame pacing state is reset in these situations:

  • Constructor (TpvApplication.Create): All fields initialized to zero/default. fFramePacingStrategy defaults to AbsoluteTimeRaster. fPresentFrameLatencyMode defaults to CombinedWait.
  • Swapchain recreate (CreateVulkanSwapChain): fFramePacingNextPresentTarget, fFramePacingLastPresentTime, history counters, and fFramePacingDriftAccumulator are reset to 0. fFramePacingSleepWithDriftCompensation is reset. This forces the AbsoluteTimeRaster strategy to re-anchor its deadline on the next frame.

Typical Configurations

Use Case PresentFrameLatencyMode FramePacingMode FramePacingStrategy MaximumFramesPerSecond
No pacing, no cap, no latency control None None (ignored) 0
Low-latency VSync CombinedWait Auto AbsoluteTimeRaster 0
Explicit 60 FPS cap CombinedWait None AbsoluteTimeRaster 60
Auto-detect refresh, stable grid CombinedWait Auto AbsoluteTimeRaster 0
VSync + monitor Hz pacing FenceWait MonitorRefreshRate AbsoluteTimeRaster 0
Legacy reactive pacing FenceWait Auto DeviationCompensation 0
Fixed 144 FPS cap, reactive CombinedWait None DeviationCompensation 144
Uncapped (benchmark) None None (ignored) 0

Pascube Src Pasvulkan Docs Memory Management In Pasvulkan (`pascube_src/pasvulkan/docs/memory_management_in_pasvulkan.md`)

Vulkan memory management in PasVulkan

Memory management in Vulkan is a complex and intricate process that gives developers control over how graphics memory is allocated and used. The primary principle of Vulkan's memory management is that it offers a lower-level interface to the GPU than APIs like OpenGL, entrusting developers with the responsibility of managing memory allocations themselves. This can lead to more efficient use of memory and enhanced performance, but it also necessitates a deeper understanding of how the GPU operates and the optimal way to manage its resources.

In Vulkan, memory is organized in a hierarchy that includes heaps, memory types, and memory property flags. Heaps are fixed-size memory resources exposed by the device, and each heap can support different memory types. When creating a resource like a buffer, Vulkan provides information about which memory types are compatible with that resource. Depending on the resource's usage flags, the developer must select the right memory type and, based on that type, the appropriate heap.

Memory can be host-visible (accessible by the CPU and potentially slower) or device-local (residing on the GPU and generally faster but not host-visible). The latter type of memory often requires the use of a staging resource or the GPU itself to write data to it. Many new systems with Unified Memory Architecture (UMA) and/or PCIe Resizable BAR (ReBAR) support can have both cases simultaneously.

Vulkan requires developers to manage memory alignment and address the possibility that different resources may alias (share) the same region of memory. Resources may also need to be sub-allocated, where a larger allocation is partitioned into smaller ones. This enables efficient reuse of existing allocations and improved cache utilization.

Libraries like the Vulkan Memory Allocator (VMA) by GPUOpen/AMD, which provide higher-level functions to assist with Vulkan memory management, do exist. VMA offers functionalities like choosing the correct and optimal memory type based on intended usage, allocating memory blocks and reserving parts of them, and creating an image/buffer, allocating memory for it, and binding them together - all in one call.

However, PasVulkan uses its own custom memory management, which predates the first public release of VMA. It manages Vulkan memory by working with memory blocks and memory chunks. A memory block is a small region within one allocation, and a memory chunk is a memory region that encompasses a list of blocks and represents a single allocation. A chunk can allocate a block, deallocate a block, and check if a block is within the chunk. A chunk allocates its memory within the constructor, and when a deallocation occurs, it merely marks the block as free. Memory alignment is automatically managed in PasVulkan's allocation process.

The core idea

The allocation policy in PasVulkan employs a memory management algorithm that uses two red-black trees to manage free memory blocks within a heap: One sorted by address and another by size.

To comprehend the effectiveness of PasVulkan's allocation policy, we need to scrutinize its key operations: allocation, deallocation, and reallocation.

  1. Allocation: The algorithm initially searches the size tree for the smallest block that is equal to or larger than the required size. If the found block is larger than the necessary size, it's divided into two blocks: the larger block is returned to the size tree for future allocations, and the smaller block of the required size is returned to the caller. If the block found is precisely the required size, it's removed from both trees and returned to the caller. If a sufficient block isn't found, a new Vulkan heap block is allocated, and the whole operation is repeated. The time complexity for these operations is O(log n) due to the search and insertion operations in the red-black trees.

  2. Deallocation: The deallocated memory blocks are returned to the address tree. Each node along the path to the insertion point for the new node is examined to see if it adjoins the node being inserted. If so, the nodes are merged, and the merged node is relocated in the size tree. If not, the node is inserted in both trees. After insertion, the trees are checked for correct balancing. Once again, these operations are performed in O(log n) time.

  3. Reallocation (not implemented in this use case): If the size of the reallocated block is larger than the original block, the original block is returned to the free trees so that any possible coalescence can occur. A new block of the requested size is then allocated, the data is moved from the original block to the new block, and the new block is returned to the caller. If the size of the reallocated block is smaller than the original block, the block is split, and the remainder is returned to the free tree. The time complexity for these operations is also O(log n).

Advantages

PasVulkan's allocation policy possesses a few key advantages:

  1. Fast operations: The use of red-black trees guarantees that all primary operations (allocation, deallocation, and reallocation) have a time complexity of O(log n), which is efficient for a large number of nodes. Red-black trees are self-balancing binary search trees, which means that they maintain their balance after insertions and deletions, ensuring that no path in the tree is more than twice as long as any other. This feature is crucial for rapid execution of tree operations.

  2. Efficient use of memory: The algorithm endeavors to find the smallest possible block that meets the size requirement, which can help minimize memory waste. During memory deallocation, the algorithm checks if the block adjoins another free block and merges them if possible, which can help avert fragmentation and optimize memory use.

  3. Scalability: PasVulkan's allocation policy can efficiently handle the expansion of the heap by adding the expanded block to the size and address trees and continuing the allocation process as before.

Drawbacks

However, it's crucial to note that this policy also has some potential drawbacks:

  1. Overhead: The use of two red-black trees for managing memory can introduce some overhead, both in terms of memory (for maintaining the tree structures) and time (for performing tree operations). This overhead may not be a concern for applications with ample memory and CPU power, but it could be significant for more constrained environments.

  2. Memory fragmentation: Although PasVulkan's allocation policy attempts to minimize fragmentation by merging adjoining free blocks during deallocation, it cannot completely prevent fragmentation. When blocks of memory are allocated and deallocated randomly, it can lead to a situation where the memory is divided into small, non-contiguous free blocks, even if the total amount of free memory is sufficient for a requested allocation. This fragmentation can render memory use inefficient and potentially lead to allocation failures.

  3. Complications with reallocation (which can be negligible here, since PasVulkan does not yet implement real reallocation at the GPU memory level): When reallocating memory, the original block is freed, and a new block is allocated. This process involves moving the data from the original block to the new block, which can be time-consuming for large amounts of data. Moreover, if the memory has become fragmented, it may be challenging to find a large enough contiguous block for the reallocation, leading to allocation failures or the need to allocate another new native Vulkan heap block.

Conclusion

Despite these potential drawbacks, PasVulkan's allocation policy can be an effective memory management strategy for many applications. Its use of red-black trees to manage memory can provide efficient allocation and deallocation operations, and its strategies for finding the smallest sufficient block and merging adjoining free blocks can contribute to efficient memory use.

The effectiveness of PasVulkan's allocation policy can vary depending on the specific requirements and constraints of the application, including the amount of available GPU memory, the frequency and size of allocation and deallocation operations, and the tolerance for overhead. Of course, other allocation policies exist, such as stack allocators, ring buffer-like allocators, and TLSF, which can potentially outperform PasVulkan's allocation policy in many situations. These policies justify their existence through their performance/benefit ratios, but PasVulkan's allocation policy aims to be generally applicable. It's also possible that PasVulkan will support other more specialized fine-tuned allocation policies in the future. After all, one never knows what the future holds. :-)


Pascube Src Pasvulkan Docs Pocascriptapi (`pascube_src/pasvulkan/docs/pocascriptapi.adoc`)

= PasVulkan POCA Script API Documentation
:toc:
:toc-placement: preamble
:toclevels: 3
:showtitle:
:!webfonts:

// Need some preamble to get TOC:
{empty}

== Overview

This document describes the PasVulkan-specific extensions to the POCA scripting API. PasVulkan provides a comprehensive set of types and functions for 2D/3D graphics, mathematics, input handling, and sprite management within POCA scripts.

For the base POCA scripting API (Array, Boolean, Console, etc.), please refer to link:https://github.com/BeRo1985/poca/blob/master/docs/scriptapi.adoc[POCA Script API Documentation].

'''''

== Vector2

=== Overview

The Vector2 type represents a 2-dimensional vector with x and y components. It is exposed as a ghost object in POCA scripts and provides comprehensive vector mathematics operations.

'''''

=== Global Vector2 Object

==== Vector2.create()

Usage:

[source,js]

let vec = Vector2.create(x, y);

  • Description: Creates a new 2D vector with the specified x and y components.
  • Parameters:
    ** +x+ (number): The x component of the vector (default: 0.0)
    ** +y+ (number): The y component of the vector (default: 0.0)
  • Return Value: A new Vector2 object.
  • Example:

[source,js]

let position = Vector2.create(10.5, 20.3); let origin = Vector2.create(); // (0, 0)

'''''

=== Vector2 Properties

==== x, r

Usage:

[source,js]

let xValue = vec.x; vec.x = 5.0; let rValue = vec.r; // Same as x

  • Description: Gets or sets the x component of the vector. The +r+ property is an alias for +x+.
  • Type: number
  • Example:

[source,js]

let vec = Vector2.create(3, 4); vec.x = 10; puts("X component: " + vec.x);

'''''

==== y, g

Usage:

[source,js]

let yValue = vec.y; vec.y = 5.0; let gValue = vec.g; // Same as y

  • Description: Gets or sets the y component of the vector. The +g+ property is an alias for +y+.
  • Type: number
  • Example:

[source,js]

let vec = Vector2.create(3, 4); vec.y = 8; puts("Y component: " + vec.y);

'''''

=== Vector2 Methods

==== length()

Usage:

[source,js]

let len = vec.length();

  • Description: Returns the Euclidean length (magnitude) of the vector.
  • Parameters: None.
  • Return Value: The length of the vector as a number.
  • Example:

[source,js]

let vec = Vector2.create(3, 4); let len = vec.length(); // Returns 5.0

'''''

==== squaredLength()

Usage:

[source,js]

let sqLen = vec.squaredLength();

  • Description: Returns the squared length of the vector. This is more efficient than +length()+ when you only need to compare lengths.
  • Parameters: None.
  • Return Value: The squared length of the vector.
  • Example:

[source,js]

let vec = Vector2.create(3, 4); let sqLen = vec.squaredLength(); // Returns 25.0

'''''

==== normalize()

Usage:

[source,js]

vec.normalize();

  • Description: Normalizes the vector in place, making it a unit vector (length = 1).
  • Parameters: None.
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let vec = Vector2.create(3, 4); vec.normalize(); // vec is now (0.6, 0.8)

'''''

==== dot(other)

Usage:

[source,js]

let dotProduct = vec.dot(otherVec);

  • Description: Computes the dot product of this vector with another vector.
  • Parameters:
    ** +other+ (Vector2): The other vector.
  • Return Value: The dot product as a number.
  • Example:

[source,js]

let v1 = Vector2.create(1, 0); let v2 = Vector2.create(0, 1); let dot = v1.dot(v2); // Returns 0.0

'''''

==== cross(other)

Usage:

[source,js]

let crossProduct = vec.cross(otherVec);

  • Description: Computes the 2D cross product (z component of the 3D cross product) with another vector.
  • Parameters:
    ** +other+ (Vector2): The other vector.
  • Return Value: The cross product as a number.
  • Example:

[source,js]

let v1 = Vector2.create(1, 0); let v2 = Vector2.create(0, 1); let cross = v1.cross(v2); // Returns 1.0

'''''

==== distanceTo(other)

Usage:

[source,js]

let distance = vec.distanceTo(otherVec);

  • Description: Computes the Euclidean distance between this vector and another vector.
  • Parameters:
    ** +other+ (Vector2): The other vector.
  • Return Value: The distance as a number.
  • Example:

[source,js]

let v1 = Vector2.create(0, 0); let v2 = Vector2.create(3, 4); let dist = v1.distanceTo(v2); // Returns 5.0

'''''

==== lerp(other, t)

Usage:

[source,js]

let result = vec.lerp(otherVec, t);

  • Description: Performs linear interpolation between this vector and another vector, modifying this vector in place.
  • Parameters:
    ** +other+ (Vector2): The target vector.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let v1 = Vector2.create(0, 0); let v2 = Vector2.create(10, 10); v1.lerp(v2, 0.5); // v1 is now (5, 5)

'''''

==== nlerp(other, t)

Usage:

[source,js]

let result = vec.nlerp(otherVec, t);

  • Description: Performs normalized linear interpolation between this vector and another vector, modifying this vector in place.
  • Parameters:
    ** +other+ (Vector2): The target vector.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).

'''''

==== slerp(other, t)

Usage:

[source,js]

let result = vec.slerp(otherVec, t);

  • Description: Performs spherical linear interpolation between this vector and another vector, modifying this vector in place.
  • Parameters:
    ** +other+ (Vector2): The target vector.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).

'''''

==== sqlerp(other, t)

Usage:

[source,js]

let result = vec.sqlerp(b, c, d, t);

  • Description: Performs squared spherical linear interpolation (squad), modifying this vector in place.
  • Parameters:
    ** +b+ (Vector2): Second control point.
    ** +c+ (Vector2): Third control point.
    ** +d+ (Vector2): Fourth control point.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).

'''''

==== clone()

Usage:

[source,js]

let copy = vec.clone();

  • Description: Creates a copy of this vector.
  • Parameters: None.
  • Return Value: A new Vector2 with the same components.
  • Example:

[source,js]

let original = Vector2.create(5, 10); let copy = original.clone();

'''''

==== copy(other)

Usage:

[source,js]

vec.copy(otherVec);

  • Description: Copies the components from another vector to this vector.
  • Parameters:
    ** +other+ (Vector2): The vector to copy from.
  • Return Value: The vector itself.

'''''

==== add(other)

Usage:

[source,js]

vec.add(otherVec);

  • Description: Adds another vector to this vector in place.
  • Parameters:
    ** +other+ (Vector2 or number): The vector or scalar to add.
  • Return Value: The vector itself.
  • Example:

[source,js]

let vec = Vector2.create(1, 2); vec.add(Vector2.create(3, 4)); // vec is now (4, 6)

'''''

==== sub(other)

Usage:

[source,js]

vec.sub(otherVec);

  • Description: Subtracts another vector from this vector in place.
  • Parameters:
    ** +other+ (Vector2 or number): The vector or scalar to subtract.
  • Return Value: The vector itself.

'''''

==== mul(value)

Usage:

[source,js]

vec.mul(scalar); vec.mul(otherVec); vec.mul(matrix);

  • Description: Multiplies this vector by a scalar, another vector (component-wise), or transforms it by a matrix, in place.
  • Parameters:
    ** +value+ (number, Vector2, Matrix3x3, or Matrix4x4): The value to multiply/transform by.
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let vec = Vector2.create(2, 3);
vec.mul(2); // vec is now (4, 6)

let vec2 = Vector2.create(1, 2);
vec2.mul(Vector2.create(3, 4)); // vec2 is now (3, 8)

let transform = Matrix3x3.create(/* ... */); vec.mul(transform); // Transform vec by matrix

'''''

==== div(value)

Usage:

[source,js]

vec.div(scalar);

  • Description: Divides this vector by a scalar or another vector (component-wise) in place.
  • Parameters:
    ** +value+ (number or Vector2): The scalar or vector to divide by.
  • Return Value: The vector itself.

'''''

==== neg()

Usage:

[source,js]

vec.neg();

  • Description: Negates this vector in place.
  • Parameters: None.
  • Return Value: The vector itself.
  • Example:

[source,js]

let vec = Vector2.create(3, -4); vec.neg(); // vec is now (-3, 4)

'''''

==== equal(other)

Usage:

[source,js]

let isEqual = vec.equal(otherVec);

  • Description: Checks if this vector equals another vector.
  • Parameters:
    ** +other+ (Vector2): The vector to compare with.
  • Return Value: 1 if equal, 0 otherwise.

'''''

==== notEqual(other)

Usage:

[source,js]

let isNotEqual = vec.notEqual(otherVec);

  • Description: Checks if this vector is not equal to another vector.
  • Parameters:
    ** +other+ (Vector2): The vector to compare with.
  • Return Value: 1 if not equal, 0 otherwise.

'''''

==== toString()

Usage:

[source,js]

let str = vec.toString();

  • Description: Converts the vector to a string representation.
  • Parameters: None.
  • Return Value: A string representation of the vector.
  • Example:

[source,js]

let vec = Vector2.create(3.5, 4.2); puts(vec.toString()); // Outputs something like "(3.5, 4.2)"

'''''

=== Operator Overloading

Vector2 supports operator overloading for common mathematical operations:

  • Addition: +vec1 + vec2+ or +vec + scalar+
  • Subtraction: +vec1 - vec2+ or +vec - scalar+
  • Multiplication: +vec * scalar+, +vec1 * vec2+, +vec * matrix+, or +matrix * vec+
    ** Supports Matrix3x3 and Matrix4x4 transformations in both orders
  • Division: +vec / scalar+ or +vec1 / vec2+
  • Negation: +-vec+
  • Equality: +vec1 == vec2+
  • Inequality: +vec1 != vec2+

Example:

[source,js]

let v1 = Vector2.create(1, 2);
let v2 = Vector2.create(3, 4);
let sum = v1 + v2; // (4, 6)
let scaled = v1 * 2; // (2, 4)

let transform = Matrix3x3.create(/* ... */); let transformed = v1 * transform; // Transform vector

'''''

== Vector3

=== Overview

The Vector3 type represents a 3-dimensional vector with x, y, and z components. It provides similar functionality to Vector2 but for 3D space.

'''''

=== Global Vector3 Object

==== Vector3.create()

Usage:

[source,js]

let vec = Vector3.create(x, y, z);

  • Description: Creates a new 3D vector with the specified x, y, and z components.
  • Parameters:
    ** +x+ (number): The x component (default: 0.0)
    ** +y+ (number): The y component (default: 0.0)
    ** +z+ (number): The z component (default: 0.0)
  • Return Value: A new Vector3 object.
  • Example:

[source,js]

let position = Vector3.create(10, 20, 30); let origin = Vector3.create(); // (0, 0, 0)

'''''

=== Vector3 Properties

==== x, r / y, g / z, b

Usage:

[source,js]

let xValue = vec.x; // or vec.r let yValue = vec.y; // or vec.g let zValue = vec.z; // or vec.b vec.x = 5.0; vec.y = 10.0; vec.z = 15.0;

  • Description: Gets or sets the x, y, or z components of the vector. The +r+, +g+, and +b+ properties are aliases for +x+, +y+, and +z+ respectively.
  • Type: number

'''''

=== Vector3 Methods

==== length()

Usage:

[source,js]

let len = vec.length();

  • Description: Calculates and returns the Euclidean length (magnitude) of the vector.
  • Parameters: None.
  • Return Value: The length of the vector as a number.
  • Example:

[source,js]

let vec = Vector3.create(3, 4, 0); let len = vec.length(); // Returns 5.0

'''''

==== squaredLength()

Usage:

[source,js]

let sqLen = vec.squaredLength();

  • Description: Returns the squared length of the vector. This is faster than +length()+ since it avoids the square root operation.
  • Parameters: None.
  • Return Value: The squared length as a number.
  • Example:

[source,js]

let vec = Vector3.create(3, 4, 0); let sqLen = vec.squaredLength(); // Returns 25.0

'''''

==== normalize()

Usage:

[source,js]

vec.normalize();

  • Description: Normalizes the vector in place (converts it to unit length while preserving direction).
  • Parameters: None.
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let vec = Vector3.create(3, 4, 0); vec.normalize(); // vec is now approximately (0.6, 0.8, 0.0)

'''''

==== dot()

Usage:

[source,js]

let dotProduct = vec.dot(other);

  • Description: Computes the dot product (scalar product) with another vector.
  • Parameters:
    ** +other+ (Vector3): The other vector.
  • Return Value: The dot product as a number.
  • Example:

[source,js]

let v1 = Vector3.create(1, 0, 0); let v2 = Vector3.create(0, 1, 0); let dot = v1.dot(v2); // Returns 0.0 (perpendicular)

'''''

==== cross()

Usage:

[source,js]

let result = vec.cross(other);

  • Description: Computes the cross product with another vector, returning a new Vector3 perpendicular to both vectors.
  • Parameters:
    ** +other+ (Vector3): The other vector.
  • Return Value: The same Vector3 representing the cross product.
  • Example:

[source,js]

let v1 = Vector3.create(1, 0, 0); let v2 = Vector3.create(0, 1, 0); let cross = v1.cross(v2); // Returns Vector3(0, 0, 1)

'''''

==== distanceTo()

Usage:

[source,js]

let dist = vec.distanceTo(other);

  • Description: Calculates the distance to another vector.
  • Parameters:
    ** +other+ (Vector3): The other vector.
  • Return Value: The distance as a number.
  • Example:

[source,js]

let v1 = Vector3.create(0, 0, 0); let v2 = Vector3.create(3, 4, 0); let dist = v1.distanceTo(v2); // Returns 5.0

'''''

==== lerp()

Usage:

[source,js]

let result = vec.lerp(other, t);

  • Description: Performs linear interpolation between this vector and another, modifying this vector in place.
  • Parameters:
    ** +other+ (Vector3): The target vector.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let start = Vector3.create(0, 0, 0); let end = Vector3.create(10, 10, 10); start.lerp(end, 0.5); // start is now (5, 5, 5)

'''''

==== nlerp()

Usage:

[source,js]

let result = vec.nlerp(other, t);

  • Description: Performs normalized linear interpolation (lerp followed by normalization), modifying this vector in place.
  • Parameters:
    ** +other+ (Vector3): The target vector.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).

'''''

==== slerp()

Usage:

[source,js]

let result = vec.slerp(other, t);

  • Description: Performs spherical linear interpolation between this vector and another, maintaining constant angular velocity, modifying this vector in place.
  • Parameters:
    ** +other+ (Vector3): The target vector.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).

'''''

==== sqlerp()

Usage:

[source,js]

let result = vec.sqlerp(b, c, d, t);

  • Description: Performs squared spherical linear interpolation (squad), modifying this vector in place.
  • Parameters:
    ** +b+ (Vector3): Second control point.
    ** +c+ (Vector3): Third control point.
    ** +d+ (Vector3): Fourth control point.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).

'''''

==== clone()

Usage:

[source,js]

let copy = vec.clone();

  • Description: Creates a new vector with the same values as this one.
  • Parameters: None.
  • Return Value: A new Vector3 object.
  • Example:

[source,js]

let original = Vector3.create(1, 2, 3); let copy = original.clone(); copy.x = 5; // original is unchanged

'''''

==== copy()

Usage:

[source,js]

vec.copy(other);

  • Description: Copies the values from another vector into this one.
  • Parameters:
    ** +other+ (Vector3): The vector to copy from.
  • Return Value: The vector itself (for method chaining).

'''''

==== add()

Usage:

[source,js]

let result = vec.add(other);

  • Description: Adds another vector or scalar to this vector.
  • Parameters:
    ** +other+ (Vector3 or number): The vector or scalar to add.
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let v1 = Vector3.create(1, 2, 3); let v2 = Vector3.create(4, 5, 6); v1.add(v2); // v1 is now (5, 7, 9)

'''''

==== sub()

Usage:

[source,js]

let result = vec.sub(other);

  • Description: Subtracts another vector or scalar from this vector.
  • Parameters:
    ** +other+ (Vector3 or number): The vector or scalar to subtract.
  • Return Value: The vector itself (for method chaining).

'''''

==== mul()

Usage:

[source,js]

let result = vec.mul(value);

  • Description: Multiplies this vector by another vector, scalar, matrix, or quaternion.
  • Parameters:
    ** +value+ (Vector3, number, Matrix3x3, Matrix4x4, or Quaternion): The value to multiply/transform by.
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let vec = Vector3.create(1, 2, 3);
vec.mul(2); // vec is now (2, 4, 6)

let mat = Matrix4x4.create(/* ... */);
vec.mul(mat); // Transform vec by matrix

let rot = Quaternion.create(/* ... */); vec.mul(rot); // Rotate vec by quaternion

'''''

==== div()

Usage:

[source,js]

let result = vec.div(value);

  • Description: Divides this vector by another vector or scalar.
  • Parameters:
    ** +value+ (Vector3 or number): The vector or scalar to divide by.
  • Return Value: The vector itself (for method chaining).

'''''

==== neg()

Usage:

[source,js]

let result = vec.neg();

  • Description: Negates this vector (all components multiplied by -1).
  • Parameters: None.
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let vec = Vector3.create(1, -2, 3); vec.neg(); // vec is now (-1, 2, -3)

'''''

==== equal()

Usage:

[source,js]

let isEqual = vec.equal(other);

  • Description: Checks if this vector is equal to another vector.
  • Parameters:
    ** +other+ (Vector3): The vector to compare with.
  • Return Value: 1 if equal, 0 otherwise.

'''''

==== notEqual()

Usage:

[source,js]

let notEqual = vec.notEqual(other);

  • Description: Checks if this vector is not equal to another vector.
  • Parameters:
    ** +other+ (Vector3): The vector to compare with.
  • Return Value: 1 if not equal, 0 otherwise.

'''''

==== toString()

Usage:

[source,js]

let str = vec.toString();

  • Description: Converts the vector to a string representation.
  • Parameters: None.
  • Return Value: A string representation of the vector.
  • Example:

[source,js]

let vec = Vector3.create(1.5, 2.5, 3.5); puts(vec.toString()); // Outputs something like "(1.5, 2.5, 3.5)"

'''''

=== Vector3 Operator Overloading

Vector3 supports operator overloading with extended multiplication support:

  • Addition: +vec1 + vec2+ or +vec + scalar+
  • Subtraction: +vec1 - vec2+ or +vec - scalar+
  • Multiplication: +vec * scalar+, +vec1 * vec2+, +vec * matrix+, +vec * quat+, or +matrix/quat * vec+
    ** Supports Matrix3x3, Matrix4x4, and Quaternion transformations in both orders
  • Division: +vec / scalar+ or +vec1 / vec2+
  • Negation: +-vec+
  • Equality: +vec1 == vec2+
  • Inequality: +vec1 != vec2+

Example:

[source,js]

let v = Vector3.create(1, 0, 0); let rotation = Quaternion.create(/* ... */); let rotated = v * rotation; // Rotate vector let backRotated = rotation * v; // Also works

'''''

== Vector4

=== Overview

The Vector4 type represents a 4-dimensional vector with x, y, z, and w components. Commonly used for colors (RGBA) or homogeneous coordinates.

'''''

=== Global Vector4 Object

==== Vector4.create()

Usage:

[source,js]

let vec = Vector4.create(x, y, z, w);

  • Description: Creates a new 4D vector.
  • Parameters:
    ** +x+ (number): The x component (default: 0.0)
    ** +y+ (number): The y component (default: 0.0)
    ** +z+ (number): The z component (default: 0.0)
    ** +w+ (number): The w component (default: 0.0)
  • Return Value: A new Vector4 object.
  • Example:

[source,js]

let color = Vector4.create(1.0, 0.0, 0.0, 1.0); // Red color

'''''

=== Vector4 Properties

  • +x+, +r+: First component
  • +y+, +g+: Second component
  • +z+, +b+: Third component
  • +w+, +a+: Fourth component

'''''

=== Vector4 Methods

==== length()

Usage:

[source,js]

let len = vec.length();

  • Description: Calculates and returns the Euclidean length (magnitude) of the vector.
  • Parameters: None.
  • Return Value: The length of the vector as a number.

'''''

==== squaredLength()

Usage:

[source,js]

let sqLen = vec.squaredLength();

  • Description: Returns the squared length of the vector. This is faster than +length()+ since it avoids the square root operation.
  • Parameters: None.
  • Return Value: The squared length as a number.

'''''

==== normalize()

Usage:

[source,js]

vec.normalize();

  • Description: Normalizes the vector in place (converts it to unit length while preserving direction).
  • Parameters: None.
  • Return Value: The vector itself (for method chaining).

'''''

==== dot()

Usage:

[source,js]

let dotProduct = vec.dot(other);

  • Description: Computes the dot product (scalar product) with another vector.
  • Parameters:
    ** +other+ (Vector4): The other vector.
  • Return Value: The dot product as a number.

'''''

==== cross()

Usage:

[source,js]

let result = vec.cross(other);

  • Description: Computes the cross product with another vector.
  • Parameters:
    ** +other+ (Vector4): The other vector.
  • Return Value: The cross product as a number.

'''''

==== distanceTo()

Usage:

[source,js]

let dist = vec.distanceTo(other);

  • Description: Calculates the distance to another vector.
  • Parameters:
    ** +other+ (Vector4): The other vector.
  • Return Value: The distance as a number.

'''''

==== lerp()

Usage:

[source,js]

let result = vec.lerp(other, t);

  • Description: Performs linear interpolation between this vector and another, modifying this vector in place.
  • Parameters:
    ** +other+ (Vector4): The target vector.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let red = Vector4.create(1, 0, 0, 1); let blue = Vector4.create(0, 0, 1, 1); red.lerp(blue, 0.5); // red is now purple

'''''

==== nlerp()

Usage:

[source,js]

let result = vec.nlerp(other, t);

  • Description: Performs normalized linear interpolation (lerp followed by normalization), modifying this vector in place.
  • Parameters:
    ** +other+ (Vector4): The target vector.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).

'''''

==== slerp()

Usage:

[source,js]

let result = vec.slerp(other, t);

  • Description: Performs spherical linear interpolation between this vector and another, modifying this vector in place.
  • Parameters:
    ** +other+ (Vector4): The target vector.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).

'''''

==== sqlerp()

Usage:

[source,js]

let result = vec.sqlerp(b, c, d, t);

  • Description: Performs squared spherical linear interpolation (squad), modifying this vector in place.
  • Parameters:
    ** +b+ (Vector4): Second control point.
    ** +c+ (Vector4): Third control point.
    ** +d+ (Vector4): Fourth control point.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The vector itself (for method chaining).

'''''

==== clone()

Usage:

[source,js]

let copy = vec.clone();

  • Description: Creates a new vector with the same values as this one.
  • Parameters: None.
  • Return Value: A new Vector4 object.
  • Example:

[source,js]

let color = Vector4.create(1, 0, 0, 1); let copy = color.clone();

'''''

==== copy()

Usage:

[source,js]

vec.copy(other);

  • Description: Copies the values from another vector into this one.
  • Parameters:
    ** +other+ (Vector4): The vector to copy from.
  • Return Value: The vector itself (for method chaining).

'''''

====add()

Usage:

[source,js]

let result = vec.add(other);

  • Description: Adds another vector or scalar to this vector.
  • Parameters:
    ** +other+ (Vector4 or number): The vector or scalar to add.
  • Return Value: The vector itself (for method chaining).

'''''

==== sub()

Usage:

[source,js]

let result = vec.sub(other);

  • Description: Subtracts another vector or scalar from this vector.
  • Parameters:
    ** +other+ (Vector4 or number): The vector or scalar to subtract.
  • Return Value: The vector itself (for method chaining).

'''''

==== mul()

Usage:

[source,js]

let result = vec.mul(value);

  • Description: Multiplies this vector by another vector, scalar, matrix, or quaternion.
  • Parameters:
    ** +value+ (Vector4, number, Matrix3x3, Matrix4x4, or Quaternion): The value to multiply/transform by.
  • Return Value: The vector itself (for method chaining).
  • Example:

[source,js]

let color = Vector4.create(1, 0.5, 0.5, 1);
color.mul(1.5); // Brighten color

let mat = Matrix4x4.create(/* ... */);
color.mul(mat); // Transform color by matrix

let quat = Quaternion.create(/* ... */); color.mul(quat); // Rotate xyz components by quaternion

'''''

==== div()

Usage:

[source,js]

let result = vec.div(value);

  • Description: Divides this vector by another vector or scalar.
  • Parameters:
    ** +value+ (Vector4 or number): The vector or scalar to divide by.
  • Return Value: The vector itself (for method chaining).

'''''

==== neg()

Usage:

[source,js]

let result = vec.neg();

  • Description: Negates this vector (all components multiplied by -1).
  • Parameters: None.
  • Return Value: The vector itself (for method chaining).

'''''

==== equal()

Usage:

[source,js]

let isEqual = vec.equal(other);

  • Description: Checks if this vector is equal to another vector.
  • Parameters:
    ** +other+ (Vector4): The vector to compare with.
  • Return Value: 1 if equal, 0 otherwise.

'''''

==== notEqual()

Usage:

[source,js]

let notEqual = vec.notEqual(other);

  • Description: Checks if this vector is not equal to another vector.
  • Parameters:
    ** +other+ (Vector4): The vector to compare with.
  • Return Value: 1 if not equal, 0 otherwise.

'''''

==== toString()

Usage:

[source,js]

let str = vec.toString();

  • Description: Converts the vector to a string representation.
  • Parameters: None.
  • Return Value: A string representation of the vector.
  • Example:

[source,js]

let color = Vector4.create(1, 0, 0, 1); puts(color.toString()); // Outputs something like "(1, 0, 0, 1)"

'''''

=== Vector4 Operator Overloading

Vector4 supports operator overloading with extended multiplication support:

  • Addition: +vec1 + vec2+ or +vec + scalar+
  • Subtraction: +vec1 - vec2+ or +vec - scalar+
  • Multiplication: +vec * scalar+, +vec1 * vec2+, +vec * matrix+, +vec * quat+, or +matrix/quat * vec+
    ** Supports Matrix3x3, Matrix4x4, and Quaternion transformations in both orders
    ** When multiplying with Quaternion, rotates the xyz components
  • Division: +vec / scalar+ or +vec1 / vec2+
  • Negation: +-vec+
  • Equality: +vec1 == vec2+
  • Inequality: +vec1 != vec2+

'''''

== Quaternion

=== Overview

The Quaternion type represents a rotation in 3D space using four components (x, y, z, w). Quaternions are preferred over Euler angles for many rotation operations.

'''''

=== Global Quaternion Object

==== Quaternion.create()

Usage:

[source,js]

let quat = Quaternion.create(x, y, z, w);

  • Description: Creates a new quaternion.
  • Parameters:
    ** +x+ (number): The x component (default: 0.0)
    ** +y+ (number): The y component (default: 0.0)
    ** +z+ (number): The z component (default: 0.0)
    ** +w+ (number): The w component (default: 1.0)
  • Return Value: A new Quaternion object.
  • Example:

[source,js]

let identity = Quaternion.create(); // Identity rotation

'''''

==== Quaternion.createFromAngleAxis()

Usage:

[source,js]

let quat = Quaternion.createFromAngleAxis(angle, axis);

  • Description: Creates a quaternion from an angle and a rotation axis.
  • Parameters:
    ** +angle+ (number): The rotation angle in radians.
    ** +axis+ (Vector3): The axis of rotation (should be normalized).
  • Return Value: A new Quaternion representing the rotation.
  • Example:

[source,js]

let axis = Vector3.create(0, 1, 0); // Y-axis let quat = Quaternion.createFromAngleAxis(Math.PI / 2, axis); // 90° rotation around Y

'''''

==== Quaternion.createFromEuler()

Usage:

[source,js]

let quat = Quaternion.createFromEuler(pitch, yaw, roll); let quat = Quaternion.createFromEuler(eulerAngles);

  • Description: Creates a quaternion from Euler angles (pitch, yaw, roll).
  • Parameters:
    ** +pitch+ (number): Rotation around X-axis in radians.
    ** +yaw+ (number): Rotation around Y-axis in radians.
    ** +roll+ (number): Rotation around Z-axis in radians.
    ** +eulerAngles+ (Vector3): A Vector3 containing (pitch, yaw, roll).
  • Return Value: A new Quaternion representing the Euler rotation.
  • Example:

[source,js]

let quat1 = Quaternion.createFromEuler(0, Math.PI / 4, 0); // 45° yaw let angles = Vector3.create(0, Math.PI / 4, 0); let quat2 = Quaternion.createFromEuler(angles);

'''''

==== Quaternion.createFromToRotation()

Usage:

[source,js]

let quat = Quaternion.createFromToRotation(fromDirection, toDirection);

  • Description: Creates a quaternion representing the rotation from one direction vector to another.
  • Parameters:
    ** +fromDirection+ (Vector3): The starting direction vector.
    ** +toDirection+ (Vector3): The target direction vector.
  • Return Value: A new Quaternion representing the rotation between the two directions.
  • Example:

[source,js]

let from = Vector3.create(1, 0, 0); // Forward let to = Vector3.create(0, 0, 1); // Right let quat = Quaternion.createFromToRotation(from, to);

'''''

==== Quaternion.createFromLookRotation()

Usage:

[source,js]

let quat = Quaternion.createFromLookRotation(forward, up);

  • Description: Creates a quaternion that rotates to look in a specific direction with a given up vector.
  • Parameters:
    ** +forward+ (Vector3): The forward direction vector.
    ** +up+ (Vector3): The up direction vector.
  • Return Value: A new Quaternion representing the look rotation.
  • Example:

[source,js]

let forward = Vector3.create(0, 0, -1); let up = Vector3.create(0, 1, 0); let quat = Quaternion.createFromLookRotation(forward, up);

'''''

==== Quaternion.createFromScaledAngleAxis()

Usage:

[source,js]

let quat = Quaternion.createFromScaledAngleAxis(scaledAxis);

  • Description: Creates a quaternion from a scaled angle-axis representation where the magnitude of the vector is the angle.
  • Parameters:
    ** +scaledAxis+ (Vector3): A vector whose direction is the axis and magnitude is the angle in radians.
  • Return Value: A new Quaternion.
  • Example:

[source,js]

let scaledAxis = Vector3.create(0, Math.PI / 2, 0); // 90° around Y-axis let quat = Quaternion.createFromScaledAngleAxis(scaledAxis);

'''''

==== Quaternion.createFromAngularVelocity()

Usage:

[source,js]

let quat = Quaternion.createFromAngularVelocity(angularVelocity);

  • Description: Creates a quaternion from an angular velocity vector (used in physics simulations).
  • Parameters:
    ** +angularVelocity+ (Vector3): The angular velocity vector.
  • Return Value: A new Quaternion.
  • Example:

[source,js]

let angVel = Vector3.create(0, 1, 0); let quat = Quaternion.createFromAngularVelocity(angVel);

'''''

==== Quaternion.createFromCols()

Usage:

[source,js]

let quat = Quaternion.createFromCols(col0, col1, col2);

  • Description: Creates a quaternion from three column vectors representing a rotation matrix.
  • Parameters:
    ** +col0+ (Vector3): First column of the rotation matrix.
    ** +col1+ (Vector3): Second column of the rotation matrix.
    ** +col2+ (Vector3): Third column of the rotation matrix.
  • Return Value: A new Quaternion.
  • Example:

[source,js]

let c0 = Vector3.create(1, 0, 0); let c1 = Vector3.create(0, 1, 0); let c2 = Vector3.create(0, 0, 1); let quat = Quaternion.createFromCols(c0, c1, c2);

'''''

==== Quaternion.createFromXY()

Usage:

[source,js]

let quat = Quaternion.createFromXY(xAxis, yAxis);

  • Description: Creates a quaternion from X and Y axis vectors.
  • Parameters:
    ** +xAxis+ (Vector3): The X-axis direction.
    ** +yAxis+ (Vector3): The Y-axis direction.
  • Return Value: A new Quaternion.
  • Example:

[source,js]

let x = Vector3.create(1, 0, 0); let y = Vector3.create(0, 1, 0); let quat = Quaternion.createFromXY(x, y);

'''''

=== Quaternion Properties

  • +x+: X component
  • +y+: Y component
  • +z+: Z component
  • +w+: W component

'''''

=== Quaternion Methods

==== length()

Usage:

[source,js]

let len = quat.length();

  • Description: Returns the magnitude of the quaternion.
  • Parameters: None.
  • Return Value: The length as a number.

'''''

==== squaredLength()

Usage:

[source,js]

let sqLen = quat.squaredLength();

  • Description: Returns the squared magnitude of the quaternion. This is faster than +length()+.
  • Parameters: None.
  • Return Value: The squared length as a number.

'''''

==== normalize()

Usage:

[source,js]

quat.normalize();

  • Description: Normalizes the quaternion in place. A normalized quaternion represents a valid rotation.
  • Parameters: None.
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let quat = Quaternion.create(0, 1, 0, 1); quat.normalize(); // Now represents a valid rotation

'''''

==== dot()

Usage:

[source,js]

let dotProduct = quat.dot(other);

  • Description: Computes the dot product with another quaternion.
  • Parameters:
    ** +other+ (Quaternion): The other quaternion.
  • Return Value: The dot product as a number.

'''''

==== lerp()

Usage:

[source,js]

let result = quat.lerp(other, t);

  • Description: Performs linear interpolation between this quaternion and another, modifying this quaternion in place.
  • Parameters:
    ** +other+ (Quaternion): The target quaternion.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The quaternion itself (for method chaining).

'''''

==== nlerp()

Usage:

[source,js]

let result = quat.nlerp(other, t);

  • Description: Performs normalized linear interpolation, modifying this quaternion in place. This is faster than slerp but doesn't maintain constant angular velocity.
  • Parameters:
    ** +other+ (Quaternion): The target quaternion.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let q1 = Quaternion.create(0, 0, 0, 1); let q2 = Quaternion.create(0, 0.707, 0, 0.707); q1.nlerp(q2, 0.5); // q1 is now halfway interpolated

'''''

==== slerp()

Usage:

[source,js]

let result = quat.slerp(other, t);

  • Description: Performs spherical linear interpolation, modifying this quaternion in place. This produces smooth rotation with constant angular velocity.
  • Parameters:
    ** +other+ (Quaternion): The target quaternion.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let q1 = Quaternion.create(0, 0, 0, 1); // Identity let q2 = Quaternion.create(0, 0.707, 0, 0.707); // 90° around Y q1.slerp(q2, 0.5); // q1 is now smoothly interpolated halfway

'''''

==== sqlerp()

Usage:

[source,js]

let result = quat.sqlerp(b, c, d, t);

  • Description: Performs squared spherical linear interpolation (squad), modifying this quaternion in place.
  • Parameters:
    ** +b+ (Quaternion): Second control point.
    ** +c+ (Quaternion): Third control point.
    ** +d+ (Quaternion): Fourth control point.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The quaternion itself (for method chaining).

'''''

==== clone()

Usage:

[source,js]

let copy = quat.clone();

  • Description: Creates a new quaternion with the same values as this one.
  • Parameters: None.
  • Return Value: A new Quaternion object.

'''''

==== copy()

Usage:

[source,js]

quat.copy(other);

  • Description: Copies the values from another quaternion into this one.
  • Parameters:
    ** +other+ (Quaternion): The quaternion to copy from.
  • Return Value: The quaternion itself (for method chaining).

'''''

==== add()

Usage:

[source,js]

let result = quat.add(other);

  • Description: Adds another quaternion to this quaternion, modifying this quaternion in place.
  • Parameters:
    ** +other+ (Quaternion): The quaternion to add.
  • Return Value: The quaternion itself (for method chaining).

'''''

==== sub()

Usage:

[source,js]

let result = quat.sub(other);

  • Description: Subtracts another quaternion from this quaternion, modifying this quaternion in place.
  • Parameters:
    ** +other+ (Quaternion): The quaternion to subtract.
  • Return Value: The quaternion itself (for method chaining).

'''''

==== mul()

Usage:

[source,js]

let result = quat.mul(other);

  • Description: Multiplies this quaternion by another quaternion, scalar, or vector. When multiplying quaternions, this combines rotations (note: order matters). When multiplying by a Vector3, it returns the rotated vector.
  • Parameters:
    ** +other+ (Quaternion, number, or Vector3): The quaternion, scalar, or vector to multiply by.
  • Return Value: The modified quaternion itself when multiplying by Quaternion/number, or a new Vector3 when multiplying by Vector3.
  • Example:

[source,js]

let rotX = Quaternion.create(/* rotation around X /);
let rotY = Quaternion.create(/
rotation around Y */);
rotX.mul(rotY); // Combined rotation in rotX

let vec = Vector3.create(1, 0, 0); let rotated = rotX.mul(vec); // Returns rotated Vector3

'''''

==== div()

Usage:

[source,js]

let result = quat.div(value);

  • Description: Divides this quaternion by a scalar value or another quaternion, modifying this quaternion in place.
  • Parameters:
    ** +value+ (number or Quaternion): The scalar or quaternion to divide by.
  • Return Value: The quaternion itself (for method chaining).

'''''

==== neg()

Usage:

[source,js]

let result = quat.neg();

  • Description: Negates this quaternion (all components multiplied by -1), modifying it in place.
  • Parameters: None.
  • Return Value: The quaternion itself (for method chaining).

'''''

==== equal()

Usage:

[source,js]

let isEqual = quat.equal(other);

  • Description: Checks if this quaternion is equal to another quaternion.
  • Parameters:
    ** +other+ (Quaternion): The quaternion to compare with.
  • Return Value: 1 if equal, 0 otherwise.

'''''

==== notEqual()

Usage:

[source,js]

let notEqual = quat.notEqual(other);

  • Description: Checks if this quaternion is not equal to another quaternion.
  • Parameters:
    ** +other+ (Quaternion): The quaternion to compare with.
  • Return Value: 1 if not equal, 0 otherwise.

'''''

==== toString()

Usage:

[source,js]

let str = quat.toString();

  • Description: Converts the quaternion to a string representation.
  • Parameters: None.
  • Return Value: A string representation of the quaternion.
  • Example:

[source,js]

let quat = Quaternion.create(0, 0, 0, 1); puts(quat.toString()); // Outputs something like "(0, 0, 0, 1)"

'''''

==== toEuler()

Usage:

[source,js]

let eulerAngles = quat.toEuler();

  • Description: Converts the quaternion to Euler angles (pitch, yaw, roll).
  • Parameters: None.
  • Return Value: A Vector3 containing the Euler angles in radians (x=pitch, y=yaw, z=roll).
  • Example:

[source,js]

let quat = Quaternion.createFromEuler(0.1, 0.2, 0.3); let euler = quat.toEuler(); puts("Pitch: " + euler.x + ", Yaw: " + euler.y + ", Roll: " + euler.z);

'''''

==== toPitch()

Usage:

[source,js]

let pitch = quat.toPitch();

  • Description: Extracts the pitch (rotation around X-axis) from the quaternion.
  • Parameters: None.
  • Return Value: The pitch angle in radians.
  • Example:

[source,js]

let quat = Quaternion.createFromEuler(0.5, 0, 0); let pitch = quat.toPitch(); // Returns ~0.5

'''''

==== toYaw()

Usage:

[source,js]

let yaw = quat.toYaw();

  • Description: Extracts the yaw (rotation around Y-axis) from the quaternion.
  • Parameters: None.
  • Return Value: The yaw angle in radians.
  • Example:

[source,js]

let quat = Quaternion.createFromEuler(0, 0.5, 0); let yaw = quat.toYaw(); // Returns ~0.5

'''''

==== toRoll()

Usage:

[source,js]

let roll = quat.toRoll();

  • Description: Extracts the roll (rotation around Z-axis) from the quaternion.
  • Parameters: None.
  • Return Value: The roll angle in radians.
  • Example:

[source,js]

let quat = Quaternion.createFromEuler(0, 0, 0.5); let roll = quat.toRoll(); // Returns ~0.5

'''''

==== toAngleAxis()

Usage:

[source,js]

let result = quat.toAngleAxis();

  • Description: Converts the quaternion to an angle-axis representation.
  • Parameters: None.
  • Return Value: A hash object with +angle+ (number) and +axis+ (Vector3) properties.
  • Example:

[source,js]

let quat = Quaternion.createFromAngleAxis(Math.PI / 2, Vector3.create(0, 1, 0)); let result = quat.toAngleAxis(); puts("Angle: " + result.angle + ", Axis: " + result.axis.toString());

'''''

==== toScaledAngleAxis()

Usage:

[source,js]

let scaledAxis = quat.toScaledAngleAxis();

  • Description: Converts the quaternion to a scaled angle-axis representation where the vector's magnitude is the angle.
  • Parameters: None.
  • Return Value: A Vector3 whose direction is the axis and magnitude is the angle in radians.
  • Example:

[source,js]

let quat = Quaternion.createFromAngleAxis(Math.PI / 2, Vector3.create(0, 1, 0)); let scaledAxis = quat.toScaledAngleAxis(); puts("Scaled axis: " + scaledAxis.toString());

'''''

==== approximatedSlerp()

Usage:

[source,js]

quat.approximatedSlerp(other, t);

  • Description: Performs a faster approximation of spherical linear interpolation (slerp), modifying this quaternion in place.
  • Parameters:
    ** +other+ (Quaternion): The target quaternion.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let q1 = Quaternion.create(0, 0, 0, 1); let q2 = Quaternion.createFromEuler(0, Math.PI / 2, 0); q1.approximatedSlerp(q2, 0.5); // Fast interpolation

'''''

==== elerp()

Usage:

[source,js]

quat.elerp(other, t);

  • Description: Performs exponential linear interpolation, modifying this quaternion in place.
  • Parameters:
    ** +other+ (Quaternion): The target quaternion.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let q1 = Quaternion.create(0, 0, 0, 1); let q2 = Quaternion.createFromEuler(0, Math.PI / 2, 0); q1.elerp(q2, 0.5); // Exponential interpolation

'''''

==== unflippedSlerp()

Usage:

[source,js]

quat.unflippedSlerp(other, t);

  • Description: Performs spherical linear interpolation without quaternion flipping, modifying this quaternion in place.
  • Parameters:
    ** +other+ (Quaternion): The target quaternion.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let q1 = Quaternion.create(0, 0, 0, 1); let q2 = Quaternion.createFromEuler(0, Math.PI / 2, 0); q1.unflippedSlerp(q2, 0.5);

'''''

==== unflippedApproximatedSlerp()

Usage:

[source,js]

quat.unflippedApproximatedSlerp(other, t);

  • Description: Performs a faster approximation of spherical linear interpolation without quaternion flipping.
  • Parameters:
    ** +other+ (Quaternion): The target quaternion.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let q1 = Quaternion.create(0, 0, 0, 1); let q2 = Quaternion.createFromEuler(0, Math.PI / 2, 0); q1.unflippedApproximatedSlerp(q2, 0.5);

'''''

==== unflippedSqlerp()

Usage:

[source,js]

quat.unflippedSqlerp(q1, q2, q3, t);

  • Description: Performs spherical quadratic interpolation without quaternion flipping, modifying this quaternion in place.
  • Parameters:
    ** +q1+ (Quaternion): First control point.
    ** +q2+ (Quaternion): Second control point.
    ** +q3+ (Quaternion): Third control point.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let q0 = Quaternion.create(0, 0, 0, 1); let q1 = Quaternion.createFromEuler(0, Math.PI / 4, 0); let q2 = Quaternion.createFromEuler(0, Math.PI / 2, 0); let q3 = Quaternion.createFromEuler(0, Math.PI, 0); q0.unflippedSqlerp(q1, q2, q3, 0.5);

'''''

==== angleBetween()

Usage:

[source,js]

let angle = quat.angleBetween(other);

  • Description: Calculates the angle (in radians) between this quaternion and another.
  • Parameters:
    ** +other+ (Quaternion): The other quaternion.
  • Return Value: The angle between the two quaternions in radians.
  • Example:

[source,js]

let q1 = Quaternion.create(0, 0, 0, 1); let q2 = Quaternion.createFromEuler(0, Math.PI / 2, 0); let angle = q1.angleBetween(q2); puts("Angle between quaternions: " + angle);

'''''

==== between()

Usage:

[source,js]

quat.between(other);

  • Description: Calculates the quaternion representing the rotation from this quaternion to another, modifying this quaternion in place.
  • Parameters:
    ** +other+ (Quaternion): The target quaternion.
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let q1 = Quaternion.create(0, 0, 0, 1); let q2 = Quaternion.createFromEuler(0, Math.PI / 2, 0); q1.between(q2); // q1 now represents the delta rotation

'''''

==== integrate()

Usage:

[source,js]

quat.integrate(omega, deltaTime);

  • Description: Integrates angular velocity into the quaternion (for physics simulations), modifying this quaternion in place.
  • Parameters:
    ** +omega+ (Vector3): The angular velocity vector.
    ** +deltaTime+ (number): The time step for integration.
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let quat = Quaternion.create(0, 0, 0, 1); let angularVelocity = Vector3.create(0, 1, 0); // Rotating around Y-axis quat.integrate(angularVelocity, 0.016); // One frame at ~60fps

'''''

==== spin()

Usage:

[source,js]

quat.spin(omega, deltaTime);

  • Description: Applies a spin (continuous rotation) to the quaternion based on angular velocity, modifying this quaternion in place.
  • Parameters:
    ** +omega+ (Vector3): The angular velocity vector.
    ** +deltaTime+ (number): The time step for the spin.
  • Return Value: The quaternion itself (for method chaining).
  • Example:

[source,js]

let quat = Quaternion.create(0, 0, 0, 1); let angularVelocity = Vector3.create(0, 2, 0); // Fast rotation around Y quat.spin(angularVelocity, 0.016);

'''''

=== Quaternion Operator Overloading

Quaternion supports operator overloading:

  • Addition: +quat1 + quat2+
  • Subtraction: +quat1 - quat2+
  • Multiplication: +quat1 * quat2+ (combines rotations), +quat * scalar+, +quat * vec+, or +vec * quat+
    ** Quaternion×Quaternion combines rotations
    ** Quaternion×Vector3 or Vector3×Quaternion rotates the vector and returns a Vector3
  • Division: +quat / scalar+ or +quat1 / quat2+
  • Negation: +-quat+
  • Equality: +quat1 == quat2+
  • Inequality: +quat1 != quat2+

Example:

[source,js]

let q1 = Quaternion.create(/* ... /);
let q2 = Quaternion.create(/
... */);
let combined = q1 * q2; // Combine rotations

let vec = Vector3.create(1, 0, 0); let rotated = q1 * vec; // Returns rotated Vector3

'''''

== Matrix3x3

=== Overview

The Matrix3x3 type represents a 3x3 matrix, commonly used for 2D transformations.

'''''

=== Global Matrix3x3 Object

==== Matrix3x3.create()

Usage:

[source,js]

let mat = Matrix3x3.create( m00, m01, m02, m10, m11, m12, m20, m21, m22 );

  • Description: Creates a new 3x3 matrix. If no parameters are provided, creates an identity matrix.
  • Parameters: Nine numbers representing the matrix elements (row-major order).
  • Return Value: A new Matrix3x3 object.
  • Example:

[source,js]

let identity = Matrix3x3.create(); // Identity matrix

'''''

==== Matrix3x3.createRotateX()

Usage:

[source,js]

let mat = Matrix3x3.createRotateX(angle);

  • Description: Creates a 3x3 rotation matrix around the X-axis.
  • Parameters:
    ** +angle+ (number): The rotation angle in radians.
  • Return Value: A new Matrix3x3 representing the rotation.
  • Example:

[source,js]

let mat = Matrix3x3.createRotateX(Math.PI / 2); // 90° rotation around X

'''''

==== Matrix3x3.createRotateY()

Usage:

[source,js]

let mat = Matrix3x3.createRotateY(angle);

  • Description: Creates a 3x3 rotation matrix around the Y-axis.
  • Parameters:
    ** +angle+ (number): The rotation angle in radians.
  • Return Value: A new Matrix3x3 representing the rotation.
  • Example:

[source,js]

let mat = Matrix3x3.createRotateY(Math.PI / 4); // 45° rotation around Y

'''''

==== Matrix3x3.createRotateZ()

Usage:

[source,js]

let mat = Matrix3x3.createRotateZ(angle);

  • Description: Creates a 3x3 rotation matrix around the Z-axis.
  • Parameters:
    ** +angle+ (number): The rotation angle in radians.
  • Return Value: A new Matrix3x3 representing the rotation.
  • Example:

[source,js]

let mat = Matrix3x3.createRotateZ(Math.PI); // 180° rotation around Z

'''''

==== Matrix3x3.createRotate()

Usage:

[source,js]

let mat = Matrix3x3.createRotate(angle, axis);

  • Description: Creates a 3x3 rotation matrix around an arbitrary axis.
  • Parameters:
    ** +angle+ (number): The rotation angle in radians.
    ** +axis+ (Vector3): The axis of rotation (should be normalized).
  • Return Value: A new Matrix3x3 representing the rotation.
  • Example:

[source,js]

let axis = Vector3.create(1, 1, 0).normalize(); let mat = Matrix3x3.createRotate(Math.PI / 3, axis);

'''''

==== Matrix3x3.createScale()

Usage:

[source,js]

let mat = Matrix3x3.createScale(sx, sy, sz); let mat = Matrix3x3.createScale(scaleVec);

  • Description: Creates a 3x3 scale matrix.
  • Parameters:
    ** +sx+ (number): Scale factor for X-axis.
    ** +sy+ (number): Scale factor for Y-axis.
    ** +sz+ (number): Scale factor for Z-axis.
    ** +scaleVec+ (Vector3): A vector containing the scale factors.
  • Return Value: A new Matrix3x3 representing the scale transformation.
  • Example:

[source,js]

let mat1 = Matrix3x3.createScale(2, 3, 1); // Non-uniform scale let mat2 = Matrix3x3.createScale(Vector3.create(2, 2, 2)); // Uniform scale

'''''

==== Matrix3x3.createTranslation()

Usage:

[source,js]

let mat = Matrix3x3.createTranslation(tx, ty); let mat = Matrix3x3.createTranslation(translationVec);

  • Description: Creates a 3x3 translation matrix (for 2D transformations).
  • Parameters:
    ** +tx+ (number): Translation along X-axis.
    ** +ty+ (number): Translation along Y-axis.
    ** +translationVec+ (Vector2): A vector containing the translation.
  • Return Value: A new Matrix3x3 representing the translation.
  • Example:

[source,js]

let mat1 = Matrix3x3.createTranslation(10, 20); let mat2 = Matrix3x3.createTranslation(Vector2.create(10, 20));

'''''

==== Matrix3x3.createFromQuaternion()

Usage:

[source,js]

let mat = Matrix3x3.createFromQuaternion(quat);

  • Description: Creates a 3x3 rotation matrix from a quaternion.
  • Parameters:
    ** +quat+ (Quaternion): The quaternion to convert.
  • Return Value: A new Matrix3x3 representing the same rotation.
  • Example:

[source,js]

let quat = Quaternion.createFromEuler(0, Math.PI / 2, 0); let mat = Matrix3x3.createFromQuaternion(quat);

'''''

==== Matrix3x3.createFromQTangent()

Usage:

[source,js]

let mat = Matrix3x3.createFromQTangent(qtangent);

  • Description: Creates a 3x3 matrix from a QTangent (compressed tangent space quaternion).
  • Parameters:
    ** +qtangent+ (Quaternion): The QTangent quaternion.
  • Return Value: A new Matrix3x3.
  • Example:

[source,js]

let qt = Quaternion.create(0.5, 0.5, 0.5, 0.5); let mat = Matrix3x3.createFromQTangent(qt);

'''''

==== Matrix3x3.createFromToRotation()

Usage:

[source,js]

let mat = Matrix3x3.createFromToRotation(from, to);

  • Description: Creates a 3x3 rotation matrix that rotates from one direction to another.
  • Parameters:
    ** +from+ (Vector3): The starting direction.
    ** +to+ (Vector3): The target direction.
  • Return Value: A new Matrix3x3 representing the rotation.
  • Example:

[source,js]

let from = Vector3.create(1, 0, 0); let to = Vector3.create(0, 1, 0); let mat = Matrix3x3.createFromToRotation(from, to);

'''''

==== Matrix3x3.createConstructForwardUp()

Usage:

[source,js]

let mat = Matrix3x3.createConstructForwardUp(forward, up);

  • Description: Creates a 3x3 orientation matrix from forward and up vectors.
  • Parameters:
    ** +forward+ (Vector3): The forward direction.
    ** +up+ (Vector3): The up direction.
  • Return Value: A new Matrix3x3 representing the orientation.
  • Example:

[source,js]

let forward = Vector3.create(0, 0, -1); let up = Vector3.create(0, 1, 0); let mat = Matrix3x3.createConstructForwardUp(forward, up);

'''''

==== Matrix3x3.createOuterProduct()

Usage:

[source,js]

let mat = Matrix3x3.createOuterProduct(u, v);

  • Description: Creates a 3x3 matrix from the outer product of two vectors.
  • Parameters:
    ** +u+ (Vector3): First vector.
    ** +v+ (Vector3): Second vector.
  • Return Value: A new Matrix3x3 representing the outer product (u ⊗ v).
  • Example:

[source,js]

let u = Vector3.create(1, 0, 0); let v = Vector3.create(0, 1, 0); let mat = Matrix3x3.createOuterProduct(u, v);

'''''

==== Matrix3x3.createSkewYX()

Usage:

[source,js]

let mat = Matrix3x3.createSkewYX(angle);

  • Description: Creates a 3x3 skew matrix that shears Y by X.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix3x3 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix3x3.createSkewYX(Math.PI / 6);

'''''

==== Matrix3x3.createSkewZX()

Usage:

[source,js]

let mat = Matrix3x3.createSkewZX(angle);

  • Description: Creates a 3x3 skew matrix that shears Z by X.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix3x3 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix3x3.createSkewZX(Math.PI / 6);

'''''

==== Matrix3x3.createSkewXY()

Usage:

[source,js]

let mat = Matrix3x3.createSkewXY(angle);

  • Description: Creates a 3x3 skew matrix that shears X by Y.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix3x3 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix3x3.createSkewXY(Math.PI / 6);

'''''

==== Matrix3x3.createSkewZY()

Usage:

[source,js]

let mat = Matrix3x3.createSkewZY(angle);

  • Description: Creates a 3x3 skew matrix that shears Z by Y.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix3x3 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix3x3.createSkewZY(Math.PI / 6);

'''''

==== Matrix3x3.createSkewXZ()

Usage:

[source,js]

let mat = Matrix3x3.createSkewXZ(angle);

  • Description: Creates a 3x3 skew matrix that shears X by Z.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix3x3 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix3x3.createSkewXZ(Math.PI / 6);

'''''

==== Matrix3x3.createSkewYZ()

Usage:

[source,js]

let mat = Matrix3x3.createSkewYZ(angle);

  • Description: Creates a 3x3 skew matrix that shears Y by Z.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix3x3 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix3x3.createSkewYZ(Math.PI / 6);

'''''

=== Matrix3x3 Properties

Matrix3x3 provides indexed access to its elements:

  • +m00+, +m01+, +m02+: First row
  • +m10+, +m11+, +m12+: Second row
  • +m20+, +m21+, +m22+: Third row

'''''

=== Matrix3x3 Methods

==== clone()

Usage:

[source,js]

let copy = mat.clone();

  • Description: Creates a new matrix with the same values as this one.
  • Parameters: None.
  • Return Value: A new Matrix3x3 object.
  • Example:

[source,js]

let original = Matrix3x3.create(); let copy = original.clone();

'''''

==== copy()

Usage:

[source,js]

mat.copy(other);

  • Description: Copies the values from another matrix into this one.
  • Parameters:
    ** +other+ (Matrix3x3): The matrix to copy from.
  • Return Value: The matrix itself (for method chaining).

'''''

==== add()

Usage:

[source,js]

let result = mat.add(other);

  • Description: Adds another matrix to this matrix (element-wise addition).
  • Parameters:
    ** +other+ (Matrix3x3): The matrix to add.
  • Return Value: The matrix itself (for method chaining).

'''''

==== sub()

Usage:

[source,js]

let result = mat.sub(other);

  • Description: Subtracts another matrix from this matrix (element-wise subtraction).
  • Parameters:
    ** +other+ (Matrix3x3): The matrix to subtract.
  • Return Value: The matrix itself (for method chaining).

'''''

==== mul()

Usage:

[source,js]

let result = mat.mul(other);

  • Description: Multiplies this matrix by another matrix, scalar, vector, or quaternion. Matrix multiplication combines transformations. When multiplying by a vector, returns the transformed vector.
  • Parameters:
    ** +other+ (Matrix3x3, number, Vector2, Vector3, Vector4, or Quaternion): The value to multiply by.
  • Return Value: The modified matrix itself when multiplying by Matrix3x3/number/Quaternion, or a new vector when multiplying by a vector.
  • Example:

[source,js]

let mat1 = Matrix3x3.create(); // Identity
let mat2 = Matrix3x3.create(
2, 0, 0,
0, 2, 0,
0, 0, 1
); // 2x scale
mat1.mul(mat2); // mat1 is now scaled

let vec = Vector3.create(1, 2, 3); let transformed = mat1.mul(vec); // Returns transformed Vector3

'''''

==== div()

Usage:

[source,js]

let result = mat.div(value);

  • Description: Divides this matrix by a scalar or another matrix (element-wise division), modifying this matrix in place.
  • Parameters:
    ** +value+ (number or Matrix3x3): The scalar or matrix to divide by.
  • Return Value: The matrix itself (for method chaining).

'''''

==== neg()

Usage:

[source,js]

let result = mat.neg();

  • Description: Negates this matrix (all elements multiplied by -1), modifying it in place.
  • Parameters: None.
  • Return Value: The matrix itself (for method chaining).

'''''

==== lerp()

Usage:

[source,js]

let result = mat.lerp(other, t);

  • Description: Performs linear interpolation between this matrix and another, modifying this matrix in place.
  • Parameters:
    ** +other+ (Matrix3x3): The target matrix.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== nlerp()

Usage:

[source,js]

let result = mat.nlerp(other, t);

  • Description: Performs normalized linear interpolation, modifying this matrix in place.
  • Parameters:
    ** +other+ (Matrix3x3): The target matrix.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== slerp()

Usage:

[source,js]

let result = mat.slerp(other, t);

  • Description: Performs spherical linear interpolation, modifying this matrix in place.
  • Parameters:
    ** +other+ (Matrix3x3): The target matrix.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== elerp()

Usage:

[source,js]

let result = mat.elerp(other, t);

  • Description: Performs exponential linear interpolation, modifying this matrix in place.
  • Parameters:
    ** +other+ (Matrix3x3): The target matrix.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== sqlerp()

Usage:

[source,js]

let result = mat.sqlerp(b, c, d, t);

  • Description: Performs squared spherical linear interpolation (squad), modifying this matrix in place.
  • Parameters:
    ** +b+ (Matrix3x3): Second control point.
    ** +c+ (Matrix3x3): Third control point.
    ** +d+ (Matrix3x3): Fourth control point.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== equal()

Usage:

[source,js]

let isEqual = mat.equal(other);

  • Description: Checks if this matrix is equal to another matrix.
  • Parameters:
    ** +other+ (Matrix3x3): The matrix to compare with.
  • Return Value: 1 if equal, 0 otherwise.

'''''

==== notEqual()

Usage:

[source,js]

let notEqual = mat.notEqual(other);

  • Description: Checks if this matrix is not equal to another matrix.
  • Parameters:
    ** +other+ (Matrix3x3): The matrix to compare with.
  • Return Value: 1 if not equal, 0 otherwise.

'''''

==== toString()

Usage:

[source,js]

let str = mat.toString();

  • Description: Converts the matrix to a string representation.
  • Parameters: None.
  • Return Value: A string representation of the matrix.

'''''

=== Matrix3x3 Operator Overloading

Matrix3x3 supports operator overloading:

  • Addition: +mat1 + mat2+
  • Subtraction: +mat1 - mat2+
  • Multiplication: +mat1 * mat2+, +mat * scalar+, +mat * vec+, +mat * quat+, or +vec/quat * mat+
    ** Matrix×Matrix combines transformations
    ** Matrix×Vector (Vector2/3/4) or Vector×Matrix transforms the vector and returns the transformed vector
    ** Matrix×Quaternion or Quaternion×Matrix combines transformation and rotation
  • Division: +mat / scalar+ or +mat1 / mat2+
  • Negation: +-mat+
  • Equality: +mat1 == mat2+
  • Inequality: +mat1 != mat2+

Example:

[source,js]

let mat = Matrix3x3.create(/* ... */); let vec = Vector3.create(1, 2, 3); let transformed = mat * vec; // Returns transformed Vector3 let alsoTransformed = vec * mat; // Also works

'''''

== Matrix4x4

=== Overview

The Matrix4x4 type represents a 4x4 matrix, the standard transformation matrix for 3D graphics.

'''''

=== Global Matrix4x4 Object

==== Matrix4x4.create()

Usage:

[source,js]

let mat = Matrix4x4.create( m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33 );

  • Description: Creates a new 4x4 matrix. If no parameters are provided, creates an identity matrix.
  • Parameters: Sixteen numbers representing the matrix elements (row-major order).
  • Return Value: A new Matrix4x4 object.
  • Example:

[source,js]

let identity = Matrix4x4.create(); // Identity matrix

'''''

==== Matrix4x4.createRotateX()

Usage:

[source,js]

let mat = Matrix4x4.createRotateX(angle);

  • Description: Creates a 4x4 rotation matrix around the X-axis.
  • Parameters:
    ** +angle+ (number): The rotation angle in radians.
  • Return Value: A new Matrix4x4 representing the rotation.
  • Example:

[source,js]

let mat = Matrix4x4.createRotateX(Math.PI / 2); // 90° rotation around X

'''''

==== Matrix4x4.createRotateY()

Usage:

[source,js]

let mat = Matrix4x4.createRotateY(angle);

  • Description: Creates a 4x4 rotation matrix around the Y-axis.
  • Parameters:
    ** +angle+ (number): The rotation angle in radians.
  • Return Value: A new Matrix4x4 representing the rotation.
  • Example:

[source,js]

let mat = Matrix4x4.createRotateY(Math.PI / 4); // 45° rotation around Y

'''''

==== Matrix4x4.createRotateZ()

Usage:

[source,js]

let mat = Matrix4x4.createRotateZ(angle);

  • Description: Creates a 4x4 rotation matrix around the Z-axis.
  • Parameters:
    ** +angle+ (number): The rotation angle in radians.
  • Return Value: A new Matrix4x4 representing the rotation.
  • Example:

[source,js]

let mat = Matrix4x4.createRotateZ(Math.PI); // 180° rotation around Z

'''''

==== Matrix4x4.createRotate()

Usage:

[source,js]

let mat = Matrix4x4.createRotate(angle, axis);

  • Description: Creates a 4x4 rotation matrix around an arbitrary axis.
  • Parameters:
    ** +angle+ (number): The rotation angle in radians.
    ** +axis+ (Vector3): The axis of rotation (should be normalized).
  • Return Value: A new Matrix4x4 representing the rotation.
  • Example:

[source,js]

let axis = Vector3.create(1, 1, 0).normalize(); let mat = Matrix4x4.createRotate(Math.PI / 3, axis);

'''''

==== Matrix4x4.createRotation()

Usage:

[source,js]

let mat = Matrix4x4.createRotation(sourceMatrix);

  • Description: Extracts the rotation part from a 4x4 matrix (removes translation and scale).
  • Parameters:
    ** +sourceMatrix+ (Matrix4x4): The source matrix.
  • Return Value: A new Matrix4x4 containing only the rotation.
  • Example:

[source,js]

let transform = Matrix4x4.createTranslation(10, 20, 30); let rotation = Matrix4x4.createRotation(transform);

'''''

==== Matrix4x4.createScale()

Usage:

[source,js]

let mat = Matrix4x4.createScale(sx, sy, sz); let mat = Matrix4x4.createScale(scaleVec);

  • Description: Creates a 4x4 scale matrix.
  • Parameters:
    ** +sx+ (number): Scale factor for X-axis.
    ** +sy+ (number): Scale factor for Y-axis.
    ** +sz+ (number): Scale factor for Z-axis.
    ** +scaleVec+ (Vector3 or Vector4): A vector containing the scale factors.
  • Return Value: A new Matrix4x4 representing the scale transformation.
  • Example:

[source,js]

let mat1 = Matrix4x4.createScale(2, 3, 4); // Non-uniform scale let mat2 = Matrix4x4.createScale(Vector3.create(2, 2, 2)); // Uniform scale

'''''

==== Matrix4x4.createTranslation()

Usage:

[source,js]

let mat = Matrix4x4.createTranslation(tx, ty, tz); let mat = Matrix4x4.createTranslation(translationVec);

  • Description: Creates a 4x4 translation matrix.
  • Parameters:
    ** +tx+ (number): Translation along X-axis.
    ** +ty+ (number): Translation along Y-axis.
    ** +tz+ (number): Translation along Z-axis.
    ** +translationVec+ (Vector3): A vector containing the translation.
  • Return Value: A new Matrix4x4 representing the translation.
  • Example:

[source,js]

let mat1 = Matrix4x4.createTranslation(10, 20, 30); let mat2 = Matrix4x4.createTranslation(Vector3.create(10, 20, 30));

'''''

==== Matrix4x4.createTranslated()

Usage:

[source,js]

let mat = Matrix4x4.createTranslated(sourceMatrix, translation);

  • Description: Creates a translated copy of a matrix.
  • Parameters:
    ** +sourceMatrix+ (Matrix4x4): The source matrix.
    ** +translation+ (Vector3): The translation to apply.
  • Return Value: A new Matrix4x4 with the translation applied.
  • Example:

[source,js]

let original = Matrix4x4.createRotateY(Math.PI / 4); let translated = Matrix4x4.createTranslated(original, Vector3.create(5, 10, 15));

'''''

==== Matrix4x4.createFromQuaternion()

Usage:

[source,js]

let mat = Matrix4x4.createFromQuaternion(quat);

  • Description: Creates a 4x4 rotation matrix from a quaternion.
  • Parameters:
    ** +quat+ (Quaternion): The quaternion to convert.
  • Return Value: A new Matrix4x4 representing the same rotation.
  • Example:

[source,js]

let quat = Quaternion.createFromEuler(0, Math.PI / 2, 0); let mat = Matrix4x4.createFromQuaternion(quat);

'''''

==== Matrix4x4.createFromToRotation()

Usage:

[source,js]

let mat = Matrix4x4.createFromToRotation(from, to);

  • Description: Creates a 4x4 rotation matrix that rotates from one direction to another.
  • Parameters:
    ** +from+ (Vector3): The starting direction.
    ** +to+ (Vector3): The target direction.
  • Return Value: A new Matrix4x4 representing the rotation.
  • Example:

[source,js]

let from = Vector3.create(1, 0, 0); let to = Vector3.create(0, 1, 0); let mat = Matrix4x4.createFromToRotation(from, to);

'''''

==== Matrix4x4.createLookAt()

Usage:

[source,js]

let mat = Matrix4x4.createLookAt(eye, center, up);

  • Description: Creates a view matrix for a camera looking at a target point.
  • Parameters:
    ** +eye+ (Vector3): The camera position.
    ** +center+ (Vector3): The point the camera is looking at.
    ** +up+ (Vector3): The up direction vector.
  • Return Value: A new Matrix4x4 view matrix.
  • Example:

[source,js]

let eye = Vector3.create(0, 5, 10); let center = Vector3.create(0, 0, 0); let up = Vector3.create(0, 1, 0); let viewMatrix = Matrix4x4.createLookAt(eye, center, up);

'''''

==== Matrix4x4.createPerspective()

Usage:

[source,js]

let mat = Matrix4x4.createPerspective(fovy, aspect, znear, zfar);

  • Description: Creates a perspective projection matrix (for 3D rendering).
  • Parameters:
    ** +fovy+ (number): Field of view angle in the Y direction (in radians).
    ** +aspect+ (number): Aspect ratio (width/height).
    ** +znear+ (number): Near clipping plane distance.
    ** +zfar+ (number): Far clipping plane distance.
  • Return Value: A new Matrix4x4 perspective projection matrix.
  • Example:

[source,js]

let projMatrix = Matrix4x4.createPerspective(
Math.PI / 3, // 60° field of view
16 / 9, // 16:9 aspect ratio
0.1, // Near plane
1000 // Far plane

);

'''''

==== Matrix4x4.createOrtho()

Usage:

[source,js]

let mat = Matrix4x4.createOrtho(left, right, bottom, top, znear, zfar);

  • Description: Creates an orthographic projection matrix (for 2D rendering or isometric 3D).
  • Parameters:
    ** +left+ (number): Left edge of the view volume.
    ** +right+ (number): Right edge of the view volume.
    ** +bottom+ (number): Bottom edge of the view volume.
    ** +top+ (number): Top edge of the view volume.
    ** +znear+ (number): Near clipping plane distance.
    ** +zfar+ (number): Far clipping plane distance.
  • Return Value: A new Matrix4x4 orthographic projection matrix.
  • Example:

[source,js]

let orthoMatrix = Matrix4x4.createOrtho(-100, 100, -75, 75, 0.1, 100);

'''''

==== Matrix4x4.createSkewYX()

Usage:

[source,js]

let mat = Matrix4x4.createSkewYX(angle);

  • Description: Creates a 4x4 skew matrix that shears Y by X.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix4x4 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix4x4.createSkewYX(Math.PI / 6);

'''''

==== Matrix4x4.createSkewZX()

Usage:

[source,js]

let mat = Matrix4x4.createSkewZX(angle);

  • Description: Creates a 4x4 skew matrix that shears Z by X.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix4x4 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix4x4.createSkewZX(Math.PI / 6);

'''''

==== Matrix4x4.createSkewXY()

Usage:

[source,js]

let mat = Matrix4x4.createSkewXY(angle);

  • Description: Creates a 4x4 skew matrix that shears X by Y.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix4x4 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix4x4.createSkewXY(Math.PI / 6);

'''''

==== Matrix4x4.createSkewZY()

Usage:

[source,js]

let mat = Matrix4x4.createSkewZY(angle);

  • Description: Creates a 4x4 skew matrix that shears Z by Y.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix4x4 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix4x4.createSkewZY(Math.PI / 6);

'''''

==== Matrix4x4.createSkewXZ()

Usage:

[source,js]

let mat = Matrix4x4.createSkewXZ(angle);

  • Description: Creates a 4x4 skew matrix that shears X by Z.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix4x4 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix4x4.createSkewXZ(Math.PI / 6);

'''''

==== Matrix4x4.createSkewYZ()

Usage:

[source,js]

let mat = Matrix4x4.createSkewYZ(angle);

  • Description: Creates a 4x4 skew matrix that shears Y by Z.
  • Parameters:
    ** +angle+ (number): The skew angle in radians.
  • Return Value: A new Matrix4x4 representing the skew transformation.
  • Example:

[source,js]

let mat = Matrix4x4.createSkewYZ(Math.PI / 6);

'''''

=== Matrix4x4 Properties

Matrix4x4 provides indexed access to all 16 elements (+m00+ through +m33+).

'''''

=== Matrix4x4 Methods

==== clone()

Usage:

[source,js]

let copy = mat.clone();

  • Description: Creates a new matrix with the same values as this one.
  • Parameters: None.
  • Return Value: A new Matrix4x4 object.
  • Example:

[source,js]

let original = Matrix4x4.create(); let copy = original.clone();

'''''

==== copy()

Usage:

[source,js]

mat.copy(other);

  • Description: Copies the values from another matrix into this one.
  • Parameters:
    ** +other+ (Matrix4x4): The matrix to copy from.
  • Return Value: The matrix itself (for method chaining).

'''''

==== add()

Usage:

[source,js]

let result = mat.add(other);

  • Description: Adds another matrix to this matrix (element-wise addition).
  • Parameters:
    ** +other+ (Matrix4x4): The matrix to add.
  • Return Value: The matrix itself (for method chaining).

'''''

==== sub()

Usage:

[source,js]

let result = mat.sub(other);

  • Description: Subtracts another matrix from this matrix (element-wise subtraction).
  • Parameters:
    ** +other+ (Matrix4x4): The matrix to subtract.
  • Return Value: The matrix itself (for method chaining).

'''''

==== mul()

Usage:

[source,js]

let result = mat.mul(other);

  • Description: Multiplies this matrix by another matrix, scalar, vector, or quaternion. Matrix multiplication combines transformations. When multiplying by a vector, returns the transformed vector.
  • Parameters:
    ** +other+ (Matrix4x4, number, Vector2, Vector3, Vector4, or Quaternion): The value to multiply by.
  • Return Value: The modified matrix itself when multiplying by Matrix4x4/number/Quaternion, or a new vector when multiplying by a vector.
  • Example:

[source,js]

let projection = Matrix4x4.create(/* ... /);
let view = Matrix4x4.create(/
... */);
let model = Matrix4x4.create(); // Identity
projection.mul(view).mul(model); // Combine transformations
canvas.setProjectionMatrix(projection);

let position = Vector3.create(1, 2, 3); let transformed = model.mul(position); // Returns transformed Vector3

'''''

==== div()

Usage:

[source,js]

let result = mat.div(value);

  • Description: Divides this matrix by a scalar or another matrix (element-wise division), modifying this matrix in place.
  • Parameters:
    ** +value+ (number or Matrix4x4): The scalar or matrix to divide by.
  • Return Value: The matrix itself (for method chaining).

'''''

==== neg()

Usage:

[source,js]

let result = mat.neg();

  • Description: Negates this matrix (all elements multiplied by -1), modifying it in place.
  • Parameters: None.
  • Return Value: The matrix itself (for method chaining).

'''''

==== lerp()

Usage:

[source,js]

let result = mat.lerp(other, t);

  • Description: Performs linear interpolation between this matrix and another, modifying this matrix in place.
  • Parameters:
    ** +other+ (Matrix4x4): The target matrix.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== nlerp()

Usage:

[source,js]

let result = mat.nlerp(other, t);

  • Description: Performs normalized linear interpolation, modifying this matrix in place.
  • Parameters:
    ** +other+ (Matrix4x4): The target matrix.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== slerp()

Usage:

[source,js]

let result = mat.slerp(other, t);

  • Description: Performs spherical linear interpolation, modifying this matrix in place.
  • Parameters:
    ** +other+ (Matrix4x4): The target matrix.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== elerp()

Usage:

[source,js]

let result = mat.elerp(other, t);

  • Description: Performs exponential linear interpolation, modifying this matrix in place.
  • Parameters:
    ** +other+ (Matrix4x4): The target matrix.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== sqlerp()

Usage:

[source,js]

let result = mat.sqlerp(b, c, d, t);

  • Description: Performs squared spherical linear interpolation (squad), modifying this matrix in place.
  • Parameters:
    ** +b+ (Matrix4x4): Second control point.
    ** +c+ (Matrix4x4): Third control point.
    ** +d+ (Matrix4x4): Fourth control point.
    ** +t+ (number): The interpolation factor (0.0 to 1.0).
  • Return Value: The matrix itself (for method chaining).

'''''

==== equal()

Usage:

[source,js]

let isEqual = mat.equal(other);

  • Description: Checks if this matrix is equal to another matrix.
  • Parameters:
    ** +other+ (Matrix4x4): The matrix to compare with.
  • Return Value: 1 if equal, 0 otherwise.

'''''

==== notEqual()

Usage:

[source,js]

let notEqual = mat.notEqual(other);

  • Description: Checks if this matrix is not equal to another matrix.
  • Parameters:
    ** +other+ (Matrix4x4): The matrix to compare with.
  • Return Value: 1 if not equal, 0 otherwise.

'''''

==== toString()

Usage:

[source,js]

let str = mat.toString();

  • Description: Converts the matrix to a string representation.
  • Parameters: None.
  • Return Value: A string representation of the matrix.

'''''

=== Matrix4x4 Operator Overloading

Matrix4x4 supports operator overloading with extended capabilities:

  • Addition: +mat1 + mat2+
  • Subtraction: +mat1 - mat2+
  • Multiplication: +mat1 * mat2+, +mat * scalar+, +mat * vec+, +mat * quat+, or +vec/quat * mat+
    ** Matrix×Matrix combines transformations
    ** Matrix×Vector (Vector2/3/4) or Vector×Matrix transforms the vector and returns the transformed vector
    ** Matrix×Quaternion or Quaternion×Matrix combines transformation and rotation
  • Division: +mat / scalar+ or +mat1 / mat2+
  • Negation: +-mat+
  • Equality: +mat1 == mat2+
  • Inequality: +mat1 != mat2+

Example:

[source,js]

let transform = Matrix4x4.create(/* ... */); let position = Vector3.create(1, 2, 3); let worldPos = transform * position; // Returns transformed Vector3

'''''

== Sprite

=== Overview

The Sprite type represents a 2D image or sprite atlas region that can be rendered on screen. Sprites are created by loading them into a SpriteAtlas and then retrieved for rendering.

'''''

=== Creating Sprites

Sprites are not created directly - they are created through SpriteAtlas methods:

  • +SpriteAtlas.load()+ - Load a sprite from an image file
  • +SpriteAtlas.loadSignedDistanceFieldSprite()+ - Create an SDF sprite from SVG path data
  • +SpriteAtlas.get()+ - Retrieve a previously loaded sprite by name

'''''

=== Using Sprites

Once you have a Sprite object (from a SpriteAtlas), you can draw it using Canvas methods:

Example:

[source,js]

// Create and load sprites into an atlas
let atlas = SpriteAtlas.create();
let playerSprite = atlas.load("player", "sprites/player.png", true, 2, 1);
atlas.upload(); // Upload to GPU

// Draw the sprite
canvas.drawSpritePosition(playerSprite, Vector2.create(100, 100));

// Or with more control canvas.drawSprite( playerSprite, Vector2.create(0, 0), // Source position Vector2.create(64, 64), // Source size Vector2.create(100, 100), // Destination position Vector2.create(128, 128) // Destination size (scaled) );

'''''

=== Sprite Canvas Drawing Methods

Sprites can be drawn using these Canvas methods:

  • +canvas.drawSprite(sprite, srcPos, srcSize, destPos, destSize)+
  • +canvas.drawSpriteOriginRotation(sprite, srcPos, srcSize, destPos, destSize, origin, angle)+
  • +canvas.drawSpritePosition(sprite, position)+

See the Canvas API documentation for full details on these methods.

'''''

=== Sprite Methods

==== getWidth()

Usage:

[source,js]

let width = sprite.getWidth();

  • Description: Returns the width of the sprite in pixels.
  • Parameters: None.
  • Return Value: The sprite width as a number.

'''''

==== getHeight()

Usage:

[source,js]

let height = sprite.getHeight();

  • Description: Returns the height of the sprite in pixels.
  • Parameters: None.
  • Return Value: The sprite height as a number.

'''''

==== getName()

Usage:

[source,js]

let name = sprite.getName();

  • Description: Returns the name of the sprite as specified when loading.
  • Parameters: None.
  • Return Value: The sprite name as a string.

'''''

==== getTrimmedWidth()

Usage:

[source,js]

let width = sprite.getTrimmedWidth();

  • Description: Returns the trimmed width of the sprite (after transparent pixel trimming).
  • Parameters: None.
  • Return Value: The trimmed sprite width as a number.

'''''

==== getTrimmedHeight()

Usage:

[source,js]

let height = sprite.getTrimmedHeight();

  • Description: Returns the trimmed height of the sprite (after transparent pixel trimming).
  • Parameters: None.
  • Return Value: The trimmed sprite height as a number.

'''''

==== getOffsetX()

Usage:

[source,js]

let offsetX = sprite.getOffsetX();

  • Description: Returns the X offset of the trimmed sprite region from the original.
  • Parameters: None.
  • Return Value: The X offset as a number.

'''''

==== getOffsetY()

Usage:

[source,js]

let offsetY = sprite.getOffsetY();

  • Description: Returns the Y offset of the trimmed sprite region from the original.
  • Parameters: None.
  • Return Value: The Y offset as a number.

'''''

==== getTrimOffset()

Usage:

[source,js]

let offset = sprite.getTrimOffset();

  • Description: Returns the trim offset as a Vector2.
  • Parameters: None.
  • Return Value: A Vector2 with x and y offset values.
  • Example:

[source,js]

let offset = sprite.getTrimOffset(); let x = offset.x; let y = offset.y;

'''''

== SpriteAtlas

=== Overview

The SpriteAtlas type manages a collection of sprites packed into a single texture atlas for efficient rendering. It supports loading images from files and creating signed distance field sprites for vector graphics.

'''''

=== Global SpriteAtlas Object

==== SpriteAtlas.create()

Usage:

[source,js]

let atlas = SpriteAtlas.create(sRGB, depth16Bit, mipMaps, useConvexHullTrimming);

  • Description: Creates a new sprite atlas.
  • Parameters:
    ** +sRGB+ (boolean): Use sRGB color space (default: true)
    ** +depth16Bit+ (boolean): Use 16-bit depth (default: false)
    ** +mipMaps+ (boolean): Generate mipmaps (default: true)
    ** +useConvexHullTrimming+ (boolean): Use convex hull for trimming (default: false)
  • Return Value: A new SpriteAtlas object.
  • Example:

[source,js]

let atlas = SpriteAtlas.create(true, false, true, false);

'''''

=== SpriteAtlas Methods

==== load()

Usage:

[source,js]

let sprite = atlas.load(name, filename, automaticTrim, padding, trimPadding);

  • Description: Loads a sprite from an image file into the atlas.
  • Parameters:
    ** +name+ (string): Name to identify the sprite
    ** +filename+ (string): Path to the image file
    ** +automaticTrim+ (boolean): Automatically trim transparent pixels (default: false)
    ** +padding+ (number): Padding around the sprite in pixels (default: 0)
    ** +trimPadding+ (number): Extra padding for trimmed sprites (default: 0)
  • Return Value: A Sprite object.
  • Example:

[source,js]

let sprite = atlas.load("player", "sprites/player.png", true, 2, 1);

'''''

==== loadSignedDistanceFieldSprite()

Usage:

[source,js]

let sprite = atlas.loadSignedDistanceFieldSprite(name, svgPath, imageWidth, imageHeight,
automaticTrim, padding, trimPadding,
scale, offsetX, offsetY, vectorPathFillRule,
sdfVariant, protectBorder);


  • Description: Creates a signed distance field sprite from SVG path data for high-quality scalable graphics.
  • Parameters:
    ** +name+ (string): Name to identify the sprite
    ** +svgPath+ (string): SVG path data
    ** +imageWidth+ (number): Width of generated image (default: 64)
    ** +imageHeight+ (number): Height of generated image (default: 64)
    ** +automaticTrim+ (boolean): Automatically trim (default: true)
    ** +padding+ (number): Padding in pixels (default: 2)
    ** +trimPadding+ (number): Trim padding (default: 0)
    ** +scale+ (number): Scale factor (default: 1.0)
    ** +offsetX+ (number): X offset (default: 0.0)
    ** +offsetY+ (number): Y offset (default: 0.0)
    ** +vectorPathFillRule+ (number): Fill rule (0=NonZero, 1=EvenOdd, default: 0)
    ** +sdfVariant+ (number): SDF variant (default: 4 for Default)
    ** +protectBorder+ (boolean): Protect border (default: false)
  • Return Value: A Sprite object with SDF data.
  • Example:

[source,js]

let icon = atlas.loadSignedDistanceFieldSprite( "heart", "M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z", 64, 64 );

'''''

==== get()

Usage:

[source,js]

let sprite = atlas.get(name);

  • Description: Retrieves a previously loaded sprite by name.
  • Parameters:
    ** +name+ (string): Name of the sprite
  • Return Value: A Sprite object, or null if not found.
  • Example:

[source,js]

let playerSprite = atlas.get("player"); canvas.drawSpritePosition(playerSprite, Vector2.create(100, 100));

'''''

==== upload()

Usage:

[source,js]

atlas.upload();

  • Description: Uploads the atlas to GPU memory. Must be called after loading all sprites and before rendering.
  • Parameters: None.
  • Return Value: The atlas itself (for method chaining).
  • Example:

[source,js]

let atlas = SpriteAtlas.create(); atlas.load("sprite1", "img1.png"); atlas.load("sprite2", "img2.png"); atlas.upload(); // Upload to GPU

'''''

==== destroy()

Usage:

[source,js]

atlas.destroy();

  • Description: Explicitly destroys the sprite atlas and frees its resources.
  • Parameters: None.
  • Return Value: None.
  • Example:

[source,js]

let tempAtlas = SpriteAtlas.create(); // Use atlas... tempAtlas.destroy(); // Free resources

'''''

== Texture

=== Overview

The Texture type represents a Vulkan texture that can be used for rendering. Textures can be loaded from image files and used in Canvas operations.

'''''

=== Global Texture Object

==== Texture.create()

Usage:

[source,js]

let texture = Texture.create(filename, mipmaps, srgb, additionalSRGB);

  • Description: Creates a texture from an image file.
  • Parameters:
    ** +filename+ (string): Path to the image file
    ** +mipmaps+ (boolean): Whether to generate mipmaps (default: true)
    ** +srgb+ (boolean): Whether to use sRGB color space (default: false)
    ** +additionalSRGB+ (boolean): Additional sRGB flag (default: false)
  • Return Value: A new Texture object.
  • Example:

[source,js]

let myTexture = Texture.create("assets/textures/wall.png", true, false, false); canvas.setTexture(myTexture);

'''''

=== Texture Methods

==== destroy()

Usage:

[source,js]

texture.destroy();

  • Description: Explicitly destroys the texture and frees its resources.
  • Parameters: None.
  • Return Value: None.
  • Example:

[source,js]

let temp = Texture.create("temp.png"); // Use texture... temp.destroy(); // Free resources immediately

'''''

== Font

=== Overview

The Font type represents a font that can be used for text rendering.

'''''

=== Font Properties and Methods

Font objects are loaded by the host application and can be used with Canvas text drawing methods.

'''''

== CanvasFont

=== Overview

The CanvasFont type is a specialized font for Canvas-based text rendering with distance field support for high-quality text at any size.

'''''

=== Global CanvasFont Object

==== CanvasFont.create()

Usage:

[source,js]

let font = CanvasFont.create(filename, dpi, atlasSize, firstCodePoint, lastCodePoint);

  • Description: Creates a canvas font from a TrueType font file.
  • Parameters:
    ** +filename+ (string): Path to the TTF font file
    ** +dpi+ (number): DPI for font rendering (default: 96)
    ** +atlasSize+ (number): Size of the texture atlas (default: 512)
    ** +firstCodePoint+ (number): First Unicode code point to include (default: 0)
    ** +lastCodePoint+ (number): Last Unicode code point to include (default: 255)
  • Return Value: A new CanvasFont object.
  • Example:

[source,js]

let font = CanvasFont.create("fonts/roboto.ttf", 96, 512, 0, 255); canvas.setFont(font); canvas.setFontSize(32); canvas.drawText("High Quality Text", 100, 100);

'''''

=== CanvasFont Methods

==== destroy()

Usage:

[source,js]

font.destroy();

  • Description: Explicitly destroys the font and frees its resources.
  • Parameters: None.
  • Return Value: None.
  • Example:

[source,js]

let tempFont = CanvasFont.create("temp.ttf"); // Use font... tempFont.destroy(); // Free resources

'''''

== CanvasShape

=== Overview

The CanvasShape type represents a 2D vector shape created from Canvas paths that can be stroked or filled multiple times efficiently. Shapes are created by capturing Canvas path operations.

'''''

=== CanvasShape Usage

CanvasShape objects are created through Canvas methods like +getStrokeShape()+ and +getFillShape()+ after building a path.

'''''

=== CanvasShape Methods

==== destroy()

Usage:

[source,js]

shape.destroy();

  • Description: Explicitly destroys the shape and frees its resources.
  • Parameters: None.
  • Return Value: None.
  • Example:

[source,js]

canvas.beginPath(); canvas.circle(0, 0, 50); canvas.endPath(); let shape = canvas.getFillShape(); // Draw shape multiple times canvas.drawShape(shape); // When done shape.destroy();

'''''

== Canvas

=== Overview

The Canvas API provides a comprehensive 2D drawing interface similar to HTML5 Canvas but with additional features for game development. Canvas operations are hardware-accelerated using Vulkan.

'''''

=== Vector Argument Conventions

Many Canvas (and the helper functions used by Scene3D drawing calls) accept vector parameters. Each such parameter accepts any of the following three forms:

[cols="1,1,1,1",options="header"]
|===
| Type | Ghost form | Array form | Hash form

| Vector2
| +Vector2.create(x,y)+
| +[x, y]+
| +{x:…, y:…}+ (aliases: +s+/+u+ for x; +t+/+v+ for y)

| Vector3
| +Vector3.create(x,y,z)+
| +[x, y, z]+
| +{x:…, y:…, z:…}+ (aliases: +r+,+g+,+b+)

| Vector4
| +Vector4.create(x,y,z,w)+
| +[x, y, z, w]+
| +{x:…, y:…, z:…, w:…}+ (aliases: +r+,+g+,+b+,+a+)

| Matrix4x4
| +Matrix4x4.create(…)+
| +[m00, m01, …, m33]+ (16 values, row-major)
| +{…}+ (component keys)
|===

Missing hash keys default to +0.0+. Wherever a parameter is documented as +(Vector2)+, +(Vector3)+, +(Vector4)+, or +(Matrix4x4)+, all three forms above are accepted.

'''''

=== Canvas Dimensions

==== getWidth()

Usage:

[source,js]

let width = canvas.getWidth();

  • Description: Returns the width of the canvas in pixels.
  • Parameters: None.
  • Return Value: The canvas width as a number.

'''''

==== getHeight()

Usage:

[source,js]

let height = canvas.getHeight();

  • Description: Returns the height of the canvas in pixels.
  • Parameters: None.
  • Return Value: The canvas height as a number.

'''''

=== Canvas Drawing Operations

==== clear(color)

Usage:

[source,js]

canvas.clear(color);

  • Description: Clears the entire canvas with the specified color.
  • Parameters:
    ** +color+ (Vector4, array, or hash): The clear color (RGBA). See <>.
  • Return Value: The canvas itself (for method chaining).
  • Example:

[source,js]

canvas.clear(Vector4.create(0, 0, 0, 1)); // ghost form canvas.clear([0, 0, 0, 1]); // array form canvas.clear({r: 0, g: 0, b: 0, a: 1}); // hash form

'''''

==== drawFilledCircle(center, radius)

Usage:

[source,js]

canvas.drawFilledCircle(center, radius); // or canvas.drawFilledCircle(centerX, centerY, radius);

  • Description: Draws a filled circle.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position. See <>.
    *** +radius+ (number): The circle radius.
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +radius+ (number): The circle radius.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.setColor(Vector4.create(1, 0, 0, 1)); // Red (ghost form)
canvas.setColor([1, 0, 0, 1]); // Red (array form)
canvas.setColor({r: 1, g: 0, b: 0, a: 1}); // Red (hash form)

// Using Vector2 ghost: canvas.drawFilledCircle(Vector2.create(100, 100), 50); // Using array: canvas.drawFilledCircle([100, 100], 50); // Using hash: canvas.drawFilledCircle({x: 100, y: 100}, 50); // or using individual numbers: canvas.drawFilledCircle(100, 100, 50);

'''''

==== drawStrokeCircle(center, radius, strokeWidth)

Usage:

[source,js]

canvas.drawStrokeCircle(center, radius, strokeWidth); // or canvas.drawStrokeCircle(centerX, centerY, radius, strokeWidth);

  • Description: Draws a stroked circle outline.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +radius+ (number): The circle radius.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +radius+ (number): The circle radius.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.setColor(Vector4.create(0, 1, 0, 1)); // Green

// Using Vector2:
canvas.drawStrokeCircle(Vector2.create(100, 100), 50, 3.0);

// or using individual numbers:
canvas.drawStrokeCircle(100, 100, 50, 3.0);

// Compare filled vs stroked: canvas.setColor(1, 0, 0, 1); // Red canvas.drawFilledCircle(100, 100, 50); canvas.setColor(0, 1, 0, 1); // Green outline canvas.drawStrokeCircle(100, 100, 50, 2.0);

'''''

==== drawFilledEllipse(center, radius)

Usage:

[source,js]

canvas.drawFilledEllipse(center, radius); // or canvas.drawFilledEllipse(centerX, centerY, radiusX, radiusY);

  • Description: Draws a filled ellipse.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +radius+ (Vector2, array, or hash): The x and y radii.
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +radiusX+ (number): The X radius.
    *** +radiusY+ (number): The Y radius.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawFilledEllipse(Vector2.create(100, 100), Vector2.create(80, 40));

// or using individual numbers: canvas.drawFilledEllipse(100, 100, 80, 40);

'''''

==== drawStrokeEllipse(center, radius, strokeWidth)

Usage:

[source,js]

canvas.drawStrokeEllipse(center, radius, strokeWidth); // or canvas.drawStrokeEllipse(centerX, centerY, radiusX, radiusY, strokeWidth);

  • Description: Draws a stroked ellipse outline.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +radius+ (Vector2, array, or hash): The x and y radii.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +radiusX+ (number): The X radius.
    *** +radiusY+ (number): The Y radius.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawStrokeEllipse(Vector2.create(100, 100), Vector2.create(80, 40), 2.5);

// or using individual numbers: canvas.drawStrokeEllipse(100, 100, 80, 40, 2.5);

'''''

==== drawFilledRectangle(topLeft, size)

Usage:

[source,js]

canvas.drawFilledRectangle(topLeft, size); // or canvas.drawFilledRectangle(x, y, width, height);

  • Description: Draws a filled rectangle.
  • Parameters:
    ** Option A:
    *** +topLeft+ (Vector2, array, or hash): The top-left corner position.
    *** +size+ (Vector2, array, or hash): The width and height.
    ** or Option B:
    *** +x+ (number): The left X coordinate.
    *** +y+ (number): The top Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawFilledRectangle(
Vector2.create(50, 50),
Vector2.create(100, 80)
);

// or using individual numbers: canvas.drawFilledRectangle(50, 50, 100, 80);

'''''

==== drawFilledRectangleCenter(center, size)

Usage:

[source,js]

canvas.drawFilledRectangleCenter(center, size); // or canvas.drawFilledRectangleCenter(centerX, centerY, width, height);

  • Description: Draws a filled rectangle centered at the specified position.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +size+ (Vector2, array, or hash): The width and height.
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawFilledRectangleCenter(Vector2.create(200, 150), Vector2.create(100, 80));

// or using individual numbers: canvas.drawFilledRectangleCenter(200, 150, 100, 80);

'''''

==== drawStrokeRectangle(center, bounds, strokeWidth)

Usage:

[source,js]

canvas.drawStrokeRectangle(center, bounds, strokeWidth); // or canvas.drawStrokeRectangle(centerX, centerY, boundsX, boundsY, strokeWidth);

  • Description: Draws a stroked rectangle outline.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +bounds+ (Vector2, array, or hash): Half-width and half-height from center.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +boundsX+ (number): Half-width from center.
    *** +boundsY+ (number): Half-height from center.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawStrokeRectangle(Vector2.create(200, 150), Vector2.create(50, 40), 2.0);

// or using individual numbers: canvas.drawStrokeRectangle(200, 150, 50, 40, 2.0);

'''''

==== drawFilledRoundedRectangle(topLeft, size, radius)

Usage:

[source,js]

canvas.drawFilledRoundedRectangle(topLeft, size, radius); // or canvas.drawFilledRoundedRectangle(x, y, width, height, radius);

  • Description: Draws a filled rounded rectangle.
  • Parameters:
    ** Option A:
    *** +topLeft+ (Vector2, array, or hash): The top-left corner position.
    *** +size+ (Vector2, array, or hash): The width and height.
    *** +radius+ (number): The corner radius for all corners.
    ** or Option B:
    *** +x+ (number): The left X coordinate.
    *** +y+ (number): The top Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
    *** +radius+ (number): The corner radius for all corners.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawFilledRoundedRectangle(
Vector2.create(50, 50),
Vector2.create(200, 100),
15
);

// or using individual numbers: canvas.drawFilledRoundedRectangle(50, 50, 200, 100, 15);

'''''

==== drawFilledRoundedRectangleCenter(center, size, radius)

Usage:

[source,js]

canvas.drawFilledRoundedRectangleCenter(center, size, radius); // or canvas.drawFilledRoundedRectangleCenter(centerX, centerY, width, height, radius);

  • Description: Draws a filled rounded rectangle centered at the specified position.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +size+ (Vector2, array, or hash): The width and height.
    *** +radius+ (number): The corner radius for all corners.
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
    *** +radius+ (number): The corner radius for all corners.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawFilledRoundedRectangleCenter(Vector2.create(200, 150), Vector2.create(100, 80), 10);

// or using individual numbers: canvas.drawFilledRoundedRectangleCenter(200, 150, 100, 80, 10);

'''''

==== drawStrokeRoundedRectangle(topLeft, size, radius, strokeWidth)

Usage:

[source,js]

canvas.drawStrokeRoundedRectangle(topLeft, size, radius, strokeWidth); // or canvas.drawStrokeRoundedRectangle(x, y, width, height, radius, strokeWidth);

  • Description: Draws a stroked rounded rectangle outline.
  • Parameters:
    ** Option A:
    *** +topLeft+ (Vector2, array, or hash): The top-left corner position.
    *** +size+ (Vector2, array, or hash): The width and height.
    *** +radius+ (number): The corner radius for all corners.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
    ** or Option B:
    *** +x+ (number): The left X coordinate.
    *** +y+ (number): The top Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
    *** +radius+ (number): The corner radius for all corners.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawStrokeRoundedRectangle(
Vector2.create(50, 50),
Vector2.create(200, 100),
15, 2.5
);

// or using individual numbers: canvas.drawStrokeRoundedRectangle(50, 50, 200, 100, 15, 2.5);

'''''

==== drawStrokeRoundedRectangleCenter(center, bounds, radius, strokeWidth)

Usage:

[source,js]

canvas.drawStrokeRoundedRectangleCenter(center, bounds, radius, strokeWidth); // or canvas.drawStrokeRoundedRectangleCenter(centerX, centerY, boundsX, boundsY, radius, strokeWidth);

  • Description: Draws a stroked rounded rectangle outline centered at the specified position.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +bounds+ (Vector2, array, or hash): Half-width and half-height from center.
    *** +radius+ (number): The corner radius for all corners.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +boundsX+ (number): Half-width from center.
    *** +boundsY+ (number): Half-height from center.
    *** +radius+ (number): The corner radius for all corners.
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawStrokeRoundedRectangleCenter(Vector2.create(200, 150), Vector2.create(50, 40), 10, 2.5);

// or using individual numbers: canvas.drawStrokeRoundedRectangleCenter(200, 150, 50, 40, 10, 2.5);

'''''

==== drawFilledCircleArcRingSegment(center, innerRadius, outerRadius, startAngle, endAngle, gapThickness)

Usage:

[source,js]

canvas.drawFilledCircleArcRingSegment(center, innerRadius, outerRadius, startAngle, endAngle, gapThickness); // or canvas.drawFilledCircleArcRingSegment(centerX, centerY, innerRadius, outerRadius, startAngle, endAngle, gapThickness);

  • Description: Draws a filled circular arc ring segment (like a pie slice).
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +innerRadius+ (number): The inner radius.
    *** +outerRadius+ (number): The outer radius.
    *** +startAngle+ (number): The start angle in radians.
    *** +endAngle+ (number): The end angle in radians.
    *** +gapThickness+ (number): Gap thickness (default: 0.0).
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +innerRadius+ (number): The inner radius.
    *** +outerRadius+ (number): The outer radius.
    *** +startAngle+ (number): The start angle in radians.
    *** +endAngle+ (number): The end angle in radians.
    *** +gapThickness+ (number): Gap thickness (default: 0.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Draw a quarter-circle ring using Vector2:
canvas.drawFilledCircleArcRingSegment(
Vector2.create(200, 200),
30, 50,
0, Math.PI / 2,
0
);

// or using individual numbers: canvas.drawFilledCircleArcRingSegment(200, 200, 30, 50, 0, Math.PI / 2, 0);

'''''

==== drawStrokeCircleArcRingSegment(center, innerRadius, outerRadius, startAngle, endAngle, gapThickness, strokeWidth)

Usage:

[source,js]

canvas.drawStrokeCircleArcRingSegment(center, innerRadius, outerRadius, startAngle, endAngle, gapThickness, strokeWidth); // or canvas.drawStrokeCircleArcRingSegment(centerX, centerY, innerRadius, outerRadius, startAngle, endAngle, gapThickness, strokeWidth);

  • Description: Draws a stroked outline of a circular arc ring segment (like the outline of a pie slice).
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +innerRadius+ (number): The inner radius.
    *** +outerRadius+ (number): The outer radius.
    *** +startAngle+ (number): The start angle in radians.
    *** +endAngle+ (number): The end angle in radians.
    *** +gapThickness+ (number): Gap thickness (default: 0.0).
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +innerRadius+ (number): The inner radius.
    *** +outerRadius+ (number): The outer radius.
    *** +startAngle+ (number): The start angle in radians.
    *** +endAngle+ (number): The end angle in radians.
    *** +gapThickness+ (number): Gap thickness (default: 0.0).
    *** +strokeWidth+ (number): The width of the stroke (default: 1.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Draw a quarter-circle ring outline using Vector2:
canvas.drawStrokeCircleArcRingSegment(
Vector2.create(200, 200),
30, 50,
0, Math.PI / 2,
0, 2.0
);

// or using individual numbers:
canvas.drawStrokeCircleArcRingSegment(200, 200, 30, 50, 0, Math.PI / 2, 0, 2.0);

// Compare filled vs stroked: canvas.setColor(1, 0, 0, 1); canvas.drawFilledCircleArcRingSegment(100, 100, 30, 50, 0, Math.PI, 0); canvas.setColor(0, 1, 0, 1); canvas.drawStrokeCircleArcRingSegment(300, 100, 30, 50, 0, Math.PI, 0, 3.0);

'''''

==== drawTexturedRectangle(texture, topLeft, size, rotationAngle, textureArrayLayer)

Usage:

[source,js]

canvas.drawTexturedRectangle(texture, topLeft, size, rotationAngle, textureArrayLayer); // or canvas.drawTexturedRectangle(texture, x, y, width, height, rotationAngle, textureArrayLayer);

  • Description: Draws a textured rectangle using the specified texture.
  • Parameters:
    ** Option A:
    *** +texture+ (Texture): The texture to use.
    *** +topLeft+ (Vector2, array, or hash): The top-left corner position.
    *** +size+ (Vector2, array, or hash): The width and height.
    *** +rotationAngle+ (number): Rotation angle in radians (default: 0.0).
    *** +textureArrayLayer+ (number): Texture array layer index (default: 0).
    ** or Option B:
    *** +texture+ (Texture): The texture to use.
    *** +x+ (number): The left X coordinate.
    *** +y+ (number): The top Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
    *** +rotationAngle+ (number): Rotation angle in radians (default: 0.0).
    *** +textureArrayLayer+ (number): Texture array layer index (default: 0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawTexturedRectangle(
texture,
Vector2.create(0, 0),
Vector2.create(800, 600),
0, 0
);

// or using individual numbers: canvas.drawTexturedRectangle(texture, 0, 0, 800, 600, 0, 0);

'''''

==== drawTexturedRectangleCenter(texture, center, size, rotationAngle, textureArrayLayer)

Usage:

[source,js]

canvas.drawTexturedRectangleCenter(texture, center, size, rotationAngle, textureArrayLayer); // or canvas.drawTexturedRectangleCenter(texture, centerX, centerY, width, height, rotationAngle, textureArrayLayer);

  • Description: Draws a textured rectangle centered at the specified position.
  • Parameters:
    ** Option A:
    *** +texture+ (Texture): The texture to use.
    *** +center+ (Vector2, array, or hash): The center position.
    *** +size+ (Vector2, array, or hash): The width and height.
    *** +rotationAngle+ (number): Rotation angle in radians (default: 0.0).
    *** +textureArrayLayer+ (number): Texture array layer index (default: 0).
    ** or Option B:
    *** +texture+ (Texture): The texture to use.
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
    *** +rotationAngle+ (number): Rotation angle in radians (default: 0.0).
    *** +textureArrayLayer+ (number): Texture array layer index (default: 0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawTexturedRectangleCenter(
texture,
Vector2.create(400, 300),
Vector2.create(64, 64),
Math.PI / 4, 0
);

// or using individual numbers: canvas.drawTexturedRectangleCenter(texture, 400, 300, 64, 64, Math.PI / 4, 0);

'''''

==== drawSprite(sprite, srcPosition, srcSize, destPosition, destSize)

Usage:

[source,js]

canvas.drawSprite(sprite, srcPosition, srcSize, destPosition, destSize); // or canvas.drawSprite(sprite, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight);

  • Description: Draws a sprite from a source rectangle to a destination rectangle.
  • Parameters:
    ** Option A:
    *** +sprite+ (Sprite): The sprite to draw.
    *** +srcPosition+ (Vector2, array, or hash): The source position in the sprite.
    *** +srcSize+ (Vector2, array, or hash): The source size to copy from the sprite.
    *** +destPosition+ (Vector2, array, or hash): The destination position on the canvas.
    *** +destSize+ (Vector2, array, or hash): The destination size on the canvas.
    ** or Option B:
    *** +sprite+ (Sprite): The sprite to draw.
    *** +srcX+ (number): The source X position in the sprite.
    *** +srcY+ (number): The source Y position in the sprite.
    *** +srcWidth+ (number): The source width to copy from the sprite.
    *** +srcHeight+ (number): The source height to copy from the sprite.
    *** +destX+ (number): The destination X position on the canvas.
    *** +destY+ (number): The destination Y position on the canvas.
    *** +destWidth+ (number): The destination width on the canvas.
    *** +destHeight+ (number): The destination height on the canvas.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2 (copy 32x32 region from (0,0) to 64x64 at (100,100)):
canvas.drawSprite(
sprite,
Vector2.create(0, 0), Vector2.create(32, 32),
Vector2.create(100, 100), Vector2.create(64, 64)
);

// or using individual numbers: canvas.drawSprite(sprite, 0, 0, 32, 32, 100, 100, 64, 64);

'''''

==== drawSpriteOriginRotation(sprite, srcPosition, srcSize, destPosition, destSize, origin, rotation)

Usage:

[source,js]

canvas.drawSpriteOriginRotation(sprite, srcPosition, srcSize, destPosition, destSize, origin, rotation); // or canvas.drawSpriteOriginRotation(sprite, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight, originX, originY, rotation);

  • Description: Draws a sprite with custom origin and rotation from a source rectangle to a destination rectangle.
  • Parameters:
    ** Option A:
    *** +sprite+ (Sprite): The sprite to draw.
    *** +srcPosition+ (Vector2, array, or hash): The source position in the sprite.
    *** +srcSize+ (Vector2, array, or hash): The source size to copy from the sprite.
    *** +destPosition+ (Vector2, array, or hash): The destination position on the canvas.
    *** +destSize+ (Vector2, array, or hash): The destination size on the canvas.
    *** +origin+ (Vector2, array, or hash): The origin point for rotation (in sprite coordinates).
    *** +rotation+ (number): The rotation angle in radians.
    ** or Option B:
    *** +sprite+ (Sprite): The sprite to draw.
    *** +srcX+ (number): The source X position in the sprite.
    *** +srcY+ (number): The source Y position in the sprite.
    *** +srcWidth+ (number): The source width to copy from the sprite.
    *** +srcHeight+ (number): The source height to copy from the sprite.
    *** +destX+ (number): The destination X position on the canvas.
    *** +destY+ (number): The destination Y position on the canvas.
    *** +destWidth+ (number): The destination width on the canvas.
    *** +destHeight+ (number): The destination height on the canvas.
    *** +originX+ (number): The origin X coordinate for rotation.
    *** +originY+ (number): The origin Y coordinate for rotation.
    *** +rotation+ (number): The rotation angle in radians.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2 (rotate around center):
canvas.drawSpriteOriginRotation(
sprite,
Vector2.create(0, 0), Vector2.create(32, 32),
Vector2.create(100, 100), Vector2.create(64, 64),
Vector2.create(16, 16), Math.PI / 4
);

// or using individual numbers: canvas.drawSpriteOriginRotation(sprite, 0, 0, 32, 32, 100, 100, 64, 64, 16, 16, Math.PI / 4);

'''''

==== drawSpritePosition(sprite, position)

Usage:

[source,js]

canvas.drawSpritePosition(sprite, position); // or canvas.drawSpritePosition(sprite, x, y);

  • Description: Draws a sprite at the specified position with its default size.
  • Parameters:
    ** Option A:
    *** +sprite+ (Sprite): The sprite to draw.
    *** +position+ (Vector2, array, or hash): The position to draw at.
    ** or Option B:
    *** +sprite+ (Sprite): The sprite to draw.
    *** +x+ (number): The X coordinate to draw at.
    *** +y+ (number): The Y coordinate to draw at.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.drawSpritePosition(sprite, Vector2.create(50, 100));

// or using individual numbers: canvas.drawSpritePosition(sprite, 50, 100);

'''''

=== Canvas Text Drawing

==== drawText(text, position)

Usage:

[source,js]

canvas.drawText(text, position); // or canvas.drawText(text, x, y);

  • Description: Draws text at the specified position using the current font.
  • Parameters:
    ** Option A:
    *** +text+ (string): The text to draw.
    *** +position+ (Vector2, array, or hash): The position to draw at.
    ** or Option B:
    *** +text+ (string): The text to draw.
    *** +x+ (number): The X coordinate to draw at.
    *** +y+ (number): The Y coordinate to draw at.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.setFont(myFont);
canvas.setFontSize(24);
canvas.setColor(Vector4.create(1, 1, 1, 1)); // White

// Using Vector2:
canvas.drawText("Hello, World!", Vector2.create(100, 100));

// or using individual numbers: canvas.drawText("Hello, World!", 100, 100);

'''''

==== drawTextCodePoint(codePoint, position)

Usage:

[source,js]

canvas.drawTextCodePoint(codePoint, position); // or canvas.drawTextCodePoint(codePoint, x, y);

  • Description: Draws a single Unicode code point at the specified position.
  • Parameters:
    ** Option A:
    *** +codePoint+ (number): The Unicode code point.
    *** +position+ (Vector2, array, or hash): The position to draw at.
    ** or Option B:
    *** +codePoint+ (number): The Unicode code point.
    *** +x+ (number): The X coordinate to draw at.
    *** +y+ (number): The Y coordinate to draw at.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Draw a Unicode heart symbol (U+2764)
// Using Vector2:
canvas.drawTextCodePoint(0x2764, Vector2.create(100, 100));

// or using individual numbers: canvas.drawTextCodePoint(0x2764, 100, 100);

'''''

==== textWidth(text)

Usage:

[source,js]

let width = canvas.textWidth(text);

  • Description: Measures the width of text when rendered with the current font.
  • Parameters:
    ** +text+ (string): The text to measure.
  • Return Value: The text width in pixels.

'''''

==== textHeight(text)

Usage:

[source,js]

let height = canvas.textHeight(text);

  • Description: Measures the height of text when rendered with the current font.
  • Parameters:
    ** +text+ (string): The text to measure.
  • Return Value: The text height in pixels.

'''''

==== textSize(text)

Usage:

[source,js]

let size = canvas.textSize(text);

  • Description: Measures both width and height of text.
  • Parameters:
    ** +text+ (string): The text to measure.
  • Return Value: A Vector2 containing width and height.

'''''

==== textRowHeight()

Usage:

[source,js]

let rowHeight = canvas.textRowHeight();

  • Description: Returns the line height for the current font.
  • Parameters: None.
  • Return Value: The row height in pixels.

'''''

=== Canvas Path Operations

==== beginPath()

Usage:

[source,js]

canvas.beginPath();

  • Description: Begins a new path. Call this before defining path commands.
  • Parameters: None.
  • Return Value: The canvas itself.

'''''

==== moveTo(position)

Usage:

[source,js]

canvas.moveTo(position); // or canvas.moveTo(x, y);

  • Description: Moves the current path position without drawing.
  • Parameters:
    ** Option A:
    *** +position+ (Vector2, array, or hash): The position to move to.
    ** or Option B:
    *** +x+ (number): The X coordinate to move to.
    *** +y+ (number): The Y coordinate to move to.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();

// Using Vector2:
canvas.moveTo(Vector2.create(50, 50));

// or using individual numbers: canvas.moveTo(50, 50);

'''''

==== lineTo(position)

Usage:

[source,js]

canvas.lineTo(position); // or canvas.lineTo(x, y);

  • Description: Draws a line from the current position to the specified position.
  • Parameters:
    ** Option A:
    *** +position+ (Vector2, array, or hash): The end position.
    ** or Option B:
    *** +x+ (number): The end X coordinate.
    *** +y+ (number): The end Y coordinate.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();
canvas.moveTo(10, 10);

// Using Vector2:
canvas.lineTo(Vector2.create(100, 100));

// or using individual numbers:
canvas.lineTo(100, 100);

canvas.stroke();

'''''

==== quadraticCurveTo(control, end)

Usage:

[source,js]

canvas.quadraticCurveTo(control, end); // or canvas.quadraticCurveTo(controlX, controlY, endX, endY);

  • Description: Draws a quadratic Bézier curve.
  • Parameters:
    ** Option A:
    *** +control+ (Vector2, array, or hash): The control point.
    *** +end+ (Vector2, array, or hash): The end point.
    ** or Option B:
    *** +controlX+ (number): The control point X coordinate.
    *** +controlY+ (number): The control point Y coordinate.
    *** +endX+ (number): The end point X coordinate.
    *** +endY+ (number): The end point Y coordinate.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();
canvas.moveTo(10, 10);

// Using Vector2:
canvas.quadraticCurveTo(Vector2.create(50, 5), Vector2.create(90, 10));

// or using individual numbers:
canvas.quadraticCurveTo(50, 5, 90, 10);

canvas.stroke();

'''''

==== cubicCurveTo(control1, control2, end)

Usage:

[source,js]

canvas.cubicCurveTo(control1, control2, end); // or canvas.cubicCurveTo(cp1X, cp1Y, cp2X, cp2Y, endX, endY);

  • Description: Draws a cubic Bézier curve.
  • Parameters:
    ** Option A:
    *** +control1+ (Vector2, array, or hash): The first control point.
    *** +control2+ (Vector2, array, or hash): The second control point.
    *** +end+ (Vector2, array, or hash): The end point.
    ** or Option B:
    *** +cp1X+ (number): The first control point X coordinate.
    *** +cp1Y+ (number): The first control point Y coordinate.
    *** +cp2X+ (number): The second control point X coordinate.
    *** +cp2Y+ (number): The second control point Y coordinate.
    *** +endX+ (number): The end point X coordinate.
    *** +endY+ (number): The end point Y coordinate.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();
canvas.moveTo(10, 10);

// Using Vector2:
canvas.cubicCurveTo(
Vector2.create(20, 5),
Vector2.create(80, 5),
Vector2.create(90, 10)
);

// or using individual numbers:
canvas.cubicCurveTo(20, 5, 80, 5, 90, 10);

canvas.stroke();

'''''

==== arc(center, radius, startAngle, endAngle, counterClockwise)

Usage:

[source,js]

canvas.arc(center, radius, startAngle, endAngle, counterClockwise); // or canvas.arc(centerX, centerY, radius, startAngle, endAngle, counterClockwise);

  • Description: Adds an arc to the current path.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center of the arc.
    *** +radius+ (number): The arc radius.
    *** +startAngle+ (number): The start angle in radians.
    *** +endAngle+ (number): The end angle in radians.
    *** +counterClockwise+ (boolean): Whether to draw counter-clockwise.
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +radius+ (number): The arc radius.
    *** +startAngle+ (number): The start angle in radians.
    *** +endAngle+ (number): The end angle in radians.
    *** +counterClockwise+ (boolean): Whether to draw counter-clockwise.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();

// Using Vector2 (draw a quarter circle):
canvas.arc(Vector2.create(100, 100), 50, 0, Math.PI / 2, false);

// or using individual numbers:
canvas.arc(100, 100, 50, 0, Math.PI / 2, false);

canvas.stroke();

'''''

==== arcTo(point1, point2, radius)

Usage:

[source,js]

canvas.arcTo(point1, point2, radius); // or canvas.arcTo(x1, y1, x2, y2, radius);

  • Description: Adds an arc to the current path using control points.
  • Parameters:
    ** Option A:
    *** +point1+ (Vector2, array, or hash): The first control point.
    *** +point2+ (Vector2, array, or hash): The second control point.
    *** +radius+ (number): The arc radius.
    ** or Option B:
    *** +x1+ (number): The first control point X coordinate.
    *** +y1+ (number): The first control point Y coordinate.
    *** +x2+ (number): The second control point X coordinate.
    *** +y2+ (number): The second control point Y coordinate.
    *** +radius+ (number): The arc radius.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();
canvas.moveTo(10, 10);

// Using Vector2:
canvas.arcTo(Vector2.create(50, 10), Vector2.create(50, 50), 20);

// or using individual numbers:
canvas.arcTo(50, 10, 50, 50, 20);

canvas.stroke();

'''''

==== ellipse(center, radius)

Usage:

[source,js]

canvas.ellipse(center, radius); // or canvas.ellipse(centerX, centerY, radiusX, radiusY);

  • Description: Adds an ellipse to the current path.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center of the ellipse.
    *** +radius+ (Vector2, array, or hash): The x and y radii.
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +radiusX+ (number): The X radius.
    *** +radiusY+ (number): The Y radius.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();

// Using Vector2:
canvas.ellipse(Vector2.create(100, 100), Vector2.create(60, 40));

// or using individual numbers:
canvas.ellipse(100, 100, 60, 40);

canvas.stroke();

'''''

==== circle(center, radius)

Usage:

[source,js]

canvas.circle(center, radius); // or canvas.circle(centerX, centerY, radius);

  • Description: Adds a circle to the current path.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center of the circle.
    *** +radius+ (number): The circle radius.
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +radius+ (number): The circle radius.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();

// Using Vector2:
canvas.circle(Vector2.create(100, 100), 50);

// or using individual numbers:
canvas.circle(100, 100, 50);

canvas.fill();

'''''

==== rectangle(topLeft, size)

Usage:

[source,js]

canvas.rectangle(topLeft, size); // or canvas.rectangle(x, y, width, height);

  • Description: Adds a rectangle to the current path.
  • Parameters:
    ** Option A:
    *** +topLeft+ (Vector2, array, or hash): The top-left corner.
    *** +size+ (Vector2, array, or hash): The width and height.
    ** or Option B:
    *** +x+ (number): The left X coordinate.
    *** +y+ (number): The top Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();

// Using Vector2:
canvas.rectangle(Vector2.create(10, 10), Vector2.create(100, 80));

// or using individual numbers:
canvas.rectangle(10, 10, 100, 80);

canvas.stroke();

'''''

==== rectangleCenter(center, size)

Usage:

[source,js]

canvas.rectangleCenter(center, size); // or canvas.rectangleCenter(centerX, centerY, width, height);

  • Description: Adds a centered rectangle to the current path.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +size+ (Vector2, array, or hash): The width and height.
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();

// Using Vector2:
canvas.rectangleCenter(Vector2.create(100, 100), Vector2.create(80, 60));

// or using individual numbers:
canvas.rectangleCenter(100, 100, 80, 60);

canvas.fill();

'''''

==== roundedRectangle(topLeft, size, radius)

Usage:

[source,js]

canvas.roundedRectangle(topLeft, size, radius); // or canvas.roundedRectangle(x, y, width, height, radius);

  • Description: Adds a rounded rectangle to the current path.
  • Parameters:
    ** Option A:
    *** +topLeft+ (Vector2, array, or hash): The top-left corner.
    *** +size+ (Vector2, array, or hash): The width and height.
    *** +radius+ (number): The corner radius for all corners.
    ** or Option B:
    *** +x+ (number): The left X coordinate.
    *** +y+ (number): The top Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
    *** +radius+ (number): The corner radius for all corners.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();

// Using Vector2:
canvas.roundedRectangle(Vector2.create(10, 10), Vector2.create(100, 80), 15);

// or using individual numbers:
canvas.roundedRectangle(10, 10, 100, 80, 15);

canvas.stroke();

'''''

==== roundedRectangleCenter(center, size, radius)

Usage:

[source,js]

canvas.roundedRectangleCenter(center, size, radius); // or canvas.roundedRectangleCenter(centerX, centerY, width, height, radius);

  • Description: Adds a centered rounded rectangle to the current path.
  • Parameters:
    ** Option A:
    *** +center+ (Vector2, array, or hash): The center position.
    *** +size+ (Vector2, array, or hash): The width and height.
    *** +radius+ (number): The corner radius for all corners.
    ** or Option B:
    *** +centerX+ (number): The center X coordinate.
    *** +centerY+ (number): The center Y coordinate.
    *** +width+ (number): The rectangle width.
    *** +height+ (number): The rectangle height.
    *** +radius+ (number): The corner radius for all corners.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath();

// Using Vector2:
canvas.roundedRectangleCenter(Vector2.create(100, 100), Vector2.create(80, 60), 10);

// or using individual numbers:
canvas.roundedRectangleCenter(100, 100, 80, 60, 10);

canvas.fill();

'''''

==== closePath()

Usage:

[source,js]

canvas.closePath();

  • Description: Closes the current path by connecting the end to the start.
  • Parameters: None.
  • Return Value: The canvas itself.

'''''

==== endPath()

Usage:

[source,js]

canvas.endPath();

  • Description: Ends the current path definition.
  • Parameters: None.
  • Return Value: The canvas itself.

'''''

==== stroke()

Usage:

[source,js]

canvas.stroke();

  • Description: Strokes the current path with the current stroke style.
  • Parameters: None.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.beginPath(); canvas.moveTo(Vector2.create(10, 10)); canvas.lineTo(Vector2.create(100, 100)); canvas.setLineWidth(2); canvas.setColor(Vector4.create(1, 0, 0, 1)); canvas.stroke();

'''''

==== fill()

Usage:

[source,js]

canvas.fill();

  • Description: Fills the current path with the current fill style.
  • Parameters: None.
  • Return Value: The canvas itself.

'''''

=== Canvas State Management

==== push()

Usage:

[source,js]

canvas.push();

  • Description: Saves the current canvas state (transformations, styles, etc.) onto a stack.
  • Parameters: None.
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.push(); canvas.setColor(Vector4.create(1, 0, 0, 1)); // Red // ... draw something ... canvas.pop(); // Restore previous color

'''''

==== pop()

Usage:

[source,js]

canvas.pop();

  • Description: Restores the canvas state from the stack.
  • Parameters: None.
  • Return Value: The canvas itself.

'''''

==== beginTransparentShape()

Usage:

[source,js]

canvas.beginTransparentShape();

  • Description: Begins a transparent shape rendering block. All subsequent drawing operations until endTransparentShape() are rendered as a single transparent shape with correct alpha blending, eliminating overdraw artifacts from overlapping transparent geometry.
  • Parameters: None.
  • Return Value: The canvas itself.
  • Notes:
    ** This feature requires fragmentStoresAndAtomics device support
    ** Automatically ends any previous transparent shape if called while one is active
    ** Use for complex transparent shapes with overlapping geometry
  • Example:

[source,js]

// Draw overlapping transparent circles as one shape canvas.setColor(Vector4.create(1, 0, 0, 0.5)); // Semi-transparent red canvas.beginTransparentShape(); canvas.drawFilledCircle(Vector2.create(100, 100), 50); canvas.drawFilledCircle(Vector2.create(120, 100), 50); // Overlaps first circle canvas.drawFilledCircle(Vector2.create(110, 120), 50); // Overlaps both canvas.endTransparentShape(); // Result: One transparent shape without overdraw darkening

'''''

==== endTransparentShape()

Usage:

[source,js]

canvas.endTransparentShape();

  • Description: Ends the current transparent shape rendering block and composites the accumulated coverage to the framebuffer.
  • Parameters: None.
  • Return Value: The canvas itself.
  • Notes:
    ** Must be called after beginTransparentShape() to complete the shape
    ** Only executes if a transparent shape is currently active
    ** Automatically flushes pending geometry
  • Example:

[source,js]

canvas.beginTransparentShape(); // ... draw multiple overlapping transparent elements ... canvas.endTransparentShape();

'''''

==== flush()

Usage:

[source,js]

canvas.flush();

  • Description: Flushes pending draw commands to the GPU.
  • Parameters: None.
  • Return Value: The canvas itself.

'''''

=== Canvas Properties (Getters and Setters)

==== getClipRect()

Usage:

[source,js]

let rect = canvas.getClipRect();

  • Description: Returns the current clipping rectangle as a Vector4 (x, y, width, height).
  • Parameters: None.
  • Return Value: Vector4 representing the clipping rectangle.
  • Example:

[source,js]

let clipRect = canvas.getClipRect(); puts("Clip rect: " + clipRect.toString());

'''''

==== setClipRect(leftTop, widthHeight)

Usage:

[source,js]

canvas.setClipRect(leftTop, widthHeight); // or canvas.setClipRect(x, y, width, height);

  • Description: Sets the clipping rectangle to restrict rendering to a specific area.
  • Parameters:
    ** Option A:
    *** +leftTop+ (Vector2, array, or hash): Top-left corner position.
    *** +widthHeight+ (Vector2, array, or hash): Width and height.
    ** or Option B:
    *** +x+ (number): The left X coordinate.
    *** +y+ (number): The top Y coordinate.
    *** +width+ (number): The width of the clip rectangle.
    *** +height+ (number): The height of the clip rectangle.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Vector2:
canvas.setClipRect(Vector2.create(10, 10), Vector2.create(200, 150));

// or using individual numbers:
canvas.setClipRect(10, 10, 200, 150);

canvas.drawFilledRectangle(Vector2.create(0, 0), Vector2.create(300, 300)); // Only the portion within the clip rect is drawn

'''''

==== setScissor()

Usage:

[source,js]

canvas.setScissor(left, top, width, height);

  • Description: Sets the scissor rectangle for hardware-accelerated clipping.
  • Parameters:
    ** +left+ (number): Left edge in pixels
    ** +top+ (number): Top edge in pixels
    ** +width+ (number): Width in pixels
    ** +height+ (number): Height in pixels
  • Return Value: None.
  • Example:

[source,js]

canvas.setScissor(0, 0, 800, 600);

'''''

==== getBlendingMode()

Usage:

[source,js]

let mode = canvas.getBlendingMode();

  • Description: Returns the current blending mode.
  • Parameters: None.
  • Return Value: Number representing the blending mode (see Canvas.BlendingMode).

'''''

==== setBlendingMode()

Usage:

[source,js]

canvas.setBlendingMode(mode);

  • Description: Sets the blending mode for compositing operations.
  • Parameters:
    ** +mode+ (number): Blending mode (use Canvas.BlendingMode constants)
  • Return Value: None.
  • Example:

[source,js]

canvas.setBlendingMode(Canvas.BlendingMode.AdditiveBlending); canvas.setColor(Vector4.create(1, 1, 1, 0.5)); canvas.drawFilledCircle(Vector2.create(100, 100), 50);

'''''

==== getLineCap()

Usage:

[source,js]

let cap = canvas.getLineCap();

  • Description: Returns the current line cap style.
  • Parameters: None.
  • Return Value: Number representing the line cap style (see Canvas.LineCap).

'''''

==== setLineCap()

Usage:

[source,js]

canvas.setLineCap(cap);

  • Description: Sets the line cap style for path strokes.
  • Parameters:
    ** +cap+ (number): Line cap style (use Canvas.LineCap constants)
  • Return Value: None.
  • Example:

[source,js]

canvas.setLineCap(Canvas.LineCap.Round); canvas.setLineWidth(10); canvas.beginPath(); canvas.moveTo(Vector2.create(10, 100)); canvas.lineTo(Vector2.create(200, 100)); canvas.stroke();

'''''

==== getLineJoin()

Usage:

[source,js]

let join = canvas.getLineJoin();

  • Description: Returns the current line join style.
  • Parameters: None.
  • Return Value: Number representing the line join style (see Canvas.LineJoin).

'''''

==== setLineJoin()

Usage:

[source,js]

canvas.setLineJoin(join);

  • Description: Sets the line join style for path corners.
  • Parameters:
    ** +join+ (number): Line join style (use Canvas.LineJoin constants)
  • Return Value: None.
  • Example:

[source,js]

canvas.setLineJoin(Canvas.LineJoin.Miter); canvas.setLineWidth(10); canvas.beginPath(); canvas.moveTo(Vector2.create(10, 10)); canvas.lineTo(Vector2.create(100, 10)); canvas.lineTo(Vector2.create(100, 100)); canvas.stroke();

'''''

==== getLineWidth()

Usage:

[source,js]

let width = canvas.getLineWidth();

  • Description: Returns the current line width in pixels.
  • Parameters: None.
  • Return Value: Number representing the line width.

'''''

==== setLineWidth()

Usage:

[source,js]

canvas.setLineWidth(width);

  • Description: Sets the line width for path strokes.
  • Parameters:
    ** +width+ (number): Line width in pixels
  • Return Value: None.
  • Example:

[source,js]

canvas.setLineWidth(5); canvas.beginPath(); canvas.circle(Vector2.create(100, 100), 50); canvas.stroke();

'''''

==== getMiterLimit()

Usage:

[source,js]

let limit = canvas.getMiterLimit();

  • Description: Returns the current miter limit for line joins.
  • Parameters: None.
  • Return Value: Number representing the miter limit.

'''''

==== setMiterLimit()

Usage:

[source,js]

canvas.setMiterLimit(limit);

  • Description: Sets the miter limit to control sharp corners in path strokes.
  • Parameters:
    ** +limit+ (number): Miter limit value
  • Return Value: None.
  • Example:

[source,js]

canvas.setMiterLimit(10); canvas.setLineJoin(Canvas.LineJoin.Miter);

'''''

==== getZPosition()

Usage:

[source,js]

let z = canvas.getZPosition();

  • Description: Returns the current Z position for depth sorting.
  • Parameters: None.
  • Return Value: Number representing the Z position.

'''''

==== setZPosition()

Usage:

[source,js]

canvas.setZPosition(z);

  • Description: Sets the Z position for depth sorting of drawn elements.
  • Parameters:
    ** +z+ (number): Z position (higher values are drawn on top)
  • Return Value: None.
  • Example:

[source,js]

canvas.setZPosition(0); canvas.drawFilledRectangle(Vector2.create(10, 10), Vector2.create(100, 100)); canvas.setZPosition(1); canvas.drawFilledCircle(Vector2.create(60, 60), 40); // Drawn on top

'''''

==== getTextHorizontalAlignment()

Usage:

[source,js]

let align = canvas.getTextHorizontalAlignment();

  • Description: Returns the current horizontal text alignment.
  • Parameters: None.
  • Return Value: Number representing the alignment (see Canvas.TextHorizontalAlignment).

'''''

==== setTextHorizontalAlignment()

Usage:

[source,js]

canvas.setTextHorizontalAlignment(alignment);

  • Description: Sets the horizontal text alignment.
  • Parameters:
    ** +alignment+ (number): Alignment mode (use Canvas.TextHorizontalAlignment constants)
  • Return Value: None.
  • Example:

[source,js]

canvas.setTextHorizontalAlignment(Canvas.TextHorizontalAlignment.Center); canvas.drawText("Centered Text", Vector2.create(400, 300));

'''''

==== getTextVerticalAlignment()

Usage:

[source,js]

let align = canvas.getTextVerticalAlignment();

  • Description: Returns the current vertical text alignment.
  • Parameters: None.
  • Return Value: Number representing the alignment (see Canvas.TextVerticalAlignment).

'''''

==== setTextVerticalAlignment()

Usage:

[source,js]

canvas.setTextVerticalAlignment(alignment);

  • Description: Sets the vertical text alignment.
  • Parameters:
    ** +alignment+ (number): Alignment mode (use Canvas.TextVerticalAlignment constants)
  • Return Value: None.
  • Example:

[source,js]

canvas.setTextVerticalAlignment(Canvas.TextVerticalAlignment.Middle); canvas.drawText("Middle Aligned", Vector2.create(100, 300));

'''''

==== getFont()

Usage:

[source,js]

let font = canvas.getFont();

  • Description: Returns the current font object.
  • Parameters: None.
  • Return Value: Font object.

'''''

==== setFont()

Usage:

[source,js]

canvas.setFont(font);

  • Description: Sets the current font for text rendering.
  • Parameters:
    ** +font+ (Font or CanvasFont): Font object to use
  • Return Value: None.
  • Example:

[source,js]

let myFont = CanvasFont.create("fonts/arial.ttf", 96, 512); canvas.setFont(myFont); canvas.drawText("Custom Font", Vector2.create(100, 100));

'''''

==== getFontSize()

Usage:

[source,js]

let size = canvas.getFontSize();

  • Description: Returns the current font size in pixels.
  • Parameters: None.
  • Return Value: Number representing the font size.

'''''

==== setFontSize()

Usage:

[source,js]

canvas.setFontSize(size);

  • Description: Sets the font size for text rendering.
  • Parameters:
    ** +size+ (number): Font size in pixels
  • Return Value: None.
  • Example:

[source,js]

canvas.setFontSize(24); canvas.drawText("24px Text", Vector2.create(10, 50)); canvas.setFontSize(48); canvas.drawText("48px Text", Vector2.create(10, 100));

'''''

==== getTexture()

Usage:

[source,js]

let texture = canvas.getTexture();

  • Description: Returns the current texture.
  • Parameters: None.
  • Return Value: Texture object or null.

'''''

==== setTexture()

Usage:

[source,js]

canvas.setTexture(texture);

  • Description: Sets the current texture for textured fills.
  • Parameters:
    ** +texture+ (Texture): Texture object to use
  • Return Value: None.
  • Example:

[source,js]

let tex = Texture.create("pattern.png"); canvas.setTexture(tex); canvas.setFillStyle(Canvas.FillStyle.Image); canvas.drawFilledRectangle(Vector2.create(0, 0), Vector2.create(200, 200));

'''''

==== getMaskTexture()

Usage:

[source,js]

let maskTex = canvas.getMaskTexture();

  • Description: Returns the current mask texture.
  • Parameters: None.
  • Return Value: Texture object or null.

'''''

==== setMaskTexture()

Usage:

[source,js]

canvas.setMaskTexture(texture);

  • Description: Sets the mask texture for advanced masking effects.
  • Parameters:
    ** +texture+ (Texture): Mask texture object
  • Return Value: None.

'''''

==== getFillStyle()

Usage:

[source,js]

let style = canvas.getFillStyle();

  • Description: Returns the current fill style.
  • Parameters: None.
  • Return Value: Number representing the fill style (see Canvas.FillStyle).

'''''

==== setFillStyle()

Usage:

[source,js]

canvas.setFillStyle(style);

  • Description: Sets the fill style for shapes.
  • Parameters:
    ** +style+ (number): Fill style (use Canvas.FillStyle constants)
  • Return Value: None.
  • Example:

[source,js]

canvas.setFillStyle(Canvas.FillStyle.LinearGradient); canvas.setStartColor(Vector4.create(1, 0, 0, 1)); // Red canvas.setStopColor(Vector4.create(0, 0, 1, 1)); // Blue canvas.drawFilledRectangle(Vector2.create(0, 0), Vector2.create(200, 200));

'''''

==== getFillRule()

Usage:

[source,js]

let rule = canvas.getFillRule();

  • Description: Returns the current fill rule.
  • Parameters: None.
  • Return Value: Number representing the fill rule (see Canvas.FillRule).

'''''

==== setFillRule()

Usage:

[source,js]

canvas.setFillRule(rule);

  • Description: Sets the fill rule for complex paths.
  • Parameters:
    ** +rule+ (number): Fill rule (use Canvas.FillRule constants)
  • Return Value: None.
  • Example:

[source,js]

canvas.setFillRule(Canvas.FillRule.EvenOdd); canvas.beginPath(); // Draw complex self-intersecting path canvas.fill();

'''''

==== getFillWrapMode()

Usage:

[source,js]

let mode = canvas.getFillWrapMode();

  • Description: Returns the current fill wrap mode.
  • Parameters: None.
  • Return Value: Number representing the wrap mode (see Canvas.FillWrapMode).

'''''

==== setFillWrapMode()

Usage:

[source,js]

canvas.setFillWrapMode(mode);

  • Description: Sets the fill wrap mode for textured fills.
  • Parameters:
    ** +mode+ (number): Wrap mode (use Canvas.FillWrapMode constants)
  • Return Value: None.
  • Example:

[source,js]

canvas.setFillWrapMode(Canvas.FillWrapMode.WrappedRepeat); canvas.setFillStyle(Canvas.FillStyle.Image);

'''''

==== getColor()

Usage:

[source,js]

let color = canvas.getColor();

  • Description: Returns the current drawing color.
  • Parameters: None.
  • Return Value: Vector4 representing RGBA color.

'''''

==== setColor(color)

Usage:

[source,js]

canvas.setColor(color); // or canvas.setColor(r, g, b, a);

  • Description: Sets the current drawing color.
  • Parameters:
    ** Option A:
    *** +color+ (Vector4, array, or hash): RGBA color (components 0.0-1.0). See <>.
    ** or Option B:
    *** +r+ (number): Red component (0.0-1.0).
    *** +g+ (number): Green component (0.0-1.0).
    *** +b+ (number): Blue component (0.0-1.0).
    *** +a+ (number): Alpha component (0.0-1.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.setColor(Vector4.create(1, 0, 0, 1)); // ghost form
canvas.setColor([1, 0, 0, 1]); // array form
canvas.setColor({r: 1, g: 0, b: 0, a: 1}); // hash form

// or using individual numbers:
canvas.setColor(1, 0, 0, 1); // Red

canvas.drawFilledCircle(Vector2.create(100, 100), 50);

'''''

==== getStartColor()

Usage:

[source,js]

let color = canvas.getStartColor();

  • Description: Returns the gradient start color.
  • Parameters: None.
  • Return Value: Vector4 representing RGBA color.

'''''

==== setStartColor(color)

Usage:

[source,js]

canvas.setStartColor(color); // or canvas.setStartColor(r, g, b, a);

  • Description: Sets the gradient start color.
  • Parameters:
    ** Option A:
    *** +color+ (Vector4, array, or hash): RGBA color (components 0.0-1.0). See <>.
    ** or Option B:
    *** +r+ (number): Red component (0.0-1.0).
    *** +g+ (number): Green component (0.0-1.0).
    *** +b+ (number): Blue component (0.0-1.0).
    *** +a+ (number): Alpha component (0.0-1.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.setFillStyle(Canvas.FillStyle.LinearGradient);

canvas.setStartColor(Vector4.create(1, 1, 0, 1)); // ghost form
canvas.setStartColor([1, 1, 0, 1]); // array form

// or using individual numbers:
canvas.setStartColor(1, 1, 0, 1); // Yellow

canvas.setStopColor(Vector4.create(1, 0, 1, 1)); // Magenta

'''''

==== getStopColor()

Usage:

[source,js]

let color = canvas.getStopColor();

  • Description: Returns the gradient stop color.
  • Parameters: None.
  • Return Value: Vector4 representing RGBA color.

'''''

==== setStopColor(color)

Usage:

[source,js]

canvas.setStopColor(color); // or canvas.setStopColor(r, g, b, a);

  • Description: Sets the gradient stop color.
  • Parameters:
    ** Option A:
    *** +color+ (Vector4, array, or hash): RGBA color (components 0.0-1.0). See <>.
    ** or Option B:
    *** +r+ (number): Red component (0.0-1.0).
    *** +g+ (number): Green component (0.0-1.0).
    *** +b+ (number): Blue component (0.0-1.0).
    *** +a+ (number): Alpha component (0.0-1.0).
  • Return Value: The canvas itself.
  • Example:

[source,js]

canvas.setFillStyle(Canvas.FillStyle.LinearGradient);
canvas.setStartColor(Vector4.create(1, 1, 0, 1)); // Yellow

canvas.setStopColor(Vector4.create(1, 0, 1, 1)); // Magenta

// or using individual numbers: canvas.setStopColor(1, 0, 1, 1); // Magenta

'''''

==== getProjectionMatrix()

Usage:

[source,js]

let matrix = canvas.getProjectionMatrix();

  • Description: Returns the current projection matrix.
  • Parameters: None.
  • Return Value: Matrix4x4 object.

'''''

==== setProjectionMatrix(matrix)

Usage:

[source,js]

canvas.setProjectionMatrix(matrix); // or canvas.setProjectionMatrix(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33);

  • Description: Sets the projection matrix for 3D transforms.
  • Parameters:
    ** Option A:
    *** +matrix+ (Matrix4x4, array [16], or hash): Projection matrix. See <>.
    ** or Option B:
    *** +m00, m01, m02, m03+ (numbers): First row of the matrix.
    *** +m10, m11, m12, m13+ (numbers): Second row of the matrix.
    *** +m20, m21, m22, m23+ (numbers): Third row of the matrix.
    *** +m30, m31, m32, m33+ (numbers): Fourth row of the matrix.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Matrix4x4:
let matrix = Matrix4x4.create(1, 0. 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
canvas.setProjectionMatrix(matrix);

// or using individual numbers (identity matrix): canvas.setProjectionMatrix( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 );

'''''

==== getViewMatrix()

Usage:

[source,js]

let matrix = canvas.getViewMatrix();

  • Description: Returns the current view matrix.
  • Parameters: None.
  • Return Value: Matrix4x4 object.

'''''

==== setViewMatrix(matrix)

Usage:

[source,js]

canvas.setViewMatrix(matrix); // or canvas.setViewMatrix(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33);

  • Description: Sets the view matrix for camera transforms.
  • Parameters:
    ** Option A:
    *** +matrix+ (Matrix4x4, array [16], or hash): View matrix. See <>.
    ** or Option B:
    *** +m00, m01, m02, m03+ (numbers): First row of the matrix.
    *** +m10, m11, m12, m13+ (numbers): Second row of the matrix.
    *** +m20, m21, m22, m23+ (numbers): Third row of the matrix.
    *** +m30, m31, m32, m33+ (numbers): Fourth row of the matrix.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Matrix4x4:
let matrix = Matrix4x4.create(1, 0. 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
canvas.setViewMatrix(matrix);

// or using individual numbers (identity matrix): canvas.setViewMatrix( 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 );

'''''

==== getModelMatrix()

Usage:

[source,js]

let matrix = canvas.getModelMatrix();

  • Description: Returns the current model matrix.
  • Parameters: None.
  • Return Value: Matrix4x4 object.

'''''

==== setModelMatrix(matrix)

Usage:

[source,js]

canvas.setModelMatrix(matrix); // or canvas.setModelMatrix(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33);

  • Description: Sets the model matrix for object transforms.
  • Parameters:
    ** Option A:
    *** +matrix+ (Matrix4x4, array [16], or hash): Model matrix. See <>.
    ** or Option B:
    *** +m00, m01, m02, m03+ (numbers): First row of the matrix.
    *** +m10, m11, m12, m13+ (numbers): Second row of the matrix.
    *** +m20, m21, m22, m23+ (numbers): Third row of the matrix.
    *** +m30, m31, m32, m33+ (numbers): Fourth row of the matrix.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Matrix4x4.create():
let matrix = Matrix4x4.create(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
canvas.setModelMatrix(matrix);

// or using individual numbers (identity matrix):
canvas.setModelMatrix(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);

canvas.drawFilledRectangle(Vector2.create(0, 0), Vector2.create(100, 100));

'''''

==== getFillMatrix()

Usage:

[source,js]

let matrix = canvas.getFillMatrix();

  • Description: Returns the current fill matrix for texture/gradient transforms.
  • Parameters: None.
  • Return Value: Matrix4x4 object.

'''''

==== setFillMatrix(matrix)

Usage:

[source,js]

canvas.setFillMatrix(matrix); // or canvas.setFillMatrix(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33);

  • Description: Sets the fill matrix for transforming fill textures/gradients.
  • Parameters:
    ** Option A:
    *** +matrix+ (Matrix4x4, array [16], or hash): Fill transformation matrix. See <>.
    ** or Option B:
    *** +m00, m01, m02, m03+ (numbers): First row of the matrix.
    *** +m10, m11, m12, m13+ (numbers): Second row of the matrix.
    *** +m20, m21, m22, m23+ (numbers): Third row of the matrix.
    *** +m30, m31, m32, m33+ (numbers): Fourth row of the matrix.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Matrix4x4.create():
let matrix = Matrix4x4.create(2, 0, 0, 0,
0, 2, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
canvas.setFillMatrix(matrix);

// or using individual numbers (scale by 2):
canvas.setFillMatrix(2, 0, 0, 0,
0, 2, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);


'''''

==== getMaskMatrix()

Usage:

[source,js]

let matrix = canvas.getMaskMatrix();

  • Description: Returns the current mask matrix.
  • Parameters: None.
  • Return Value: Matrix4x4 object.

'''''

==== setMaskMatrix(matrix)

Usage:

[source,js]

canvas.setMaskMatrix(matrix); // or canvas.setMaskMatrix(m00, m01, m02, m03, m10, m11, m12, m13, m20, m21, m22, m23, m30, m31, m32, m33);

  • Description: Sets the mask matrix for transforming mask textures.
  • Parameters:
    ** Option A:
    *** +matrix+ (Matrix4x4, array [16], or hash): Mask transformation matrix. See <>.
    ** or Option B:
    *** +m00, m01, m02, m03+ (numbers): First row of the matrix.
    *** +m10, m11, m12, m13+ (numbers): Second row of the matrix.
    *** +m20, m21, m22, m23+ (numbers): Third row of the matrix.
    *** +m30, m31, m32, m33+ (numbers): Fourth row of the matrix.
  • Return Value: The canvas itself.
  • Example:

[source,js]

// Using Matrix4x4.create():
let matrix = Matrix4x4.create(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);
canvas.setMaskMatrix(matrix);

// or using individual numbers (identity matrix):
canvas.setMaskMatrix(1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1);


'''''

==== setStrokePattern()

Usage:

[source,js]

canvas.setStrokePattern(pattern);

  • Description: Sets a stroke pattern for dashed/dotted lines.
  • Parameters:
    ** +pattern+ (string): Pattern string
  • Return Value: None.

'''''

==== drawShape()

Usage:

[source,js]

canvas.drawShape(shape);

  • Description: Draws a previously created CanvasShape.
  • Parameters:
    ** +shape+ (CanvasShape): Shape object to draw
  • Return Value: None.
  • Example:

[source,js]

canvas.beginPath(); canvas.circle(Vector2.create(0, 0), 50); canvas.endPath(); let shape = canvas.getFillShape(); // Draw the shape multiple times canvas.drawShape(shape);

'''''

==== getStrokeShape()

Usage:

[source,js]

let shape = canvas.getStrokeShape();

  • Description: Returns a CanvasShape from the current path's stroke.
  • Parameters: None.
  • Return Value: CanvasShape object.

'''''

==== getFillShape()

Usage:

[source,js]

let shape = canvas.getFillShape();

  • Description: Returns a CanvasShape from the current path's fill.
  • Parameters: None.
  • Return Value: CanvasShape object.
  • Example:

[source,js]

canvas.beginPath(); canvas.rectangle(Vector2.create(0, 0), Vector2.create(100, 100)); canvas.endPath(); let fillShape = canvas.getFillShape(); // Reuse this shape for efficient rendering for (let i = 0; i < 10; i++) { canvas.push(); canvas.setModelMatrix(/* transform */); canvas.drawShape(fillShape); canvas.pop(); }

'''''

=== Canvas Enumerations

The Canvas namespace provides several enumeration objects:

==== Canvas.BlendingMode

Blending modes for compositing:

  • +None+: No blending
  • +NoDiscard+: No discard blending
  • +AlphaBlending+: Standard alpha blending
  • +AdditiveBlending+: Additive blending
  • +OnlyDepth+: Only depth rendering

Example:

[source,js]

canvas.setBlendingMode(Canvas.BlendingMode.AlphaBlending); canvas.setBlendingMode(Canvas.BlendingMode.AdditiveBlending); // For glow effects

'''''

==== Canvas.LineCap

Line cap styles:

  • +Butt+: Butt line cap (flat end)
  • +Square+: Square line cap (extends half line width)
  • +Round+: Round line cap

Example:

[source,js]

canvas.setLineCap(Canvas.LineCap.Round);

'''''

==== Canvas.LineJoin

Line join styles:

  • +Bevel+: Beveled line join
  • +Miter+: Mitered line join
  • +Round+: Rounded line join

Example:

[source,js]

canvas.setLineJoin(Canvas.LineJoin.Round);

'''''

==== Canvas.FillRule

Fill rules for path filling:

  • +DoNotMatter+: Fill rule does not matter
  • +NonZero+: Non-zero winding rule
  • +EvenOdd+: Even-odd rule

Example:

[source,js]

canvas.setFillRule(Canvas.FillRule.EvenOdd);

'''''

==== Canvas.FillStyle

Fill styles:

  • +Color+: Solid color fill
  • +Image+: Image/texture fill
  • +LinearGradient+: Linear gradient fill
  • +RadialGradient+: Radial gradient fill

Example:

[source,js]

canvas.setFillStyle(Canvas.FillStyle.Color); canvas.setFillStyle(Canvas.FillStyle.LinearGradient);

'''''

==== Canvas.FillWrapMode

Texture wrap modes:

  • +None+: No wrapping
  • +WrappedRepeat+: Wrapped repeat mode
  • +MirroredRepeat+: Mirrored repeat mode

Example:

[source,js]

canvas.setFillWrapMode(Canvas.FillWrapMode.WrappedRepeat);

'''''

==== Canvas.TextHorizontalAlignment

Horizontal text alignment:

  • +Leading+: Leading alignment (left in LTR, right in RTL)
  • +Center+: Center alignment
  • +Tailing+: Tailing alignment (right in LTR, left in RTL)

Example:

[source,js]

canvas.setTextHorizontalAlignment(Canvas.TextHorizontalAlignment.Center);

'''''

==== Canvas.TextVerticalAlignment

Vertical text alignment:

  • +Leading+: Leading alignment (top)
  • +Middle+: Middle alignment (vertical center)
  • +Tailing+: Tailing alignment (bottom)

Example:

[source,js]

canvas.setTextVerticalAlignment(Canvas.TextVerticalAlignment.Middle);

'''''

==== Canvas.VectorPathFillRule

Vector path fill rules:

  • +NonZero+: Non-zero winding rule
  • +EvenOdd+: Even-odd rule

'''''

==== Canvas.SignedDistanceField2DVariant

SDF rendering variants for advanced text and shape rendering:

  • +SDF+: Standard signed distance field
  • +SSAASDF+: Super-sampled anti-aliased SDF
  • +GSDF+: Gradient-based SDF
  • +MSDF+: Multi-channel signed distance field
  • +Default+: Default SDF variant

Example:

[source,js]

// SDF variants are typically set at the system level // and used internally for high-quality text rendering

'''''

== Input

=== Overview

The Input API provides access to keyboard, mouse, and pointer events. Event data is passed through hash objects containing event information.

'''''

=== Input Event Types

The Input.EventType enumeration defines the following event types:

  • +EVENT_NONE+: No event
  • +EVENT_KEY+: Keyboard event
  • +EVENT_POINTER+: Pointer/mouse event
  • +EVENT_SCROLLED+: Scroll wheel event
  • +EVENT_DRAGDROPFILE+: Drag and drop file event

'''''

=== Key Codes

The Input.KeyCode enumeration provides constants for all keyboard keys:

==== Special Keys

  • +KEYCODE_QUIT+
  • +KEYCODE_ANYKEY+
  • +KEYCODE_UNKNOWN+
  • +KEYCODE_FIRST+
  • +KEYCODE_BACKSPACE+
  • +KEYCODE_TAB+
  • +KEYCODE_RETURN+
  • +KEYCODE_PAUSE+
  • +KEYCODE_ESCAPE+
  • +KEYCODE_SPACE+
  • +KEYCODE_DELETE+

==== Punctuation and Symbol Keys

  • +KEYCODE_EXCLAIM+ (!)
  • +KEYCODE_QUOTEDBL+ (")
  • +KEYCODE_HASH+ (#)
  • +KEYCODE_DOLLAR+ ($)
  • +KEYCODE_AMPERSAND+ (&)
  • +KEYCODE_APOSTROPHE+ (')
  • +KEYCODE_LEFTPAREN+ (()
  • +KEYCODE_RIGHTPAREN+ ())
  • +KEYCODE_ASTERISK+ (*)
  • +KEYCODE_PLUS+ (+)
  • +KEYCODE_COMMA+ (,)
  • +KEYCODE_MINUS+ (-)
  • +KEYCODE_PERIOD+ (.)
  • +KEYCODE_SLASH+ (/)
  • +KEYCODE_COLON+ (:)
  • +KEYCODE_SEMICOLON+ (;)
  • +KEYCODE_LESS+ (<)
  • +KEYCODE_EQUALS+ (=)
  • +KEYCODE_GREATER+ (>)
  • +KEYCODE_QUESTION+ (?)
  • +KEYCODE_AT+ (@)
  • +KEYCODE_LEFTBRACKET+ ([)
  • +KEYCODE_BACKSLASH+ ()
  • +KEYCODE_RIGHTBRACKET+ (])
  • +KEYCODE_CARET+ (^)
  • +KEYCODE_UNDERSCORE+ (_)
  • +KEYCODE_BACKQUOTE+ (`)
  • +KEYCODE_LEFTBRACE+ ({)
  • +KEYCODE_PIPE+ (|)
  • +KEYCODE_RIGHTBRACE+ (})
  • +KEYCODE_TILDE+ (~)

==== Alphanumeric Keys

  • +KEYCODE_0+ through +KEYCODE_9+
  • +KEYCODE_A+ through +KEYCODE_Z+

==== Function Keys

  • +KEYCODE_F1+ through +KEYCODE_F24+

==== Arrow Keys

  • +KEYCODE_UP+
  • +KEYCODE_DOWN+
  • +KEYCODE_LEFT+
  • +KEYCODE_RIGHT+

==== Modifier Keys

  • +KEYCODE_LSHIFT+, +KEYCODE_RSHIFT+
  • +KEYCODE_LCTRL+, +KEYCODE_RCTRL+
  • +KEYCODE_LALT+, +KEYCODE_RALT+
  • +KEYCODE_LGUI+, +KEYCODE_RGUI+

==== Numpad Keys

  • +KEYCODE_KP0+ through +KEYCODE_KP9+
  • +KEYCODE_KP_PERIOD+, +KEYCODE_KP_DIVIDE+, +KEYCODE_KP_MULTIPLY+
  • +KEYCODE_KP_MINUS+, +KEYCODE_KP_PLUS+, +KEYCODE_KP_ENTER+, +KEYCODE_KP_EQUALS+

==== Advanced Numpad Keys

  • +KEYCODE_KP_00+, +KEYCODE_KP_000+
  • +KEYCODE_KP_LEFTPAREN+, +KEYCODE_KP_RIGHTPAREN+
  • +KEYCODE_KP_LEFTBRACE+, +KEYCODE_KP_RIGHTBRACE+
  • +KEYCODE_KP_TAB+, +KEYCODE_KP_BACKSPACE+
  • +KEYCODE_KP_A+ through +KEYCODE_KP_F+
  • +KEYCODE_KP_XOR+, +KEYCODE_KP_POWER+, +KEYCODE_KP_PERCENT+
  • +KEYCODE_KP_LESS+, +KEYCODE_KP_GREATER+
  • +KEYCODE_KP_AMPERSAND+, +KEYCODE_KP_DBLAMPERSAND+
  • +KEYCODE_KP_VERTICALBAR+, +KEYCODE_KP_DBLVERTICALBAR+
  • +KEYCODE_KP_COLON+, +KEYCODE_KP_COMMA+, +KEYCODE_KP_HASH+
  • +KEYCODE_KP_SPACE+, +KEYCODE_KP_AT+, +KEYCODE_KP_EXCLAM+
  • +KEYCODE_KP_MEMSTORE+, +KEYCODE_KP_MEMRECALL+, +KEYCODE_KP_MEMCLEAR+
  • +KEYCODE_KP_MEMADD+, +KEYCODE_KP_MEMSUBTRACT+, +KEYCODE_KP_MEMMULTIPLY+, +KEYCODE_KP_MEMDIVIDE+
  • +KEYCODE_KP_PLUSMINUS+, +KEYCODE_KP_CLEAR+, +KEYCODE_KP_CLEARENTRY+
  • +KEYCODE_KP_BINARY+, +KEYCODE_KP_OCTAL+, +KEYCODE_KP_DECIMAL+, +KEYCODE_KP_HEXADECIMAL+
  • +KEYCODE_KP_EQUALSAS400+
  • +KEYCODE_THOUSANDSSEPARATOR+, +KEYCODE_DECIMALSEPARATOR+
  • +KEYCODE_CURRENCYUNIT+, +KEYCODE_CURRENCYSUBUNIT+

==== Navigation Keys

  • +KEYCODE_HOME+
  • +KEYCODE_END+
  • +KEYCODE_PAGEUP+
  • +KEYCODE_PAGEDOWN+
  • +KEYCODE_INSERT+

==== Lock Keys

  • +KEYCODE_CAPSLOCK+
  • +KEYCODE_NUMLOCK+
  • +KEYCODE_SCROLLLOCK+
  • +KEYCODE_LOCKINGCAPSLOCK+
  • +KEYCODE_LOCKINGNUMLOCK+
  • +KEYCODE_LOCKINGSCROLLLOCK+

==== System Keys

  • +KEYCODE_MODE+
  • +KEYCODE_HELP+
  • +KEYCODE_PRINTSCREEN+
  • +KEYCODE_SYSREQ+
  • +KEYCODE_MENU+
  • +KEYCODE_POWER+
  • +KEYCODE_APPLICATION+
  • +KEYCODE_SELECT+
  • +KEYCODE_STOP+
  • +KEYCODE_AGAIN+
  • +KEYCODE_UNDO+
  • +KEYCODE_CUT+
  • +KEYCODE_COPY+
  • +KEYCODE_PASTE+
  • +KEYCODE_FIND+

==== Media Keys

  • +KEYCODE_MUTE+
  • +KEYCODE_VOLUMEUP+
  • +KEYCODE_VOLUMEDOWN+
  • +KEYCODE_AUDIONEXT+
  • +KEYCODE_AUDIOPREV+
  • +KEYCODE_AUDIOSTOP+
  • +KEYCODE_AUDIOPLAY+
  • +KEYCODE_AUDIOMUTE+
  • +KEYCODE_MEDIASELECT+
  • +KEYCODE_AUDIO_FAST_FORWARD+
  • +KEYCODE_AUDIO_REWIND+

==== Application Control Keys

  • +KEYCODE_WWW+
  • +KEYCODE_MAIL+
  • +KEYCODE_CALCULATOR+
  • +KEYCODE_COMPUTER+
  • +KEYCODE_AC_SEARCH+
  • +KEYCODE_AC_HOME+
  • +KEYCODE_AC_BACK+
  • +KEYCODE_AC_FORWARD+
  • +KEYCODE_AC_STOP+
  • +KEYCODE_AC_REFRESH+
  • +KEYCODE_AC_BOOKMARKS+

==== Display and Brightness Keys

  • +KEYCODE_BRIGHTNESSDOWN+
  • +KEYCODE_BRIGHTNESSUP+
  • +KEYCODE_DISPLAYSWITCH+
  • +KEYCODE_KBDILLUMTOGGLE+
  • +KEYCODE_KBDILLUMDOWN+
  • +KEYCODE_KBDILLUMUP+
  • +KEYCODE_EJECT+
  • +KEYCODE_SLEEP+

==== International Keys

  • +KEYCODE_INTERNATIONAL1+ through +KEYCODE_INTERNATIONAL9+
  • +KEYCODE_LANG1+ through +KEYCODE_LANG9+
  • +KEYCODE_NONUSBACKSLASH+
  • +KEYCODE_NONUSHASH+
  • +KEYCODE_102ND+
  • +KEYCODE_KATAKANAHIRAGANA+
  • +KEYCODE_HENKAN+
  • +KEYCODE_MUHENKAN+
  • +KEYCODE_HANGEUL+
  • +KEYCODE_HANJA+

==== Mobile/Android Keys

  • +KEYCODE_BACK+
  • +KEYCODE_CAMERA+
  • +KEYCODE_CALL+
  • +KEYCODE_CENTER+
  • +KEYCODE_FORWARD_DEL+
  • +KEYCODE_DPAD_CENTER+, +KEYCODE_DPAD_LEFT+, +KEYCODE_DPAD_RIGHT+
  • +KEYCODE_DPAD_DOWN+, +KEYCODE_DPAD_UP+
  • +KEYCODE_ENDCALL+
  • +KEYCODE_ENVELOPE+
  • +KEYCODE_EXPLORER+
  • +KEYCODE_FOCUS+
  • +KEYCODE_GRAVE+
  • +KEYCODE_HEADSETHOOK+
  • +KEYCODE_NOTIFICATION+
  • +KEYCODE_PICTSYMBOLS+
  • +KEYCODE_SWITCH_CHARSET+

==== Game Controller Keys

  • +KEYCODE_BUTTON_CIRCLE+
  • +KEYCODE_BUTTON_A+, +KEYCODE_BUTTON_B+, +KEYCODE_BUTTON_C+
  • +KEYCODE_BUTTON_X+, +KEYCODE_BUTTON_Y+, +KEYCODE_BUTTON_Z+
  • +KEYCODE_BUTTON_L1+, +KEYCODE_BUTTON_R1+
  • +KEYCODE_BUTTON_L2+, +KEYCODE_BUTTON_R2+
  • +KEYCODE_BUTTON_THUMBL+, +KEYCODE_BUTTON_THUMBR+
  • +KEYCODE_BUTTON_START+, +KEYCODE_BUTTON_SELECT+, +KEYCODE_BUTTON_MODE+

==== Other Keys

  • +KEYCODE_ALTERASE+
  • +KEYCODE_CANCEL+
  • +KEYCODE_CLEAR+
  • +KEYCODE_PRIOR+
  • +KEYCODE_RETURN2+
  • +KEYCODE_SEPARATOR+
  • +KEYCODE_OUT+
  • +KEYCODE_OPER+
  • +KEYCODE_CLEARAGAIN+
  • +KEYCODE_CRSEL+
  • +KEYCODE_EXSEL+
  • +KEYCODE_COUNT+ (Total number of key codes)

'''''

=== Key Modifier Flags

The Input.KeyModifier enumeration provides flags for modifier key states:

  • +KEYMOD_NONE+
  • +KEYMOD_LSHIFT+
  • +KEYMOD_RSHIFT+
  • +KEYMOD_LCTRL+
  • +KEYMOD_RCTRL+
  • +KEYMOD_LALT+
  • +KEYMOD_RALT+
  • +KEYMOD_LMETA+
  • +KEYMOD_RMETA+
  • +KEYMOD_NUM+
  • +KEYMOD_CAPS+
  • +KEYMOD_MODE+
  • +KEYMOD_CTRL+
  • +KEYMOD_SHIFT+
  • +KEYMOD_ALT+
  • +KEYMOD_META+

'''''

=== Pointer Button Flags

The Input.PointerButton enumeration provides flags for pointer buttons:

  • +POINTERBUTTON_NONE+
  • +POINTERBUTTON_LEFT+
  • +POINTERBUTTON_MIDDLE+
  • +POINTERBUTTON_RIGHT+
  • +POINTERBUTTON_X1+
  • +POINTERBUTTON_X2+

'''''

=== Pointer Event Types

The Input.PointerEventTypes enumeration defines pointer/mouse event types:

  • +POINTEREVENT_DOWN+: Pointer button pressed
  • +POINTEREVENT_UP+: Pointer button released
  • +POINTEREVENT_MOTION+: Pointer moved
  • +POINTEREVENT_DRAG+: Pointer dragged (moved while button pressed)

'''''

=== Key Event Types

The Input.KeyEventTypes enumeration defines keyboard event types:

  • +KEYEVENT_DOWN+: Key pressed
  • +KEYEVENT_UP+: Key released
  • +KEYEVENT_TYPED+: Key typed (with repeat)
  • +KEYEVENT_UNICODE+: Unicode character input

'''''

=== Joystick Hat Positions

The Input.JoystickHats enumeration provides constants for joystick hat (D-pad) positions:

  • +JOYSTICK_HAT_CENTERED+: Hat centered (no direction)
  • +JOYSTICK_HAT_LEFT+: Hat pushed left
  • +JOYSTICK_HAT_RIGHT+: Hat pushed right
  • +JOYSTICK_HAT_UP+: Hat pushed up
  • +JOYSTICK_HAT_DOWN+: Hat pushed down
  • +JOYSTICK_HAT_LEFTUP+: Hat pushed left and up (diagonal)
  • +JOYSTICK_HAT_RIGHTUP+: Hat pushed right and up (diagonal)
  • +JOYSTICK_HAT_LEFTDOWN+: Hat pushed left and down (diagonal)
  • +JOYSTICK_HAT_RIGHTDOWN+: Hat pushed right and down (diagonal)
  • +JOYSTICK_HAT_NONE+: No hat input

'''''

=== Game Controller Bind Types

The Input.GameControllerBindTypes enumeration defines controller binding types:

  • +GAME_CONTROLLER_BINDTYPE_NONE+: No binding
  • +GAME_CONTROLLER_BINDTYPE_BUTTON+: Bound to a button
  • +GAME_CONTROLLER_BINDTYPE_AXIS+: Bound to an axis
  • +GAME_CONTROLLER_BINDTYPE_HAT+: Bound to a hat/D-pad

'''''

=== Game Controller Axes

The Input.GameControllerAxes enumeration defines standard game controller analog axes:

  • +GAME_CONTROLLER_AXIS_INVALID+: Invalid axis
  • +GAME_CONTROLLER_AXIS_LEFTX+: Left stick X axis
  • +GAME_CONTROLLER_AXIS_LEFTY+: Left stick Y axis
  • +GAME_CONTROLLER_AXIS_RIGHTX+: Right stick X axis
  • +GAME_CONTROLLER_AXIS_RIGHTY+: Right stick Y axis
  • +GAME_CONTROLLER_AXIS_TRIGGERLEFT+: Left trigger axis
  • +GAME_CONTROLLER_AXIS_TRIGGERRIGHT+: Right trigger axis
  • +GAME_CONTROLLER_AXIS_MAX+: Maximum axis index

'''''

=== Game Controller Buttons

The Input.GameControllerButtons enumeration defines standard game controller buttons:

  • +GAME_CONTROLLER_BUTTON_INVALID+: Invalid button
  • +GAME_CONTROLLER_BUTTON_A+: A button (Xbox) / Cross (PlayStation)
  • +GAME_CONTROLLER_BUTTON_B+: B button (Xbox) / Circle (PlayStation)
  • +GAME_CONTROLLER_BUTTON_X+: X button (Xbox) / Square (PlayStation)
  • +GAME_CONTROLLER_BUTTON_Y+: Y button (Xbox) / Triangle (PlayStation)
  • +GAME_CONTROLLER_BUTTON_BACK+: Back/Select button
  • +GAME_CONTROLLER_BUTTON_GUIDE+: Guide/Home button
  • +GAME_CONTROLLER_BUTTON_START+: Start button
  • +GAME_CONTROLLER_BUTTON_LEFTSTICK+: Left stick click
  • +GAME_CONTROLLER_BUTTON_RIGHTSTICK+: Right stick click
  • +GAME_CONTROLLER_BUTTON_LEFTSHOULDER+: Left shoulder button (LB/L1)
  • +GAME_CONTROLLER_BUTTON_RIGHTSHOULDER+: Right shoulder button (RB/R1)
  • +GAME_CONTROLLER_BUTTON_DPAD_UP+: D-pad up
  • +GAME_CONTROLLER_BUTTON_DPAD_DOWN+: D-pad down
  • +GAME_CONTROLLER_BUTTON_DPAD_LEFT+: D-pad left
  • +GAME_CONTROLLER_BUTTON_DPAD_RIGHT+: D-pad right
  • +GAME_CONTROLLER_BUTTON_MISC1+: Misc button 1 (e.g., Xbox Share button)
  • +GAME_CONTROLLER_BUTTON_PADDLE1+: Paddle 1 (Xbox Elite)
  • +GAME_CONTROLLER_BUTTON_PADDLE2+: Paddle 2 (Xbox Elite)
  • +GAME_CONTROLLER_BUTTON_PADDLE3+: Paddle 3 (Xbox Elite)
  • +GAME_CONTROLLER_BUTTON_PADDLE4+: Paddle 4 (Xbox Elite)
  • +GAME_CONTROLLER_BUTTON_TOUCHPAD+: Touchpad button (PlayStation)
  • +GAME_CONTROLLER_BUTTON_MAX+: Maximum button index

'''''

=== Input Event Hash Structure

Input events are passed to scripts as hash objects with the following structure:

==== Key Event Hash

When +eventType+ is +EVENT_KEY+:

  • +eventType+: The event type (EVENT_KEY)
  • +keyCode+: The key code (from Input.KeyCode)
  • +modifiers+: Key modifier flags
  • +pressed+: 1 if key was pressed, 0 if released

==== Pointer Event Hash

When +eventType+ is +EVENT_POINTER+:

  • +eventType+: The event type (EVENT_POINTER)
  • +position+: Vector2 with pointer position
  • +delta+: Vector2 with movement delta
  • +buttons+: Button state flags
  • +pressure+: Pointer pressure (0.0 to 1.0)

==== Scroll Event Hash

When +eventType+ is +EVENT_SCROLLED+:

  • +eventType+: The event type (EVENT_SCROLLED)
  • +delta+: Vector2 with scroll delta

'''''

=== Example: Input Handling

[source,js]

// In your update function, handle input events
function onInput(event) {
let eventType = event.eventType;

if (eventType == Input.EventType.EVENT_KEY) {
let keyCode = event.keyCode;
let pressed = event.pressed;

text
if (keyCode == Input.KeyCode.KEYCODE_ESCAPE && pressed) {
  // Handle escape key press
  puts("Escape pressed!");
}

if (keyCode == Input.KeyCode.KEYCODE_SPACE && pressed) {
  // Handle space bar
  playerJump();
}

} else if (eventType == Input.EventType.EVENT_POINTER) {
let position = event.position;
let buttons = event.buttons;

text
if (buttons & Input.PointerButton.BUTTON_LEFT) {
  // Handle left mouse button
  handleClick(position);
}

} else if (eventType == Input.EventType.EVENT_SCROLLED) {
let delta = event.delta;
// Handle scroll
zoom += delta.y;
}

}

'''''

== Audio

=== Overview

The Audio API provides comprehensive sound and music playback capabilities. It manages sound effects (with polyphony and spatial audio support) and background music. The API consists of two main components: the SoundManager for managing sound effects, and the MusicManager for managing background music.

'''''

=== SoundManager

The SoundManager namespace provides functions for creating, finding, and managing sound effects.

==== SoundManager.create()

Usage:

[source,js]

let sound = SoundManager.create(name, fileName, polyphony, loop, realVoices, fadeOutDuration);

  • Description: Creates a new sound effect with the specified parameters.
  • Parameters:
    ** +name+ (string): A unique identifier for the sound.
    ** +fileName+ (string): The path to the audio file.
    ** +polyphony+ (number): Maximum number of simultaneous instances of this sound (default: 1).
    ** +loop+ (number): Whether the sound should loop (1 for true, 0 for false, default: 1).
    ** +realVoices+ (number): Number of real audio voices to allocate (-1 for automatic, default: -1).
    ** +fadeOutDuration+ (number): Duration of fade-out in seconds when stopping (default: 0.0).
  • Return Value: A Sound object.
  • Example:

[source,js]

// Create a sound effect that can play 4 times simultaneously
let explosionSound = SoundManager.create("explosion", "sounds/explosion.ogg", 4, 0, -1, 0.5);

// Create a looping ambient sound let ambientSound = SoundManager.create("ambient", "sounds/ambient.ogg", 1, 1);

'''''

==== SoundManager.find()

Usage:

[source,js]

let sound = SoundManager.find(name);

  • Description: Finds a previously created sound by name.
  • Parameters:
    ** +name+ (string): The name of the sound to find.
  • Return Value: The Sound object, or null if not found.
  • Example:

[source,js]

let sound = SoundManager.find("explosion"); if (sound.valid()) { sound.play(1.0, 0.0, 1.0); }

'''''

==== SoundManager.remove()

Usage:

[source,js]

SoundManager.remove(name);

  • Description: Removes and destroys a sound by name.
  • Parameters:
    ** +name+ (string): The name of the sound to remove.
  • Return Value: None.

'''''

==== SoundManager.clear()

Usage:

[source,js]

SoundManager.clear();

  • Description: Removes all sounds from the manager.
  • Parameters: None.
  • Return Value: None.

'''''

=== Sound Objects

Sound objects are created through the SoundManager and provide methods for playback control.

==== sound.valid()

Usage:

[source,js]

let isValid = sound.valid();

  • Description: Checks if the sound object is valid and ready to use.
  • Parameters: None.
  • Return Value: 1 if valid, 0 otherwise.

'''''

==== sound.destroy()

Usage:

[source,js]

sound.destroy();

  • Description: Destroys the sound object and releases its resources.
  • Parameters: None.
  • Return Value: None.

'''''

==== sound.load()

Usage:

[source,js]

sound.load();

  • Description: Loads the sound data from disk.
  • Parameters: None.
  • Return Value: None.

'''''

==== sound.reload()

Usage:

[source,js]

sound.reload();

  • Description: Reloads the sound data from disk.
  • Parameters: None.
  • Return Value: None.

'''''

==== sound.getName()

Usage:

[source,js]

let name = sound.getName();

  • Description: Returns the name of the sound.
  • Parameters: None.
  • Return Value: The sound name as a string.

'''''

==== sound.getUID()

Usage:

[source,js]

let uid = sound.getUID();

  • Description: Returns the unique identifier of the sound.
  • Parameters: None.
  • Return Value: The UID as a number.

'''''

==== sound.getFileName()

Usage:

[source,js]

let fileName = sound.getFileName();

  • Description: Returns the file name of the sound.
  • Parameters: None.
  • Return Value: The file name as a string.

'''''

==== sound.getPolyphony()

Usage:

[source,js]

let polyphony = sound.getPolyphony();

  • Description: Returns the maximum polyphony of the sound.
  • Parameters: None.
  • Return Value: The polyphony value.

'''''

==== sound.getLoop()

Usage:

[source,js]

let loop = sound.getLoop();

  • Description: Returns whether the sound loops.
  • Parameters: None.
  • Return Value: 1 if looping, 0 otherwise.

'''''

==== sound.getRealVoices()

Usage:

[source,js]

let realVoices = sound.getRealVoices();

  • Description: Returns the number of real voices allocated for this sound.
  • Parameters: None.
  • Return Value: The number of real voices.

'''''

==== sound.getFadeOutDuration()

Usage:

[source,js]

let duration = sound.getFadeOutDuration();

  • Description: Returns the fade-out duration in seconds.
  • Parameters: None.
  • Return Value: The fade-out duration.

'''''

==== sound.play()

Usage:

[source,js]

let voiceID = sound.play(volume, panning, rate);

  • Description: Plays the sound with the specified parameters.
  • Parameters:
    ** +volume+ (number): Volume level (0.0 to 1.0 or higher).
    ** +panning+ (number): Stereo panning (-1.0 for left, 0.0 for center, 1.0 for right).
    ** +rate+ (number): Playback rate (1.0 is normal speed).
  • Return Value: A voice ID that can be used to control this specific playback instance.
  • Example:

[source,js]

let voiceID = sound.play(0.8, 0.0, 1.0); // Play at 80% volume, centered

'''''

==== sound.playSpatialization(volume, panning, rate, spatialization, position, velocity, local)

Usage:

[source,js]

let voiceID = sound.playSpatialization(volume, panning, rate, spatialization, position, velocity, local); // or when spatialization is enabled, you can use individual numbers: let voiceID = sound.playSpatialization(volume, panning, rate, spatialization, x, y, z, vx, vy, vz, local);

  • Description: Plays the sound with 3D spatial audio.
  • Parameters:
    ** +volume+ (number): Volume level.
    ** +panning+ (number): Stereo panning.
    ** +rate+ (number): Playback rate.
    ** +spatialization+ (number): Enable spatialization (1 for true, 0 for false).
    ** When spatialization is enabled:
    *** Option A:
    **** +position+ (Vector3): 3D position of the sound source.
    **** +velocity+ (Vector3): 3D velocity of the sound source (for Doppler effect).
    *** or Option B:
    **** +x, y, z+ (numbers): 3D position coordinates.
    **** +vx, vy, vz+ (numbers): 3D velocity components.
    ** +local+ (number): Use local coordinates (1) or world coordinates (0).
  • Return Value: A voice ID.
  • Example:

[source,js]

// Using Vector3:
let pos = Vector3.create(10, 0, 5);
let vel = Vector3.create(0, 0, 0);
let voiceID = sound.playSpatialization(1.0, 0.0, 1.0, 1, pos, vel, 0);

// or using individual numbers: let voiceID = sound.playSpatialization(1.0, 0.0, 1.0, 1, 10, 0, 5, 0, 0, 0, 0);

'''''

==== sound.stop()

Usage:

[source,js]

sound.stop(voiceID);

  • Description: Stops a specific playback instance.
  • Parameters:
    ** +voiceID+ (number): The voice ID returned by play() or playSpatialization().
  • Return Value: None.

'''''

==== sound.keyOff()

Usage:

[source,js]

sound.keyOff(voiceID);

  • Description: Triggers the release phase of a sound (for sounds with ADSR envelopes).
  • Parameters:
    ** +voiceID+ (number): The voice ID.
  • Return Value: None.

'''''

==== sound.setVolume()

Usage:

[source,js]

sound.setVolume(voiceID, volume);

  • Description: Changes the volume of a playing sound instance.
  • Parameters:
    ** +voiceID+ (number): The voice ID.
    ** +volume+ (number): The new volume level.
  • Return Value: The voice ID.

'''''

==== sound.setPanning()

Usage:

[source,js]

sound.setPanning(voiceID, panning);

  • Description: Changes the panning of a playing sound instance.
  • Parameters:
    ** +voiceID+ (number): The voice ID.
    ** +panning+ (number): The new panning value.
  • Return Value: The voice ID.

'''''

==== sound.setRate()

Usage:

[source,js]

sound.setRate(voiceID, rate);

  • Description: Changes the playback rate of a playing sound instance.
  • Parameters:
    ** +voiceID+ (number): The voice ID.
    ** +rate+ (number): The new playback rate.
  • Return Value: The voice ID.

'''''

==== sound.setPosition(voiceID, spatialization, position, velocity, local)

Usage:

[source,js]

sound.setPosition(voiceID, spatialization, position, velocity, local); // or when spatialization is enabled, you can use individual numbers: sound.setPosition(voiceID, spatialization, x, y, z, vx, vy, vz, local);

  • Description: Updates the 3D position and velocity of a playing sound instance.
  • Parameters:
    ** +voiceID+ (number): The voice ID.
    ** +spatialization+ (number): Enable spatialization.
    ** When spatialization is enabled:
    *** Option A:
    **** +position+ (Vector3): New 3D position.
    **** +velocity+ (Vector3): New 3D velocity.
    *** or Option B:
    **** +x, y, z+ (numbers): New 3D position coordinates.
    **** +vx, vy, vz+ (numbers): New 3D velocity components.
    ** +local+ (number): Use local coordinates.
  • Return Value: The voice ID.
  • Example:

[source,js]

// Using Vector3:
let newPos = Vector3.create(15, 5, 0);
let newVel = Vector3.create(2, 0, 0);
sound.setPosition(voiceID, 1, newPos, newVel, 0);

// or using individual numbers: sound.setPosition(voiceID, 1, 15, 5, 0, 2, 0, 0, 0);

'''''

==== sound.setEffectMix()

Usage:

[source,js]

sound.setEffectMix(voiceID, active);

  • Description: Enables or disables audio effects for a playing sound instance.
  • Parameters:
    ** +voiceID+ (number): The voice ID.
    ** +active+ (number): 1 to enable effects, 0 to disable.
  • Return Value: The voice ID.

'''''

==== sound.isPlaying()

Usage:

[source,js]

let playing = sound.isPlaying();

  • Description: Checks if any instance of this sound is currently playing.
  • Parameters: None.
  • Return Value: 1 if playing, 0 otherwise.

'''''

==== sound.isVoicePlaying()

Usage:

[source,js]

let playing = sound.isVoicePlaying(voiceID);

  • Description: Checks if a specific voice instance is currently playing.
  • Parameters:
    ** +voiceID+ (number): The voice ID to check.
  • Return Value: 1 if playing, 0 otherwise.

'''''

=== MusicManager

The MusicManager namespace provides functions for managing background music.

==== MusicManager.create()

Usage:

[source,js]

let music = MusicManager.create(name, fileName);

  • Description: Creates a new music track.
  • Parameters:
    ** +name+ (string): A unique identifier for the music.
    ** +fileName+ (string): The path to the audio file.
  • Return Value: A Music object.
  • Example:

[source,js]

let bgMusic = MusicManager.create("background", "music/background.ogg");

'''''

==== MusicManager.find()

Usage:

[source,js]

let music = MusicManager.find(name);

  • Description: Finds a previously created music track by name.
  • Parameters:
    ** +name+ (string): The name of the music to find.
  • Return Value: The Music object, or null if not found.

'''''

==== MusicManager.remove()

Usage:

[source,js]

MusicManager.remove(name);

  • Description: Removes and destroys a music track by name.
  • Parameters:
    ** +name+ (string): The name of the music to remove.
  • Return Value: None.

'''''

==== MusicManager.clear()

Usage:

[source,js]

MusicManager.clear();

  • Description: Removes all music tracks from the manager.
  • Parameters: None.
  • Return Value: None.

'''''

=== Music Objects

Music objects are created through the MusicManager and provide methods for playback control.

==== music.valid()

Usage:

[source,js]

let isValid = music.valid();

  • Description: Checks if the music object is valid and ready to use.
  • Parameters: None.
  • Return Value: 1 if valid, 0 otherwise.

'''''

==== music.destroy()

Usage:

[source,js]

music.destroy();

  • Description: Destroys the music object and releases its resources.
  • Parameters: None.
  • Return Value: None.

'''''

==== music.load()

Usage:

[source,js]

music.load();

  • Description: Loads the music data from disk.
  • Parameters: None.
  • Return Value: None.

'''''

==== music.reload()

Usage:

[source,js]

music.reload();

  • Description: Reloads the music data from disk.
  • Parameters: None.
  • Return Value: None.

'''''

==== music.getName()

Usage:

[source,js]

let name = music.getName();

  • Description: Returns the name of the music track.
  • Parameters: None.
  • Return Value: The music name as a string.

'''''

==== music.getUID()

Usage:

[source,js]

let uid = music.getUID();

  • Description: Returns the unique identifier of the music track.
  • Parameters: None.
  • Return Value: The UID as a number.

'''''

==== music.getFileName()

Usage:

[source,js]

let fileName = music.getFileName();

  • Description: Returns the file name of the music track.
  • Parameters: None.
  • Return Value: The file name as a string.

'''''

==== music.play()

Usage:

[source,js]

music.play(volume, panning, rate, loop);

  • Description: Plays the music track.
  • Parameters:
    ** +volume+ (number): Volume level (0.0 to 1.0 or higher).
    ** +panning+ (number): Stereo panning (-1.0 to 1.0).
    ** +rate+ (number): Playback rate (1.0 is normal speed).
    ** +loop+ (number): Whether to loop (1 for true, 0 for false).
  • Return Value: None.
  • Example:

[source,js]

music.play(0.7, 0.0, 1.0, 1); // Play at 70% volume, centered, looping

'''''

==== music.stop()

Usage:

[source,js]

music.stop();

  • Description: Stops the music playback.
  • Parameters: None.
  • Return Value: None.

'''''

==== music.setVolume()

Usage:

[source,js]

music.setVolume(volume);

  • Description: Changes the volume of the currently playing music.
  • Parameters:
    ** +volume+ (number): The new volume level.
  • Return Value: None.

'''''

==== music.setPanning()

Usage:

[source,js]

music.setPanning(panning);

  • Description: Changes the panning of the currently playing music.
  • Parameters:
    ** +panning+ (number): The new panning value.
  • Return Value: None.

'''''

==== music.setRate()

Usage:

[source,js]

music.setRate(rate);

  • Description: Changes the playback rate of the currently playing music.
  • Parameters:
    ** +rate+ (number): The new playback rate.
  • Return Value: None.

'''''

==== music.isPlaying()

Usage:

[source,js]

let playing = music.isPlaying();

  • Description: Checks if the music is currently playing.
  • Parameters: None.
  • Return Value: 1 if playing, 0 otherwise.

'''''

==== music.pause()

Usage:

[source,js]

music.pause();

  • Description: Pauses the currently playing music without resetting the playback position.
  • Parameters: None.
  • Return Value: The music object (for chaining), or null if invalid.

'''''

==== music.resume()

Usage:

[source,js]

music.resume();

  • Description: Resumes a paused music track from where it was paused.
  • Parameters: None.
  • Return Value: The music object (for chaining), or null if invalid.

'''''

==== music.isPaused()

Usage:

[source,js]

let paused = music.isPaused();

  • Description: Checks if the music is currently paused.
  • Parameters: None.
  • Return Value: 1 if paused, 0 otherwise.

'''''

=== Example: Audio Usage

[source,js]

// Create and play sound effects
let explosionSound = SoundManager.create("explosion", "sounds/explosion.wav", 4, 0);
let jumpSound = SoundManager.create("jump", "sounds/jump.wav", 2, 0);

// Play sound effects
explosionSound.play(1.0, 0.0, 1.0);

// Play with 3D spatialization
let enemyPos = Vector3.create(10, 0, 5);
let enemyVel = Vector3.create(0, 0, 0);
let voiceID = explosionSound.playSpatialization(0.8, 0.0, 1.0, 1, enemyPos, enemyVel, 0);

// Create and play background music
let bgMusic = MusicManager.create("bgm", "music/background.ogg");
bgMusic.play(0.6, 0.0, 1.0, 1); // Loop the music

// Later, fade out music by reducing volume
bgMusic.setVolume(0.3);

// Pause and resume music
bgMusic.pause();
// ... some time later ...
bgMusic.resume();

// Stop music
bgMusic.stop();

// Clean up SoundManager.clear(); MusicManager.clear();

'''''

== Scene3D

=== Overview

The Scene3D API exposes the PasVulkan 3D scene-graph to POCA scripts. It is
accessed through the +engine.scene3d+ object.

NOTE: +engine.scene3d+ is not created by the engine itself — it is
injected by the game application at context initialisation time by calling
+InitializePOCAScene3DContext(context, scene3DInstance, engineHash)+
(implemented in +PasVulkan.POCA.Scene3D.pas+). In the planetgame1 (Seeds)
project this call is made in +UnitGamePOCA.pas+. A game that does not call
+InitializePOCAScene3DContext+ will not have an +engine.scene3d+ object at
all.

All objects returned by the Scene3D API are ghost objects. A ghost holds
a pointer to the underlying engine resource but does not hold an
independent reference-count on it. The resource is owned by the scene.

When the POCA garbage collector finalises a ghost, only the internal pointer
is nulled — the engine resource itself is not released. Call .destroy()
on a ghost to explicitly release (DecRef) the resource immediately and null
the pointer. Any resource not explicitly destroyed is cleaned up by
+TpvScene3D.Destroy+ at scene / game shutdown.

Do not call +.destroy()+ on ghosts that you still intend to use. Holding
a ghost variable alive keeps the pointer valid, but the resource stays alive
regardless (it is owned by the scene).

'''''

=== engine.scene3d — Scene object

+engine.scene3d+ is a ghost object injected by the game application (see
Overview above). It is the entry point for all Scene3D operations. All
factory methods on it return ghost objects that the caller is responsible for
keeping alive (or explicitly destroying).

'''''

==== engine.scene3d.createImage(width, height, pixels)

Usage:

[source,js]

let img = engine.scene3d.createImage(width, height, pixels);

  • Description: Creates a +Scene3DImage+ ghost from an array of packed RGBA8
    pixel values. Pixels are encoded as +0xRRGGBBAA+ 32-bit integers stored in
    the +pixels+ array in row-major order. The underlying image data is stored
    as QOI internally.
  • Parameters:
    ** +width+ (number): Image width in pixels.
    ** +height+ (number): Image height in pixels.
    ** +pixels+ (array): Array of +width * height+ 32-bit RGBA values.
  • Return Value: A +Scene3DImage+ ghost, or +null+ on failure.
  • Notes: The image is not yet uploaded to the GPU after creation. Call
    +img.upload()+ once per render frame until +img.isUploaded()+ returns
    +true+, or simply upload before first use.
  • Example:

[source,js]

// 2×2 white image let pixels = [0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF]; let img = engine.scene3d.createImage(2, 2, pixels);

'''''

==== engine.scene3d.loadImage(path)

Usage:

[source,js]

let img = engine.scene3d.loadImage("textures/rock.png");

  • Description: Loads an image from the application asset bundle by virtual
    path. Supported formats are those understood by the engine (PNG, JPEG, QOI,
    KTX2, …). The image is fully loaded and uploaded synchronously during this
    call.
  • Parameters:
    ** +path+ (string): Asset-relative virtual path.
  • Return Value: A +Scene3DImage+ ghost, or +null+ if the asset does not
    exist or loading fails.

'''''

==== engine.scene3d.getImageByName(name)

Usage:

[source,js]

let img = engine.scene3d.getImageByName("my_image");

  • Description: Looks up an already-loaded image by its internal name.
  • Parameters:
    ** +name+ (string): The image name (set during creation or loading).
  • Return Value: A +Scene3DImage+ ghost (new owned reference), or +null+ if
    no image with that name exists.

'''''

==== engine.scene3d.createSampler([type])

Usage:

[source,js]

let s = engine.scene3d.createSampler(); // default repeat let s = engine.scene3d.createSampler('nonrepeat'); let s = engine.scene3d.createSampler('mipmap'); let s = engine.scene3d.createSampler('mipmapnonrepeat');

  • Description: Creates a new +Scene3DSampler+ ghost with the given filter
    and wrap preset.
  • Parameters:
    ** +type+ (string, optional): One of +'default'+, +'nonrepeat'+,
    +'mipmap'+, +'mipmapnonrepeat'+. Defaults to +'default'+ (bilinear,
    repeat).
  • Return Value: A +Scene3DSampler+ ghost.

'''''

==== engine.scene3d.defaultSampler()

Usage:

[source,js]

let s = engine.scene3d.defaultSampler();

  • Description: Returns the scene's built-in default sampler (bilinear, repeat
    wrapping) as an owned ghost reference.
  • Return Value: A +Scene3DSampler+ ghost, or +null+ if no default sampler
    exists.

'''''

==== engine.scene3d.defaultNonRepeatSampler()

Usage:

[source,js]

let s = engine.scene3d.defaultNonRepeatSampler();

  • Description: Returns the scene's built-in default non-repeat sampler
    (bilinear, clamp-to-edge) as an owned ghost reference.
  • Return Value: A +Scene3DSampler+ ghost, or +null+ if not available.

'''''

==== engine.scene3d.createTexture(image [, sampler])

Usage:

[source,js]

let tex = engine.scene3d.createTexture(img); let tex = engine.scene3d.createTexture(img, sampler);

  • Description: Creates a +Scene3DTexture+ ghost by combining a
    +Scene3DImage+ and an optional +Scene3DSampler+. When no sampler is
    supplied the scene's default repeat sampler is used automatically.
  • Parameters:
    ** +image+ (+Scene3DImage+): The image ghost to attach.
    ** +sampler+ (+Scene3DSampler+, optional): A sampler ghost. Defaults to
    the scene default.
  • Return Value: A +Scene3DTexture+ ghost, or +null+ on failure.

'''''

==== engine.scene3d.createTextureFromImage(width, height, pixels)

Usage:

[source,js]

let tex = engine.scene3d.createTextureFromImage(width, height, pixels);

  • Description: Convenience shortcut that creates an image from a pixel array
    and immediately wraps it in a texture using the default sampler. No separate
    image ghost is returned; the image is owned by the texture.
  • Parameters:
    ** +width+ (number): Image width in pixels.
    ** +height+ (number): Image height in pixels.
    ** +pixels+ (array): Array of +width * height+ packed RGBA8 values
    (+0xRRGGBBAA+).
  • Return Value: A +Scene3DTexture+ ghost, or +null+ on failure.

'''''

==== engine.scene3d.createMaterial([opts])

Usage:

[source,js]

let mat = engine.scene3d.createMaterial();
let mat = engine.scene3d.createMaterial({
name: 'myMaterial',
shadingModel: 'pbr', // 'pbr' | 'specularGlossiness' | 'unlit'
alphaMode: 'opaque', // 'opaque' | 'mask' | 'blend'
alphaCutoff: 0.5,
doubleSided: false,
castShadows: true,
receiveShadows: true,
noWetness: false,
baseColor: [1, 1, 1, 1], // [r, g, b, a]
metallic: 0.0,
roughness: 0.5,
emissive: [0, 0, 0], // [r, g, b]
baseColorTexture: tex,
normalTexture: normalTex,
metallicRoughnessTexture: mrTex,
occlusionTexture: aoTex,
emissiveTexture: emTex,
hologram: {
active: false,
direction: [0, 1, 0],
flickerSpeed: 1.0,
flickerMin: 0.5,
flickerMax: 1.0,
mainColor: [0, 0.8, 1, 1],
rimColor: [0, 0.5, 1, 1],
rimPower: 2.0,
rimThreshold: 0.2,
scanTiling: 1.0,
scanSpeed: 0.5,
scanMin: 0.0,
scanMax: 1.0,
glowTiling: 1.0,
glowSpeed: 0.3,
glowMin: 0.0,
glowMax: 1.0,
},

});

  • Description: Creates a new +Scene3DMaterial+ ghost. All fields in the
    optional +opts+ hash are applied atomically before +FillShaderData+ is
    called, so no intermediate GPU updates are generated.
  • Parameters:
    ** +opts+ (hash, optional): Initial property values. All keys are optional
    and use the defaults of the engine material if omitted.

[cols="1,1,3", options="header"]
|===
|Key |Type |Description

|+name+ |string |Internal material name (default: +'poca_material'+).
|+shadingModel+ |string |+'pbr'+ (default), +'specularGlossiness'+, or +'unlit'+.
|+alphaMode+ |string |+'opaque'+ (default), +'mask'+, or +'blend'+.
|+alphaCutoff+ |number |Alpha cutoff threshold for +'mask'+ mode (default 0.5).
|+doubleSided+ |bool |Disable back-face culling (default +false+).
|+castShadows+ |bool |Whether the material casts shadows (default +true+).
|+receiveShadows+ |bool |Whether the material receives shadows (default +true+).
|+noWetness+ |bool |Suppress wetness/rain interaction (default +false+).
|+baseColor+ |array[4] |Base colour factor +[r, g, b, a]+ (default +[1,1,1,1]+).
|+metallic+ |number |Metallic factor 0–1 (default 0).
|+roughness+ |number |Roughness factor 0–1 (default 1).
|+emissive+ |array[3] |Emissive colour factor +[r, g, b]+ (default +[0,0,0]+).
|+baseColorTexture+ |Scene3DTexture |Base colour / albedo texture.
|+normalTexture+ |Scene3DTexture |Tangent-space normal map.
|+metallicRoughnessTexture+ |Scene3DTexture |Metallic-roughness texture (B=metallic, G=roughness).
|+occlusionTexture+ |Scene3DTexture |Ambient-occlusion texture (R channel).
|+emissiveTexture+ |Scene3DTexture |Emissive colour texture.
|+hologram+ |hash |Hologram sub-object (see hologram table below).
|===

[cols="1,1,3", options="header"]
|===
|Hologram key |Type |Description

|+active+ |bool |Enable hologram rendering (default +false+).
|+direction+ |array[3] |Scan/glow direction vector +[x, y, z]+.
|+flickerSpeed+ |number |Flicker animation speed.
|+flickerMin+ |number |Minimum flicker intensity.
|+flickerMax+ |number |Maximum flicker intensity.
|+mainColor+ |array[4] |Main hologram colour +[r, g, b, a]+.
|+rimColor+ |array[4] |Rim light colour +[r, g, b, a]+.
|+rimPower+ |number |Fresnel rim exponent.
|+rimThreshold+ |number |Fresnel rim threshold.
|+scanTiling+ |number |Scan-line tiling.
|+scanSpeed+ |number |Scan-line scroll speed.
|+scanMin+ |number |Scan-line intensity minimum.
|+scanMax+ |number |Scan-line intensity maximum.
|+glowTiling+ |number |Glow tiling.
|+glowSpeed+ |number |Glow scroll speed.
|+glowMin+ |number |Glow intensity minimum.
|+glowMax+ |number |Glow intensity maximum.
|===

  • Return Value: A +Scene3DMaterial+ ghost.

'''''

=== Scene3DImage

A ghost object wrapping a +TpvScene3D.TImage+. The ghost holds a pointer
to the image; the image itself is owned by the scene. GC-finalised ghosts
only null their pointer. Call +img.destroy()+ to release (DecRef) explicitly.

'''''

==== img.upload()

Usage:

[source,js]

img.upload();

  • Description: Triggers a GPU upload for the image (synchronous staging
    enqueue). Due to the render-frame pipeline, the upload may not be visible
    until the next rendered frame. Call repeatedly until +img.isUploaded()+
    returns +true+ if synchronous availability is required.
  • Return Value: The image ghost (for method chaining).

'''''

==== img.isUploaded()

Usage:

[source,js]

if (img.isUploaded()) { ... }

  • Description: Returns +true+ (+1+) if the GPU upload has completed, or
    +false+ (+0+) if it is still pending.
  • Return Value: +1+ or +0+.

'''''

==== img.destroy()

Usage:

[source,js]

img.destroy();

  • Description: Immediately releases the ghost's reference on the image. The
    ghost's internal pointer is nulled; any further method calls on the same
    variable are silently ignored.
  • Return Value: +null+.

'''''

=== Scene3DSampler

A ghost object wrapping a +TpvScene3D.TSampler+. The ghost holds a
pointer; the sampler is owned by the scene. GC-finalised ghosts only null
their pointer. Call +sampler.destroy()+ to release explicitly.

'''''

==== sampler.destroy()

Usage:

[source,js]

sampler.destroy();

  • Description: Immediately releases the ghost's reference on the sampler.
  • Return Value: +null+.

'''''

=== Scene3DTexture

A ghost object wrapping a +TpvScene3D.TTexture+. The ghost holds a
pointer; the texture is owned by the scene. GC-finalised ghosts only null
their pointer. Call +tex.destroy()+ to release explicitly.

'''''

==== tex.destroy()

Usage:

[source,js]

tex.destroy();

  • Description: Immediately releases the ghost's reference on the texture.
  • Return Value: +null+.

'''''

=== Scene3DMaterial

A ghost object wrapping a +TpvScene3D.TMaterial+. After any setter call the
material automatically calls +FillShaderData+ and notifies the scene of a new
material data generation so GPU buffers are updated. Use +fillShaderData()+
explicitly to batch multiple setters and trigger only one GPU update.

'''''

==== mat.setShadingModel(model)

Usage:

[source,js]

mat.setShadingModel('pbr'); // PBR metallic-roughness (default) mat.setShadingModel('specularGlossiness'); // PBR specular-glossiness mat.setShadingModel('unlit'); // Unlit / no lighting

  • Parameters:
    ** +model+ (string): +'pbr'+, +'specularGlossiness'+, or +'unlit'+.
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setAlphaMode(mode)

Usage:

[source,js]

mat.setAlphaMode('opaque'); // (default) mat.setAlphaMode('mask'); mat.setAlphaMode('blend');

  • Parameters:
    ** +mode+ (string): +'opaque'+, +'mask'+, or +'blend'+.
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setAlphaCutoff(value)

Usage:

[source,js]

mat.setAlphaCutoff(0.5);

  • Description: Sets the alpha cutoff threshold used when +alphaMode+ is
    +'mask'+.
  • Parameters:
    ** +value+ (number): Alpha cutoff 0–1.
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setDoubleSided(value)

Usage:

[source,js]

mat.setDoubleSided(true);

  • Description: Enables or disables back-face culling.
  • Parameters:
    ** +value+ (bool/number): +true+/+1+ = double-sided (no culling).
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setCastShadows(value)

Usage:

[source,js]

mat.setCastShadows(false);

  • Parameters:
    ** +value+ (bool/number): +true+/+1+ = casts shadows (default).
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setReceiveShadows(value)

Usage:

[source,js]

mat.setReceiveShadows(false);

  • Parameters:
    ** +value+ (bool/number): +true+/+1+ = receives shadows (default).
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setNoWetness(value)

Usage:

[source,js]

mat.setNoWetness(true);

  • Description: When +true+ the material is excluded from rain/wetness
    effects.
  • Parameters:
    ** +value+ (bool/number): +true+/+1+ = suppress wetness.
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setBaseColorFactor(r, g, b, a)

Usage:

[source,js]

mat.setBaseColorFactor(1.0, 0.5, 0.0, 1.0); // scalar form mat.setBaseColorFactor([1.0, 0.5, 0.0, 1.0]); // array form mat.setBaseColorFactor({r: 1.0, g: 0.5, b: 0.0, a: 1.0}); // hash form mat.setBaseColorFactor(Vector4.create(1.0, 0.5, 0.0, 1.0)); // ghost form

  • Description: Sets the base colour (albedo) factor.
  • Parameters (Option A):
    ** +r+, +g+, +b+, +a+ (number): RGBA components, each 0–1.
  • Parameters (Option B):
    ** +color+ (Vector4, array[4], or hash {r,g,b,a}): RGBA colour. See <>.
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setMetallicFactor(value)

Usage:

[source,js]

mat.setMetallicFactor(1.0);

  • Parameters:
    ** +value+ (number): Metallic factor 0–1.
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setRoughnessFactor(value)

Usage:

[source,js]

mat.setRoughnessFactor(0.3);

  • Parameters:
    ** +value+ (number): Roughness factor 0–1.
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setEmissiveFactor(r, g, b)

Usage:

[source,js]

mat.setEmissiveFactor(1.0, 0.5, 0.0); // scalar form mat.setEmissiveFactor([1.0, 0.5, 0.0]); // array form mat.setEmissiveFactor({r: 1.0, g: 0.5, b: 0.0}); // hash form mat.setEmissiveFactor(Vector3.create(1.0, 0.5, 0.0)); // ghost form

  • Description: Sets the emissive colour factor. The emissive strength
    component (w) is not modified.
  • Parameters (Option A):
    ** +r+, +g+, +b+ (number): RGB components, each 0–1 (or higher for HDR).
  • Parameters (Option B):
    ** +color+ (Vector3, array[3], or hash {r,g,b}): RGB colour. See <>.
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setBaseColorTexture(tex [, texCoord])

Usage:

[source,js]

mat.setBaseColorTexture(tex); mat.setBaseColorTexture(tex, 1); // use UV set 1

  • Description: Assigns the base colour / albedo texture.
  • Parameters:
    ** +tex+ (+Scene3DTexture+): The texture ghost.
    ** +texCoord+ (number, optional): UV channel index (default +0+).
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setNormalTexture(tex [, scale [, texCoord]])

Usage:

[source,js]

mat.setNormalTexture(normalTex); mat.setNormalTexture(normalTex, 2.0); // double normal strength mat.setNormalTexture(normalTex, 1.0, 1); // UV set 1

  • Description: Assigns the tangent-space normal map.
  • Parameters:
    ** +tex+ (+Scene3DTexture+): The normal map texture.
    ** +scale+ (number, optional): Normal map scale/strength (default +1.0+).
    ** +texCoord+ (number, optional): UV channel index (default +0+).
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setMetallicRoughnessTexture(tex [, texCoord])

Usage:

[source,js]

mat.setMetallicRoughnessTexture(mrTex);

  • Description: Assigns the metallic-roughness texture (B channel = metallic,
    G channel = roughness).
  • Parameters:
    ** +tex+ (+Scene3DTexture+): The texture ghost.
    ** +texCoord+ (number, optional): UV channel index (default +0+).
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setOcclusionTexture(tex [, strength [, texCoord]])

Usage:

[source,js]

mat.setOcclusionTexture(aoTex); mat.setOcclusionTexture(aoTex, 0.8); // partial occlusion strength mat.setOcclusionTexture(aoTex, 1.0, 1); // UV set 1

  • Description: Assigns the ambient-occlusion texture (R channel).
  • Parameters:
    ** +tex+ (+Scene3DTexture+): The AO texture ghost.
    ** +strength+ (number, optional): Occlusion strength 0–1 (default +1.0+).
    ** +texCoord+ (number, optional): UV channel index (default +0+).
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setEmissiveTexture(tex [, texCoord])

Usage:

[source,js]

mat.setEmissiveTexture(emTex);

  • Description: Assigns the emissive texture.
  • Parameters:
    ** +tex+ (+Scene3DTexture+): The emissive texture ghost.
    ** +texCoord+ (number, optional): UV channel index (default +0+).
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.setHologram(opts)

Usage:

[source,js]

mat.setHologram({ active: true, direction: [0, 1, 0], flickerSpeed: 2.0, flickerMin: 0.6, flickerMax: 1.0, mainColor: [0, 0.8, 1, 0.9], rimColor: [0, 0.4, 1, 1], rimPower: 3.0, rimThreshold: 0.15, scanTiling: 2.0, scanSpeed: 0.8, scanMin: 0.0, scanMax: 0.6, glowTiling: 1.0, glowSpeed: 0.3, glowMin: 0.1, glowMax: 0.9, });

  • Description: Applies hologram rendering parameters. Only the keys present
    in +opts+ are modified; omitted keys retain their current values.
  • Parameters:
    ** +opts+ (hash): Hologram property hash. See the hologram key table in
    +createMaterial+ for the full list of accepted keys and their types.
  • Return Value: The material ghost (for method chaining).

'''''

==== mat.fillShaderData()

Usage:

[source,js]

mat.fillShaderData();

  • Description: Explicitly calls +FillShaderData+ and notifies the scene of a
    new material data generation, flushing GPU buffers. Use this after a batch of
    setter calls to reduce the number of GPU-buffer updates to one.

NOTE: Every individual setter already calls +fillShaderData+ internally, so
calling it again after a single setter is redundant. It is useful only when
you want to set many properties at once without intermediate GPU flushes
(though the current implementation still flushes after each setter).

  • Return Value: The material ghost (for method chaining).

'''''

==== mat.destroy()

Usage:

[source,js]

mat.destroy();

  • Description: Immediately releases the ghost's reference on the material.
    The ghost's internal pointer is nulled; any further method calls on it are
    silently ignored.
  • Return Value: +null+.

'''''

=== Scene3D — Full example

[source,js]

// Load a texture from an asset file
let img = engine.scene3d.loadImage("textures/metal_basecolor.png");

// Create a texture using the default sampler
let tex = engine.scene3d.createTexture(img);

// Build a PBR metallic material
let mat = engine.scene3d.createMaterial({
name: 'metalPlate',
metallic: 0.9,
roughness: 0.2,
baseColorTexture: tex,
});

// … attach mat to a mesh primitive later …

// Explicit cleanup when no longer needed mat.destroy(); tex.destroy(); img.destroy();

'''''

=== Scene3DGroup

A Scene3DGroup represents a procedurally-created 3D object group (equivalent to a glTF scene file).
Obtained from engine.scene3d.createGroup(name).

Build order: create meshes → create primitives → add vertices/indices → finish primitives → finish meshes → create nodes → set node properties → create scenes → add nodes → add materials → call group.finish() → call group.createInstance().

[cols="1,3"]
|===
|Method |Description

|group.createMesh([name]) |Create a new Scene3DMesh within this group.
|group.createNode([name]) |Create a new Scene3DNode within this group.
|group.createScene([name]) |Create a new Scene3DGroupScene within this group.
|group.addMaterial(mat) |Register a Scene3DMaterial with this group; returns integer material index.
|group.finish() |Finalise and upload the group to the GPU. Must be called once before createInstance().
|group.createInstance() |Instantiate the group in the scene; returns a Scene3DInstance.
|group.getAnimationID(name) |Look up an animation by name; returns integer index or -1 if not found.
|group.destroy() |Invalidate the POCA ghost (the group itself is owned by the scene).
|===

.Example [source,javascript]

let g = engine.scene3d.createGroup('myObject');
let mat = engine.scene3d.createMaterial({ name: 'red', baseColor: [1,0,0,1] });
let matIdx = g.addMaterial(mat);

let mesh = g.createMesh('body');
let prim = mesh.createPrimitive('triangles');
prim.setMaterial(mat);
// … add vertices / indices …
prim.finish();
mesh.finish();

let node = g.createNode('root');
node.setMesh(mesh);
node.setTranslation(0.0, 0.0, 0.0);

let sc = g.createScene('default');
sc.addNode(node);

g.finish(); let inst = g.createInstance();

'''''

=== Scene3DMesh

A Scene3DMesh is a named mesh within a Scene3DGroup. Obtained from group.createMesh(name).

[cols="1,3"]
|===
|Method |Description

|mesh.createPrimitive(['triangles'|'lines'|'points']) |Create a new Scene3DPrimitive. Defaults to 'triangles'.
|mesh.calculateTangentSpace() |Auto-compute tangents from positions, normals and UVs (call after adding all primitives).
|mesh.finish() |Finalise the mesh (called implicitly by group.finish()).
|mesh.destroy() |Invalidate the POCA ghost (mesh lifetime is managed by the group).
|===

'''''

=== Scene3DPrimitive

A Scene3DPrimitive is a draw call within a Scene3DMesh. Obtained from mesh.createPrimitive(topology).

[cols="1,3"]
|===
|Method |Description

|prim.setMaterial(mat) |Attach a Scene3DMaterial to this primitive.
|prim.addVertex(x,y,z [,nx,ny,nz] [,tx,ty,tz] [,u0,v0] [,u1,v1] [,r,g,b,a]) a|Append a vertex (positional form). Groups are optional but must be supplied in order. Valid total arg counts: 3, 6, 9, 11, 13, or 17. Normal and tangent are oct-encoded internally. Tangent (0,0,0) enables automatic tangent-space via calculateTangentSpace(). Color defaults to (1,1,1,1). Returns the integer vertex index.
|prim.addVertex({position, normal, tangent, texcoord0, texcoord1, color}) a|Append a vertex (hash/object form). Pass a hash with any of the following keys — all optional: +
position — Vector3 ghost, {x,y,z} / {r,g,b} hash, or [x,y,z] array +
normal — Vector3 ghost, {x,y,z} / {r,g,b} hash, or [x,y,z] array +
tangent — Vector3 ghost, {x,y,z} / {r,g,b} hash, or [x,y,z] array +
texcoord0 — Vector2 ghost, {x/s/u, y/t/v} hash, or [x,y] array +
texcoord1 — Vector2 ghost, {x/s/u, y/t/v} hash, or [x,y] array +
color — Vector4 ghost, {x/r, y/g, z/b, w/a} hash, or [r,g,b,a] array +
Returns the integer vertex index.
|prim.addIndex(i) |Append an index into the vertex buffer.
|prim.finish() |Finalise this primitive.
|prim.destroy() |Invalidate the POCA ghost (primitive lifetime is managed by the mesh).
|===

.Building a triangle (positional form) [source,javascript]

let prim = mesh.createPrimitive('triangles'); prim.setMaterial(mat); prim.addVertex( 0.0, 1.0, 0.0, 0,0,1, 0,0,0, 0.5, 0.0 ); prim.addVertex( -1.0, -1.0, 0.0, 0,0,1, 0,0,0, 0.0, 1.0 ); prim.addVertex( 1.0, -1.0, 0.0, 0,0,1, 0,0,0, 1.0, 1.0 ); prim.addIndex(0); prim.addIndex(1); prim.addIndex(2); prim.finish();

.Building a triangle (hash form) [source,javascript]

let prim = mesh.createPrimitive('triangles'); prim.setMaterial(mat); prim.addVertex({position:[ 0.0, 1.0, 0.0], normal:[0,0,1], texcoord0:[0.5, 0.0]}); prim.addVertex({position:[ -1.0, -1.0, 0.0], normal:[0,0,1], texcoord0:[0.0, 1.0]}); prim.addVertex({position:[ 1.0, -1.0, 0.0], normal:[0,0,1], texcoord0:[1.0, 1.0]}); prim.addIndex(0); prim.addIndex(1); prim.addIndex(2); prim.finish();

'''''

=== Scene3DNode

A Scene3DNode represents a transform node in the scene graph of a Scene3DGroup.
Obtained from group.createNode(name).

[cols="1,3"]
|===
|Method |Description

|node.setMesh(mesh) |Attach a Scene3DMesh to this node.
|node.addChild(childNode) |Add a child Scene3DNode.
|node.setTranslation(x, y, z) |Set the node's local translation. Also accepts a Vector3 ghost, array [x,y,z], or hash {x,y,z}.
|node.setRotation(qx, qy, qz, qw) |Set the node's local rotation as a quaternion. Also accepts a Quaternion ghost, array [x,y,z,w], or hash {x,y,z,w}.
|node.setScale(sx, sy, sz) |Set the node's local scale. Also accepts a Vector3 ghost, array [x,y,z], or hash {x,y,z}.
|node.setMatrix(m00,…,m15) |Override the full 4×4 transform (16 floats, row-major). Also accepts a Matrix4x4 ghost, array [16], or hash.
|node.setVisible(bool) |Show/hide this node.
|node.setCastShadows(bool) |Enable/disable shadow casting for this node.
|node.finish() |Finalise the node before calling group.finish().
|node.destroy() |Invalidate the POCA ghost (node lifetime is managed by the group).
|===

'''''

=== Scene3DGroupScene

A Scene3DGroupScene is the root scene list within a Scene3DGroup that declares which nodes are top-level.
Obtained from group.createScene(name).

[cols="1,3"]
|===
|Method |Description

|scene.addNode(node) |Add a root Scene3DNode to this scene.
|scene.destroy() |Invalidate the POCA ghost (scene lifetime is managed by the group).
|===

NOTE: scene.finish() is implicit; called internally by group.finish().

'''''

=== Scene3DLight

A Scene3DLight is a standalone dynamic light (point, spot, or directional) placed in the scene.
Created via scene3d.createPointLight(...), scene3d.createSpotLight(...), or scene3d.createDirectionalLight(...).

The light is owned by POCA — call light.destroy() to free it; the GC will also call Free automatically.
Call light.update() after changing any property to push the changes to the GPU.

NOTE: engine.scene3d is created and managed by the game layer, not the engine directly.

[cols="1,3"]
|===
|Method |Description

|scene3d.createPointLight(x,y,z, r,g,b, intensity, range) |Create a point light at position (x,y,z) with colour (r,g,b), given intensity and attenuation range. Returns a Scene3DLight.
|scene3d.createSpotLight(x,y,z, dx,dy,dz, r,g,b, intensity, range, innerDeg, outerDeg) |Create a spot light at (x,y,z) pointing in direction (dx,dy,dz). innerDeg / outerDeg are the inner/outer cone half-angles in degrees. Returns a Scene3DLight.
|scene3d.createDirectionalLight(dx,dy,dz, r,g,b, intensity) |Create a directional light with direction (dx,dy,dz). Returns a Scene3DLight.
|light.setType(t) |Change the light type: 1 = Directional, 2 = Point, 3 = Spot. Returns light.
|light.setPosition(x,y,z) |Set the translation part of the light's matrix, preserving orientation. Returns light.
|light.setDirection(dx,dy,dz) |Recompute the light matrix orientation toward (dx,dy,dz), preserving the current position. Returns light.
|light.setMatrix(m00,m01,…,m15) |Set the full 4×4 double-precision light matrix (16 row-major arguments). Returns light.
|light.setColor(r,g,b) |Set the light colour. Returns light.
|light.setIntensity(v) |Set the light intensity. Returns light.
|light.setRange(v) |Set the attenuation range (point/spot lights). Returns light.
|light.setConeAngles(innerDeg, outerDeg) |Set inner and outer cone half-angles in degrees (spot lights). Returns light.
|light.setCastShadows(bool) |Enable or disable shadow casting. Returns light.
|light.setVisible(bool) |Show or hide the light. Returns light.
|light.update([inFlightFrameIndex]) |Push all property changes to the GPU. Pass the current in-flight frame index, or omit for auto (-1). Returns light.
|light.destroy() |Free the light and invalidate the POCA ghost.
|===

.Example [source,javascript]

let pt = engine.scene3d.createPointLight(0.0, 2.0, 0.0, 1.0, 0.9, 0.7, 5.0, 10.0);
pt.setCastShadows(true);
pt.update();

let spot = engine.scene3d.createSpotLight(
0.0, 5.0, 0.0, // position
0.0, -1.0, 0.0, // direction (down)
1.0, 1.0, 1.0, // colour
8.0, 20.0, // intensity, range
15.0, 30.0 // inner/outer cone degrees
);
spot.update();

let sun = engine.scene3d.createDirectionalLight(-0.5, -1.0, -0.5, 1.0, 0.95, 0.8, 3.0); sun.update();

'''''

=== Scene3DDecal

A Scene3DDecal is a dynamic decal projected onto scene geometry.
Created via scene3d.spawnDecal(opts) (see opts table in the Reference section).

The decal is owned by TpvScene3D; the POCA ghost stores a back-pointer only.
Call decal.destroy() to hide the decal early and release the ghost data.
Never call Free on a decal directly.

NOTE: engine.scene3d is created and managed by the game layer, not the engine directly.

[cols="1,3"]
|===
|Method / Factory |Description

|scene3d.spawnDecal(opts) |Spawn a decal; returns a Scene3DDecal ghost. Required opts: position:[x,y,z], size:[w,h]. Optional: orientation:[qx,qy,qz,qw], rotation (rad), texture indices (albedoTexture, normalTexture, ormTexture, specularTexture, emissiveTexture), blendMode, pbrBlendFactor, opacity, angleFade, edgeFade, lifetime, fadeOutTime, passMesh, passPlanet, passGrass.
|decal.setVisible(bool) |Show or hide the decal. Returns decal.
|decal.setOpacity(f) |Set opacity (0–1). Returns decal.
|decal.setPosition(x,y,z) |Set the world-space position (TpvVector3D). Returns decal.
|decal.setOrientation(qx,qy,qz,qw) |Set the orientation quaternion. Returns decal.
|decal.setRotation(f) |Set extra rotation about the decal normal, in radians. Returns decal.
|decal.setSize(w,h) |Set decal width and height; depth defaults to 0.5. Returns decal.
|decal.setBlendMode(mode) |Set blend mode: 'alpha', 'multiply', 'overlay', 'additive', 'pbr', 'normalmap'. Returns decal.
|decal.destroy() |Mark decal invisible (if still valid), release ghost data.
|===

.Example [source,javascript]

let d = engine.scene3d.spawnDecal({ position: [10.0, 0.05, 5.0], size: [1.0, 1.0], albedoTexture: myAlbedoIdx, blendMode: 'alpha', opacity: 0.8, lifetime: 5.0, fadeOutTime: 1.0 }); d.setVisible(true);

'''''

=== Scene3DBakedMesh

A Scene3DBakedMesh is a CPU-side triangle soup snapshot of a Scene3DInstance's geometry.
Obtained from instance.getBakedMesh().

The caller owns the Scene3DBakedMesh and must call destroy() when finished
to free the underlying memory.

.Scene3DBakedMesh creation
[cols="1,3"]
|===
|POCA call |Description

|instance.getBakedMesh() |Bake the instance's current geometry into a triangle mesh; returns a Scene3DBakedMesh ghost.
|===

.Scene3DBakedMesh methods
[cols="1,3"]
|===
|Method |Description

|bm.raycast(origin, dir) |Cast a ray against the baked mesh. origin and dir are [x,y,z] arrays. Returns {distance, position:{x,y,z}, u, v} for the closest hit, or null if no hit.
|bm.destroy() |Free the baked mesh immediately (must be called to avoid memory leaks).
|===

.Scene3DBakedMesh example [source,js]

let bm = instance.getBakedMesh(); let hit = bm.raycast([0,10,0], [0,-1,0]); if (hit !== null) { console.log("hit at distance " + hit.distance); } bm.destroy();

'''

.Scene3DScene raycast
[cols="1,3"]
|===
|Method |Description

|scene3d.raycast(origin, dir, instances) |Cast a ray against the baked geometry of every Scene3DInstance in the instances array. Returns {instance, distance, position:{x,y,z}, u, v} for the closest overall hit, or null if no hit.
|===

'''''

=== Scene3DParticle — scene3d.addParticle

Spawns a fire-and-forget particle. No ghost is returned; the engine recycles slots automatically.

.addParticle — hash-opts form
[cols="1,1,3"]
|===
|Opt |Default |Description

|position |required |[x,y,z] world position
|velocity |[0,0,0] |Initial velocity vector
|gravity |[0,0,0] |Gravity acceleration vector
|rotationStart |0.0 |Start rotation in radians
|rotationEnd |0.0 |End rotation in radians
|sizeStart |[1,1] |Particle size at birth [w,h]
|sizeEnd |[0,0] |Particle size at death [w,h]
|colorStart |[1,1,1,1] |RGBA colour at birth
|colorEnd |[1,1,1,0] |RGBA colour at death
|lifetime |1.0 |Particle lifetime in seconds
|textureID |0 |Texture atlas index
|additiveBlending |false |Use additive blending if true
|===

Returns the particle slot index as an integer.

.addParticle — positional form [source,js]

// scene3d.addParticle(position, velocity, gravity, rotStart, rotEnd,
// sizeStart, sizeEnd, colorStart, colorEnd,
// lifetime, textureID, additiveBlending)
scene3d.addParticle([x,y,z], [0,0,0], [0,-9.8,0], 0, 0,
[0.5,0.5], [0,0], [1,1,1,1], [1,1,1,0],
2.0, 0, false);


.addParticle — hash form [source,js]

scene3d.addParticle({ position: [x, y, z], velocity: [vx, vy, vz], gravity: [0, -9.8, 0], sizeStart: [0.5, 0.5], sizeEnd: [0.0, 0.0], colorStart: [1, 0.5, 0, 1], colorEnd: [1, 0.5, 0, 0], lifetime: 1.5, additiveBlending: true });

'''''

=== Scene3DModel (game-side)

Scene3DModel is a game-side ghost (Seeds / UnitGamePOCA.pas) that wraps a loaded
TGameInstanceableModel. It is obtained by calling engine.scene3d.loadModel(path).

NOTE: This ghost type is only available when running inside the Seeds game engine.
It uses the game's TGameInstanceableModels system, which handles glTF/GLB loading,
physics collision meshes, and animation.

.Scene3DModel creation
[cols="1,1,3"]
|===
|Function|Returns|Description

|engine.scene3d.loadModel(path)|Scene3DModel|Load a glTF/GLB asset synchronously. path may use the {models}/… prefix understood by the asset system.
|===

.Scene3DModel methods
[cols="1,1,3"]
|===
|Method|Returns|Description

|model.createInstance()|Scene3DInstance|Wrap the first backing TGameInstanceableModelInstance as a Scene3DInstance ghost. All transform, animation, and lifecycle methods of Scene3DInstance work on the returned value.
|model.unload()|null|Immediately free the underlying TGameInstanceableModel. The POCA ghost becomes a dangling reference; do not use it afterwards.
|===

.Scene3DModel example [source,javascript]

let model = engine.scene3d.loadModel('{models}/chess/board.glb'); let inst = model.createInstance(); inst.setPosition(0, 0.05, 0); // ... use inst ... model.unload();

'''''

=== Scene3DInstance

A Scene3DInstance is a live copy of a Scene3DGroup placed in the scene.
Obtained from group.createInstance().

The instance owns its own animation state and world transform.
Call inst.destroy() when the object is no longer needed — this releases the Pascal object.

NOTE: engine.scene3d (and therefore group.createInstance()) is created and managed by the game layer, not the engine directly.

[cols="1,3"]
|===
|Method |Description

|inst.setScene(sceneIdx) |Select which root scene within the group to render (integer index); returns inst.
|inst.setActive(bool) |Show or hide the instance; returns inst.
|inst.isActive() |Returns true if the instance is currently active.
|inst.setModelMatrix(m00,m01,…,m15) |Set the 4×4 double-precision world transform. Arguments are the 16 matrix elements in row-major order. Returns inst.
|inst.getModelMatrix() |Return the current world matrix as a 16-element flat array (row-major doubles).
|inst.setAnimation(idx, time [,factor [,additive]]) |Directly set animation idx (integer) to the given time (seconds), optional blend factor (default 1.0), and optional additive flag (default false). Returns inst.
|inst.setAnimationState(idx, {time?, factor?, additive?}) |Partial update via hash — only the keys present in the hash are applied. Returns inst.
|inst.getAnimation(idx) |Returns {factor, time, additive, complete} hash for animation idx.
|inst.setAnimationFactor(idx, factor) |Set the blend weight for animation idx. Returns inst.
|inst.setAnimationTime(idx, t) |Set the playback position (seconds) for animation idx. Returns inst.
|inst.setAnimationAdditive(idx, bool) |Set the additive blend flag for animation idx. Returns inst.
|inst.playAnimation(name [,loop [,speed]]) |High-level start: look up animation by name, reset time to 0, set factor = speed (default 1.0), set loop flag (default false). Returns true on success, false if name not found.
|inst.stopAnimation(name) |Stop the named animation: sets its factor and auto-advance speed to 0. Returns inst.
|inst.stopAllAnimations() |Stop all animations on this instance. Returns inst.
|inst.isAnimationPlaying(name) |Returns true if the named animation has a non-zero blend factor.
|inst.getAnimationTime(name) |Returns the current playback time (seconds) of the named animation, or null if not found.
|inst.setAnimationTimeByName(name, t) |Set the playback time of the named animation. Returns inst.
|inst.updateAnimations() |Advance all auto-playing animations by wall-clock delta, handle loop wrap-around or stop on completion, then call Instance.Update() to push state to the GPU. Returns inst. Call this once per frame for each animated instance.
|inst.getBakedMesh() |Not yet implemented — returns null.
|inst.createRenderInstance() |Create a new Scene3DRenderInstance (GPU render slot) for this instance. Returns the new ghost.
|inst.destroy() |Free the instance and its animation state. Invalidates the POCA ghost.
|===

.Example [source,javascript]

let inst = g.createInstance();
inst.setScene(0);
inst.setActive(true);
// identity matrix
inst.setModelMatrix(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1);

// play "walk" animation in a loop
inst.playAnimation('walk', true, 1.0);

// in the per-frame update function:
inst.updateAnimations();

let ri = inst.createRenderInstance(); ri.setActive(true); ri.setModelMatrix(1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1);

'''''

=== Scene3DRenderInstance

A Scene3DRenderInstance is a GPU draw-call slot for a Scene3DInstance.
Each instance can have multiple render instances (e.g., for instanced rendering at different positions).
Obtained from inst.createRenderInstance().

The render instance is owned by the Pascal TInstance — call ri.remove() to deregister it;
do not call Free. The POCA ghost is invalidated after remove().

[cols="1,3"]
|===
|Method |Description

|ri.setActive(bool) |Toggle GPU visibility of this render slot. Returns ri.
|ri.setModelMatrix(m00,m01,…,m15) |Set the 4×4 double-precision world transform for this render slot (16 row-major doubles). Returns ri.
|ri.remove() |Deregister this render instance from the GPU scene. Invalidates the POCA ghost.
|===

'''''

== Summary

The PasVulkan POCA Script API provides a comprehensive set of types and functions for game development:

  • Math Types: Vector2, Vector3, Vector4, Quaternion, Matrix3x3, Matrix4x4
  • Graphics Types: Sprite, SpriteAtlas, Texture, Font, CanvasFont, CanvasShape
  • Canvas API: Comprehensive 2D drawing with shapes, text, sprites, and paths
  • Input API: Keyboard, mouse, and pointer event handling
  • Audio API: Sound effects with polyphony and 3D spatialization, background music playback
  • Scene3D API: 3D scene-graph access — images, samplers, textures, materials, groups, meshes, primitives, nodes, and scenes with full PBR and hologram support

All types support operator overloading and provide fluent APIs for method chaining. The Canvas API is hardware-accelerated using Vulkan for high-performance 2D rendering. The Audio API provides both simple 2D and advanced 3D spatial audio capabilities.

For the base POCA scripting features (Array, Boolean, Console, String, Math, etc.), please refer to the link:https://github.com/BeRo1985/poca/blob/master/docs/scriptapi.adoc[POCA Script API Documentation].

'''''

== Integration with PasVulkan

To use these APIs in your PasVulkan application:

  1. Create a POCA context using the POCA library
  2. Call +InitializeForPOCAContext+ to register all PasVulkan types and functions
  3. Create a +TpvPOCAAudio+ instance to enable audio functionality
  4. Load and execute your POCA scripts
  5. Pass Canvas, Sprite, Font, and other objects from your PasVulkan application to scripts
  6. Handle input events and forward them to scripts through event hashes
  7. Call +FinalizeForPOCAContext+ when done to clean up resources

The PasVulkan POCA integration is designed to provide a complete scripting solution for games and applications built with PasVulkan.


Pascube Src Pasvulkan Docs Renderer Design (`pascube_src/pasvulkan/docs/renderer_design.md`)

Renderer Design overview

Introduction

This document provides an overview of the renderer design, focusing on the architecture and challenges associated with modern GPU-driven rendering techniques. It highlights the differences between traditional rendering methods and the current approach, particularly in terms of animation handling and memory management.

PasVulkan's renderer architecture is designed to be flexible and efficient, allowing for high-performance rendering in real-time applications. The architecture is built around the Vulkan API, which provides low-level access to the GPU and enables advanced rendering techniques.

The renderer is a strict GPU-driven architecture, meaning that all rendering operations are performed on the GPU rather than the CPU. This approach allows for better performance and scalability, as the GPU can handle large amounts of data in parallel. The renderer is a strict forward+ renderer, meaning that it uses a forward rendering pipeline with additional optimizations for handling large scenes and complex lighting.

Why no deferred renderer? And why forward+ clustered renderer?

Deferred rendering was once a popular choice for real-time graphics, particularly in the context of complex lighting and detailed scene management. However, as GPU architectures and rendering techniques have evolved, the limitations of deferred rendering have become more apparent, leading to a shift towards forward+ rendering and other modern techniques.

In short, while deferred rendering was a promising technique when introduced, it has proven less effective for today's GPU architecture and rendering techniques. Originally designed to enable more complex lighting models and scene details than traditional forward rendering, deferred rendering offered significant benefits in its time. However, as GPU capabilities have dramatically advanced, the demands of modern rendering, characterized by highly
detailed scenes, diverse material types, and intricate lighting, have started to reveal practical limitations of deferred rendering. Because the greater the material variety, the more complex the lighting becomes, deferred rendering's limitations in handling multiple material types and lights simultaneously become apparent, with the G-Buffer needing to store enormous amounts of data for each pixel (e.g., normals, depth, albedo, and additional material parameters), leading to increased memory usage and bandwidth demands. This results in significantly increased memory usage and bandwidth demands, even on modern GPUs optimized for handling large amounts of data in parallel.

Furthermore, the complexity inherent to deferred rendering can also introduce additional overhead in terms of shader management and resource binding, making it less suitable for real-time applications where performance is paramount. For instance, deferred rendering relies heavily on multiple render targets (MRT) and intermediate buffers, and the necessity to store intermediate data for each pixel, which consequently stresses memory bandwidth and requires substantial storage for these buffers, challenges that older hardware could somewhat manage but become limiting under current performance expectations. Modern GPUs, despite their increased memory capacities, benefit more from methods that offer greater flexibility and efficiency in handling the vast amounts of data present in contemporary scenes.

Deferred rendering's reliance on these intermediate steps not only leads to increased memory usage and bandwidth demands but also results in additional overhead due to the complexity of shader management and resource binding. This complexity is less of an issue with forward rendering, which typically avoids the need for multiple GPU passes and the storage of extensive intermediate data, resulting in more efficient resource usage and performance. As a consequence, while deferred rendering had historical significance in enabling advanced lighting and scene detail, its limitations in adaptability and efficiency render it less suitable for modern rendering pipelines that demand high performance and flexibility.

Modern rendering techniques such as forward+ emerged to address these challenges by blending the simplicity of forward rendering with advanced tile‑based or clustered light management and culling. Forward+ divides the scene into tiles or clusters and tracks which lights affect each region. During rendering, the engine ignores lights that do not influence a given tile, reducing the number of lights processed and lowering the computational cost. This method excels in scenes with many light sources because the renderer focuses only on those that matter. For forward+, a compute shader sorts the lights into a tile or cluster structure, allowing the renderer to efficiently access only the relevant lights for each pixel. This approach minimizes the overhead associated with managing multiple render targets and intermediate buffers, which are common in deferred rendering. And Material properties live in a bindless data structure so shaders fetch them on demand without multiple render targets or large intermediate buffers, even in a random access manner without the need for a pre-defined order. This allows for a more flexible and efficient rendering pipeline, as shaders can access only the data they need without the overhead of older methods By cutting bulky intermediate data this approach reduces memory use and bandwidth requirements compared with deferred rendering while still supporting diverse materials and lighting conditions at high performance.

Graphics hardware has also evolved to include features such as hardware‑accelerated ray tracing and advanced shading models that fit naturally into a forward+ pipeline. These capabilities enable realistic reflections, shadows and material interactions without the massive intermediate data storage that deferred rendering demands, making forward+ an ideal foundation for real‑time graphics development.

In summary, while deferred rendering once heralded a new era of complex lighting and detailed scene management, today's GPU architectures and rendering techniques have shifted towards approaches that better align with the demands of highly detailed, multi-material, and intensely lit scenes. The increased memory footprint, bandwidth usage, and overhead related to shader and resource management associated with deferred rendering have made it a less practical and viable choice for modern real-time applications, reinforcing the industry's move toward more efficient, flexible, and adaptable rendering strategies.

Single-Buffer Renderer Architecture

At PasVulkan a single‑buffer renderer architecture is adopted to leverage modern GPU capabilities and optimize rendering performance. All model data, including vertex attributes, indices and material properties, is stored in a single buffer per data type. This approach enables efficient random memory access and removes the overhead of multiple buffer bindings during rendering, avoiding costly state changes. By using one buffer the renderer can quickly access the necessary data for each draw call without extra bindings or state changes, improving performance and reducing CPU overhead. And in the optimal case, a single draw call can render multiple meshes, provided shaders have random access to all material data and textures. This is achieved through bindless data structures and bindless textures, which allow shaders to fetch material properties on demand without the need for multiple render targets or large intermediate buffers. This approach reduces memory usage and bandwidth requirements compared to deferred rendering while still supporting diverse materials and lighting conditions at high performance.

For hardware raytracing this design is required anyway since BLAS (Bottom‑Level Acceleration Structures) must be built from the same vertex data used for rasterization. Storing that data in one buffer ensures a consistent format and layout for both rasterization and raytracing. If separate buffers were used, memory usage would increase, and data management would become more complex.

Challenges of Modern GPU-Driven Renderer Architectures Compared to Traditional Approaches

In a GPU-driven renderer architecture, where all vertices are preprocessed per frame by a compute shader at the beginning of a frame and stored in a single "everything-in-one-single-buffer," the following problems arise regarding per-instance animations:

  1. Preprocessing of Vertex Data per Frame

    The compute shader calculates all vertex data for a specific animation state at the start of each frame and stores it in one large shared buffer. This data remains static and unchanged for the entire frame.

  2. Static Vertex Data for All Instances

    All subsequent rendering stages, including rasterization, further render passes, and hardware raytracing, access the same preprocessed vertex buffer. Consequently, all instances of the same model share the same animation state within a frame. Different animation states per instance are not possible unless separate mesh copies are created in the buffer for additional animation states, which in turn increases vRAM usage.

  3. Reduction of Draw Calls Through the "Everything-in-One-Single-Buffer" Approach

    The "everything-in-one-single-buffer" approach aims to reduce the number of draw calls using bindless data structures. Ideally, a single draw call can render multiple meshes, provided shaders have random access to all material data and textures. Older architectures required separate draw calls for each material and texture group, significantly increasing the number of draw calls and potentially impairing performance.

  4. Support for Hi-Z Two-Pass Occlusion Culling

    The "everything-in-one-single-buffer" approach is a prerequisite for Hi-Z two-pass occlusion culling. The culling compute shader needs access to all objects through a single linear object list with offset references to the respective vertex and index ranges within the large buffer. This enables efficient occlusion culling by quickly determining which objects are visible and which are not. Without a unified buffer, such efficient access would be difficult to achieve.

  5. Limitations Imposed by Hardware Raytracing (BLAS)

    Hardware raytracing requires the creation of Bottom-Level Acceleration Structures (BLAS), which rely on static vertex data. Although each BLAS can have its own transformation matrix, this only allows positioning, rotation, or scaling of the entire model, not changes in animation poses. Different animation states would require separate vertex data, which cannot be implemented within a single buffer.

  6. Necessity for Multiple Vertex Data Sets for Different Animation States

    To simultaneously represent different animation states, separate areas within the large buffer must be reserved for each required animation variant. Each "unique instance" with its own animation state thus requires individual preprocessed vertex data. This leads to a significant increase in vRAM usage because the same vertex data must be stored multiple times—for each distinct animation.

  7. Simplified Calculation of Motion Vectors

    Using a double-buffered "everything-in-one-single-buffer" approach simplifies the calculation of motion vectors. Direct access to the positions from the last and current frames in the shared buffer allows efficient computation of position differences for the motion vector render target. These motion vectors are essential for subsequent post-processing passes like antialiasing and motion blur, as they determine pixel motion direction and speed.

  8. Comparison with Older Rendering Methods

    In older GPU pipelines, animations and transformations were dynamically recalculated at runtime per render pass and pipeline stage in the vertex shader. Each instance could have its own animation state without additional memory for vertex data. However, this older method led to significant overhead in modern games because each render pass and pipeline stage continuously recalculated animations. Although the current approach with a precomputed large buffer sacrifices flexibility regarding animations per GPU instance—as all instances must use the same set of static vertices—it is often more performant overall.

Summary

In an architecture where a compute shader precomputes and stores all vertex data per frame in a large, static buffer, the following challenges arise:

  • Limited animation variety per frame: All instances of the same model share the same animation state within a frame.

  • Increased memory demand for different animations: Different animation states require separate vertex data sets in memory, increasing vRAM usage.

  • Reduced number of draw calls: While the "everything-in-one-single-buffer" approach reduces draw calls using bindless data structures, it complicates simultaneous representation of different animation states.

  • Necessity of a unified buffer for occlusion culling: The approach supports efficient occlusion culling but limits animation flexibility per instance.

  • Simplified calculation of motion vectors: The double-buffered approach simplifies motion vector calculations but further restricts animation flexibility due to consistent frame data storage.

  • Limited use of hardware raytracing: Static BLAS structures prevent flexible animation changes without additional memory overhead.

Compared to older rendering methods that allowed dynamic animations per instance, the new approach is less flexible and consumes more memory when representing various animation states simultaneously. Each unique instance can only display one animation state per frame unless memory usage is increased by duplicating vertex data for each animation.

Hi-Z Two-Pass Occlusion Culling

Introduction

Occlusion culling is a vital and critical optimization technique in real-time 3D rendering, particularly in complex scenes with many objects. Its primary goal is to avoid rendering objects that are completely hidden (occluded) from the viewer's perspective by other objects closer to the camera. By determining which objects are visible and culling those that are not, occlusion culling helps prevent the GPU from wasting resources on vertex processing, rasterization, and pixel shading for hidden geometry. This technique is especially important in modern game engines, where performance and efficiency are critical for delivering high-quality, real-time experiences.

Hierarchical Z-Buffer (Hi-Z) Two-Pass Occlusion Culling is a popular and efficient GPU-driven technique to achieve this. It leverages a mipmapped representation of the depth buffer (the Hierarchical Z-Buffer) to perform occlusion tests rapidly on the GPU, minimizing CPU involvement and avoiding costly read-backs from the GPU to the CPU.

This document outlines the Hi-Z Two-Pass Occlusion Culling technique, its implementation, and its advantages in modern rendering pipelines. It also discusses the challenges associated with implementing this technique in a GPU-driven architecture, particularly in the context of the "everything-in-one-single-buffer" approach.

Core Concept: The Hierarchical Z-Buffer (Hi-Z)

The foundation of this technique is the Hierarchical Z-Buffer (Hi-Z). It's essentially a mipmap pyramid generated from the scene's depth buffer (Z-buffer).

  1. Base Level (Mip 0): This is the standard, full-resolution depth buffer generated by rendering some geometry (see Pass 1).
  2. Subsequent Levels (Mip 1, Mip 2, ...): Each subsequent level is a downsampled version of the previous one. For instance, Mip 1 might be half the width and height of Mip 0.
  3. Depth Value Storage: Crucially, each texel (pixel) in a higher mip level (lower resolution) stores a single depth value that represents the depth information of the corresponding block of texels (e.g., 2x2, 4x4) in the lower mip level (higher resolution). For occlusion culling, each texel in the Hi-Z typically stores the minimum depth value (i.e., the nearest Z value) within its corresponding region in the finer level. PasVulkan supports both standard-Z (0 = near plane, 1 = far plane) and reversed-Z (1 = near plane, 0 = far plane) depth conventions. In reversed-Z mode the pyramid stores the maximum depth value per texel instead, since the nearest surface has the highest Z value; occlusion comparisons are inverted accordingly.

This hierarchical structure allows for quick depth comparisons against large screen-space regions by sampling from the appropriate (coarser) mip level.

The Two-Pass Process

As the name suggests, the technique generally operates in two - but actually three since the Z-prepass is a separate pass, but it is often combined with the Hi-Z generation pass, so it is not counted as a separate pass - main passes executed on the GPU:

Pass 1: Depth Pre-Pass and Hi-Z Generation

  1. Z-Prepass (with Temporal Coherence Visibility):
    Render the last frame visible objects in the scene to establish an initial depth buffer, or everything (but frustum culled) into the depth buffer only (Z-prepass) to establish a baseline depth buffer for the Hi-Z generation. This is often done using a simplified shader that only writes depth information. The Z-prepass can be thought of as a "depth-only" rendering pass where the goal is to write the depth values of the major occluders in the scene. This pass typically renders all static objects and dynamic objects that are not occluded by other objects. The Z-prepass is crucial for establishing a baseline depth buffer for the Hi-Z generation. Important that no reprojection from the previous frame depth buffer - as it was done in the past by other implementations - is done here, since it is and was a bad idea, since it can lead to incorrect depth values and artifacts in the Hi-Z buffer. The Z-prepass should be done with the current frame's geometry to ensure that the depth information is accurate and up-to-date. So rendering only the objects that were determined to be visible in the last frame into the current frame's initial depth buffer. This leverages temporal coherence to potentially save rendering cost and avoid slight inaccuracies or latency with very fast-moving objects, which wouldn't be the case if reprojection from the previous frame depth buffer would be done here.

  2. Hi-Z Buffer Construction:
    Using the depth buffer generated in the previous step, construct the Hi-Z mipmap pyramid. This is typically done using compute shaders or specialized hardware features. Starting from the full-resolution depth buffer (Mip 0), successive downsampling passes are performed. In each pass, a compute shader reads a block of texels (e.g., 2x2) from the source mip level and writes the minimum (nearest) Z value among them to the corresponding single texel in the destination (coarser) mip level (or the maximum when using reversed-Z). This process repeats until the smallest mip level (often 1x1) is generated.

Pass 2: Occlusion Query Pass

This pass determines the visibility of the remaining objects (potential occludees) that were not rendered in the initial Z-prepass.

  1. Prepare Occludee List: Identify the draw nodes whose visibility needs testing. In PasVulkan the tested granularity is the TGroup mesh node — a single mesh node within a glTF scene graph — not the top-level scene object or the whole TGroup. This usually involves nodes that passed view-frustum culling. For each node, its bounding sphere is used for the occlusion test.
  2. GPU-Based Testing: This pass is implemented as a compute shader operating over the visible draw-node list. For each potential occludee:
    • Project Bounding Sphere: The object's bounding sphere (center + radius) is projected analytically onto the screen (projectSphere), yielding a screen-space circle that conservatively bounds the projected sphere.
    • Find Screen-Space Footprint: The axis-aligned bounding rectangle of the screen-space circle is used as the test region.
    • Determine Front-Face Depth ($Z_{front}$): The view-space depth of the sphere's front face (center depth minus radius, clamped to the near plane) is computed and expressed in the same depth representation as the Hi-Z samples.
    • Select Hi-Z Mip Level: Based on the screen-space size of the projected sphere's footprint, an appropriate mip level is selected from the Hi-Z buffer. Smaller projections can use coarser (higher) mip levels for faster queries.
    • Sample Hi-Z: Sample the Hi-Z buffer within the screen-space footprint at the selected mip level to find the nearest occluder depth ($Z_{HiZ}$) already rendered in that region during Pass 1.
    • Perform Depth Test: Compare the object's front-face depth against the nearest occluder from the Hi-Z:
      • If the sphere's front face is behind $Z_{HiZ}$: The object is entirely occluded and culled.
      • Otherwise: The object is considered potentially visible and proceeds to rendering.
  3. Generate Visibility Results and Indirect Draw Commands:
    The results of these tests (a list or buffer indicating whether each object is visible or occluded) are stored on the GPU. This visibility information is then used in the main rendering pass to draw only the objects that are potentially visible. Additionally, indirect draw commands
    are written to a buffer for the objects that passed the occlusion test. This buffer contains the draw commands for the visible objects, which will be used in the main rendering passes. The indirect draw command buffer is a GPU-side structure that allows for efficient rendering of multiple objects in a single draw call, reducing CPU overhead and improving performance.
  4. Render Rest Of Visible Objects Into the Depth Buffer:
    The objects that are not occluded (i.e., those that passed the depth test) are rendered into the same depth buffer as well, for to construct the final depth buffer for the main rendering passes, so that early depth testing (early-Z testing) can be used to skip over occluded fragments in the main rendering pass. This is important for performance, as it allows the GPU to skip processing fragments that are occluded by other objects.

Per-Meshlet Culling (Mesh Shader Extension)

When the mesh shader path is active, visibility testing is further refined at the meshlet level as a third culling tier inside the same compute passes. This is described in full in the Meshlet Rendering section. In brief:

  • Normal mesh-shader path: mesh_cull.comp emits per-object task-shader dispatches. The task shader (mesh.task) then performs per-meshlet bounding-sphere frustum and Hi-Z culling within each workgroup of 32 meshlets before forwarding surviving meshlets to the mesh shader via task payload.
  • MESHLET_EXPAND mode: The task shader is skipped. mesh_cull.comp itself handles per-meshlet culling in Pass 1, appending each surviving meshlet to a scratch buffer for subsequent sorting and direct mesh-shader dispatch.

Main Rendering Pass

Finally, the main rendering passes draws the scene on the screen using the visibility results from the previous occlusion query pass in one go. This is typically done using indirect draw commands, which allow the GPU to efficiently render multiple objects in a single draw call or few draw calls, reducing CPU overhead and improving performance. The indirect draw command buffer generated in the previous occlusion query pass is used to issue the draw calls for the visible objects. This allows the GPU to efficiently render only the objects that are potentially visible, skipping over those that were determined to be occluded in the previous pass. Shader optimizations can allow reusing the depth from the prepass to avoid redundant depth calculations (Equal Depth Test).

Advantages

  • GPU Driven: Performs culling directly on the GPU, avoiding CPU bottlenecks and costly GPU-CPU data transfers (read-backs).
  • Efficient for Many Objects: Scales well with a high number of potential occludees.
  • Handles Dynamic Scenes: By regenerating the Hi-Z buffer each frame (or frequently), it correctly handles moving occluders and occludees.
  • Conservative: The use of bounding spheres and minimum depth values in the Hi-Z buffer ensures that objects are generally not culled incorrectly. False negatives are rare or even completely avoided when implemented correctly. However, the technique may occasionally classify occluded objects as visible, resulting in false positives. This is acceptable and even preferable, since rendering a few unnecessary objects (overdraw) is safer than missing visible ones.
  • No Latency: Because no reprojection is involved, the Hi-Z buffer accurately reflects with the current frame's geometry at all times. This offers a key advantage over older Hi-Z techniques based on reprojection but following a similar overall concept, which could suffer from latency and precision loss in scenarios involving high-velocity motion, object transformations or rapid geometric alterations. By directly deriving the Hi-Z buffer from the present frame, this approach ensures real-time, accurate occlusion without the artifacts inherent in reprojecting previous depth data, crucial for maintaining visual fidelity in demanding scenarios.

Disadvantages

  • Overhead: Requires a Z-prepass (adds draw calls) and compute resources for Hi-Z generation and the query pass. May not be beneficial in simple scenes where occlusion is minimal, but it doesn't hurt either on modern GPUs as they can handle it well.
  • Memory Usage: The Hi-Z buffer requires additional memory, especially for high-resolution textures. This can be a concern on lower-end hardware or when many mip levels are used.
  • Potential Inaccuracy: Testing against bounding spheres is an approximation, where objects might be marked visible even if technically occluded, especially with complex elongated shapes or poorly fitting bounding spheres. However, this conservative approach is intended to prevent false negatives, making the resulting false positives generally acceptable in real-time rendering, unlike false negatives which would indicate incorrect implementations.
  • Complexity: Implementation requires careful handling of coordinate spaces, depth precision, and GPU synchronization.

Conclusion

Hi-Z Two-Pass Occlusion Culling is a powerful, GPU-centric technique for improving rendering performance in complex 3D scenes. By building a hierarchical representation of the depth buffer and using it to perform fast visibility tests on the GPU before the main rendering pass, it effectively skips the processing and rendering of objects hidden from view, freeing up GPU resources for visible geometry and effects.

Model Data Management

Introduction

Efficient model data management is critical for modern rendering engines to achieve high performance and flexibility. PasVulkan uses GLTF as its base foundational model format, extending it internally for improved data representation, compatibility, and efficiency. Its key design principles include a single buffer architecture, bindless data structures, and an optimized approach for handling animations and transformations.

Beyond glTF, PasVulkan can also import Collada (.dae), Wavefront OBJ (.obj), and FBX (.fbx) files. All three are implemented as fully native Pascal loaders with no third-party libraries, residing in PasVulkan.FileFormats.DAE.pas, PasVulkan.FileFormats.OBJ.pas, and PasVulkan.FileFormats.FBX.pas respectively. Regardless of the source format, the importer converts the data into the same internal representation as glTF, so all downstream systems (meshlet building, LOD, PVMF caching, GPU buffers) work identically for all formats.

The same native-Pascal philosophy applies to image and texture formats. BMP, PNG, JPEG, TGA, QOI, and KTX1 all have fully self-contained Pascal loaders and writers (PasVulkan.Image.BMP.pas, PasVulkan.Image.PNG.pas, PasVulkan.Image.JPEG.pas, PasVulkan.Image.TGA.pas, PasVulkan.Image.QOI.pas), with no external dependencies. The sole exception is KTX2: because KTX2 requires Basis Universal GPU texture compression transcoding, PasVulkan loads the Khronos libktx shared library at runtime (ktx.dll / libktx.so / libktx.dylib) to handle KTX2 files.

glTF 2.0 Compatibility and Game-Oriented Design

PasVulkan strives to maintain broad glTF 2.0 compatibility while simultaneously being practical for game use. The philosophy is: support the full richness of the Khronos ecosystem wherever possible, but integrate it into a pipeline that performs well in real-time gameplay scenarios.

On the compatibility side, the engine parses and applies a wide set of official Khronos extensions:

Category Extensions
Materials KHR_materials_unlit, KHR_materials_pbrSpecularGlossiness, KHR_materials_specular, KHR_materials_sheen, KHR_materials_clearcoat, KHR_materials_emissive_strength, KHR_materials_ior, KHR_materials_iridescence, KHR_materials_transmission, KHR_materials_diffuse_transmission, KHR_materials_volume, KHR_materials_anisotropy, KHR_materials_dispersion
Textures KHR_texture_transform, KHR_texture_basisu (Basis Universal)
Animation KHR_animation_pointer (animate any property by JSON pointer)
Lights KHR_lights_punctual
Scene graph KHR_node_visibility
LOD MSFT_lod, MSFT_screencoverage

On the game-engine side, several pragmatic choices ensure real-time viability:

  • All model data is pre-processed at import time (meshlet building, LOD metadata, bounding spheres, material deduplication) and serialised into the PVMF cache (see below), so nothing expensive happens at runtime.
  • Material and texture deduplication across the entire scene reduces GPU memory and descriptor overhead.
  • Features that are visually compelling but prohibitively expensive (e.g. CVCT voxelisation via geometry shaders) are retained in the codebase for completeness but flagged as non-production-ready.
  • The renderer intentionally avoids G-buffer intermediate stages and deferred shading, keeping the forward+ pipeline lean enough for complex open-world scenes.

PVMF: Pre-Processed Model Cache Format

Loading a glTF file at runtime is expensive: JSON parsing, mesh attribute decoding (potentially with Draco or Basis Universal), meshlet construction, LOD metadata extraction, and material deduplication can all take significant time for large models. To avoid repeating this work on every game start, PasVulkan defines PVMF (PasVulkan Model Format) — a binary cache format.

When a group is first imported from glTF the engine can serialise the fully post-processed internal state (meshes, primitives, meshlets, LOD metadata, materials, textures, animations, skins, nodes, scenes) to a PVMF stream via TGroup.SaveToStream. On subsequent launches the engine detects the PVMF header ('P','V','M','F' signature + version tag PVMFVersion) and calls TGroup.LoadFromStream, which deserialises the ready-to-use data directly — no JSON parsing, no meshlet rebuilding, no LOD calculation.

Key properties of PVMF:

  • Version-locked: The version constant (PVMFVersion) is bumped whenever the internal data layout changes. A stale cache file is detected by the version mismatch and triggers a clean re-import from the original glTF.
  • Stores all pre-computed data: Meshlets (MeshletDescriptorBuffer contents), LOD TGPULODInfo structs, bounding spheres, material GPU structs, and texture metadata are all written to the cache, so the comment in the importer reads // CollectMeshlets; // already loaded from PVMF.
  • Not a distribution format: PVMF is an engine-internal cache. It is not intended to be shipped directly to end users or used as an interchange format between tools.

Model Instance Structure

To manage instances efficiently, particularly regarding animations and transformations, PasVulkan organizes model instances into a clear hierarchy:

1. **TpvScene3D.TGroup**

  • Contains shared model data such as vertex attributes, indices, and material information.
  • Shared across all instances of the same model to reduce redundancy.
  • It does not directly contain instance-specific GPU data as whole, but rather serves as the base structure from which instances derive.
  • Per group data includes:
    • Materials:
      • Materials are TpvScene3D global, but linked per-group-wise. Deduplication of materials across groups happens during loading, ensuring that materials are not duplicated unnecessarily. The deduplication is done per hash table lookup of a hash value of the raw data of the material.
    • Textures:
      • Textures are TpvScene3D global, but linked per-group-wise. Deduplication of textures across groups happens during loading, ensuring that textures are not duplicated unnecessarily. The deduplication is done per hash table lookup of a hash value of the raw data of the texture.
      • Maximum 32,768 textures are supported inside TpvScene3D, which is sufficient for most applications. This limit is imposed by internal structures and optimizations, for example because each texture is accessible both as a linear RGB and as an sRGB image view for random shader access with interpolation-compatible color-type handling, requiring two slots per texture in the descriptor set. Consequently, the effective limit is 32,768 textures, as the internal hardcoded array size in the TpvScene3D texture descriptor management system is 65,536 (defined as a constant), divided by two. This allows a large number of textures to be used without exceeding the descriptor set slot limit.

2. **TpvScene3D.TGroup.TInstance**

  • Contains unique per-instance data, notably animation states and transformation matrices.
  • Enables different instances to independently animate without duplicating the entire model data, reducing overall memory usage.
  • Requires additional preprocessed vertex data stored once per frame (not per draw call), particularly important for ray tracing, which relies on pre-baked vertex buffers calculated via compute shaders at each frame start.
  • Balances flexibility (unique animations per instance) and memory overhead (additional CPU/GPU memory usage).
  • Per-instance data includes:
    • Animation State:
      • Defines the current animation state per instance.
    • Scene State:
      • Defines the current GLTF Scene state per instance, which is used to determine the current visible nodes in the scene graph and to apply the correct transformations to the instance.
    • Vertices:
      • Input data is split into static and dynamic parts.
      • Static input includes texture coordinates, vertex colors, and material indices.
      • Dynamic input includes position, morph target base index, joint block base index, joint block count, root node index, node index, normal (oct-encoded int16×2), tangent (oct-encoded int16×2), flags (e.g., sign of bitangent), and generation.
      • Dynamic output is double-buffered across two large shared buffers to enable motion vector computation.
      • Additionally, a position-only output buffer is used for acceleration structures (BLAS). These position-only vertices omit the root transformation matrix, as the root transformation is applied by the bottom-level acceleration structure (BLAS) instance data, which is used for hardware ray tracing.
      • Approximate cost is ~3× vertex data per instance.
      • Duplication is necessary since the vertex data contains per-instance positions, indices to materials, morph target and joint data offsets.
      • The generation field is used to determine whether the previous frame's vertex data corresponds to the current frame, allowing correct motion vector calculation.
    • Indices:
      • Each instance has its own index buffer referencing its portion of the shared vertex buffer.
      • This allows distinct vertex ranges per instance.
    • Matrices:
      • Includes transformation matrices for positioning, rotation, and scaling per group node and bone joint matrices. This includes the root transformation matrix for the instance, which is applied to all vertices during processing in the compute shader, or in the case of GPU instances, applied to the instance data in the vertex shader.
    • Bone Joint Indices and Weights:
      • Implemented using a linear list of quads (groups of 4 indices/weights), supporting variable bone influence per vertex, where each vertex has a start offset and count of bone influence quad blocks in their corresponding shared data buffers.
      • Enables high flexibility at the cost of increased compute complexity.
      • This structure allows the compute shader to dynamically walk through bone influences per vertex without artificial limits.
      • A high number of bones per vertex increases GPU workload due to complex branching and loop iterations in the compute shader. The more bones influence a vertex, the more branching and loop steps the GPU must execute, increasing computational load, cache-misses and potentially leading to performance bottlenecks.
    • Morph Targets / Blend Shapes:
      • Optional support for advanced deformations.
      • Implemented using a linked list per-vertex and per-morph-vertex-wise, allowing for flexible morph target management, where each vertex has a starting morph target offset index pointing to the first linked list entry, or zero if no morph targets are applied.
      • A high number of morph targets per vertex increases GPU workload due to complex branching and loop iterations in the compute shader. The more morph targets influence a vertex, the more branching and loop steps the GPU must execute, increasing computational load.
      • A high number of morph targets per vertex can lead to increased memory usage, as each morph target requires additional storage for its vertex data. This can be a concern in memory-constrained environments, such as mobile devices or low-end GPUs.
    • Animated Materials:
      • Instances can have unique animated material variants.
      • Static materials are shared; animated materials are duplicated per instance.
        • Per-instance animated materials are duplicated to allow instance-unique material animation states. This is necessary for animated material properties, which require per-instance material values independent of the shared global material data.
        • Static (non-animated) materials are shared to avoid duplication.

3. **TpvScene3D.TGroup.TInstance.TRenderInstance**

  • Represents specific occurrences of the same unique instance in the scene with varying root transformations.
  • Enables multiple renderings of the same animated instance without duplicating unique animation data, conserving memory.
  • Stores per-render-instance properties such as root transformation matrix, specialized shader effects (selection highlighting, holographic effect, and so on) that are independent of the core animation and instance data.
  • A TpvScene3D.TGroup.TInstance can have multiple TpvScene3D.TGroup.TInstance.TRenderInstance objects, each representing a different rendering of the same animated instance with its own root transformation and optional shader effects. And an TpvScene3D.TGroup.TInstance can even have no TpvScene3D.TGroup.TInstance.TRenderInstance objects, then it is treated as a render instance itself, which can be useful for certain cases where the instance is rendered directly without need for additional render instances or instance-specific effects. But this should be avoided in most cases for new code, as it can be changed in the future, so that TpvScene3D.TGroup.TInstance.TRenderInstance is always required for rendering, for to simplify and to optimize the rendering pipeline even further and to allow for more flexibility in the future.

Notes

Indeed, this is a little bit confusing, that two things are called "instance" in the PasVulkan renderer, but they are different things. The first one is the TpvScene3D.TGroup.TInstance, which is a unique instance of a model with its own animation state and transformation data, while the second one is the TpvScene3D.TGroup.TInstance.TRenderInstance, which represents a specific occurrence of that unique instance in the scene with varying root transformations. This distinction allows for efficient management of model instances and their rendering properties.

4. **Virtual Instances (TVirtualInstanceManager)**

For scenes with many near-identical objects (asteroids, trees, crowd characters …) manually managing one full TGroup.TInstance per object would be prohibitively expensive in VRAM and preprocessing time, since every unique animation state requires its own vertex buffer copy. The Virtual Instance System solves this by decoupling lightweight user-facing virtual instances from the small pool of non-virtual instances that own the actual GPU resources:

  • Virtual instances (CreateInstance(Virtual:=true)) — lightweight objects (~few hundred bytes). Each carries a transform, animation state, and scene index. They never own GPU buffers directly.
  • Non-virtual instances — a fixed, preallocated pool per group. Each owns the full GPU resources (vertex buffers, joint matrices, etc.) and is recycled rather than freed.
  • Render instances — a preallocated pool per non-virtual instance. Used for GPU hardware instancing: multiple virtual instances with the same animation state share one non-virtual instance and are drawn in a single instanced draw call.

Each frame TVirtualInstanceManager.UpdateAssignments() runs a two-step greedy assignment:

  1. Diversity pass — each non-virtual instance is paired with the most dissimilar unassigned virtual instance to maximise the range of animation states represented in the pool.
  2. Instancing pass — remaining virtual instances are paired with the most similar active non-virtual instance, sharing its GPU resources via render-instance hardware instancing.

Similarity is scored from animation time and blend-factor differences, with a temporal coherence bonus (+5.0) for same-frame-as-last-frame assignments and a switching penalty (−1.0) to minimise popping.

For full API details, configuration options, and usage examples see docs/scene3d_virtualinstances.md.

Decal System

The decal system projects textures onto surfaces at runtime without extra geometry or dedicated render passes. Typical uses are bullet holes, scorch marks, dirt, footprints, graffiti, and gameplay indicators.

Each decal is defined by a world-space position, an orientation quaternion, an optional rotation around the forward axis, and a size (width × height in metres). From these, a world-to-decal transform matrix is computed once at spawn time and uploaded to the GPU. In the fragment shader, every rendered surface fragment is inverse-transformed into decal space; if it falls inside the unit cube, the decal textures are sampled and blended.

Key aspects of the implementation:

  • Full PBR workflow: A decal can supply separate textures for albedo, normal map, and ORM (occlusion / roughness / metallic). It modifies all PBR properties of the surface it lands on, not just colour.
  • Six blend modes: AlphaBlend, Multiply, Overlay, Additive, JustPBR (PBR properties only, no albedo), and JustNormalMap (normal perturbation only).
  • Dual lookup strategy: In the default LIGHTCLUSTERS path a compute shader (frustumclustergridassign.comp) assigns decals to frustum-space cluster cells each frame; fragment shaders iterate only the decals in their cluster. A BVH skip-tree path is also maintained for ray tracing / path-tracing use cases.
  • Order-stable rendering: Decals are stored in an append-only list. Deletion sets the slot to nil and defers compaction to PrepareFrame, so the relative order of surviving decals never changes and overlap is flicker-free.
  • Lifetime and fade-out: Each decal carries an optional lifetime (seconds) and fade-out duration. The engine ages decals in UpdateDecals, marks expired ones, and compacts on the next frame.
  • Pass filtering: Each decal records which render passes it applies to (mesh, planet surface, grass, etc.), so decals are evaluated only in relevant fragment shaders.
  • Holder tracking: Decals can be associated with a scene object (planet, vehicle). If the holder moves, the decal moves with it.

For full API reference, shader integration details, and performance guidance see docs/scene3d_decals.md.

Single Buffer Architecture and Bindless Access

PasVulkan uses a single buffer architecture to enable efficient random access to various data with minimal overhead. This eliminates the need for frequent buffer bindings, improves performance, and significantly reduces buffer binding overhead during rendering, enhancing real-time performance.

Bindless data structures allow shaders to random access mesh data, materials and textures directly, without extra render targets or intermediate buffers. This design reduces GPU memory traffic and is more efficient than other traditional approaches. It's needed for modern rendering techniques like forward+ and hardware ray tracing, where efficient data access is crucial for performance.

Handling Per-Instance Animations

In GPU-driven pipelines like PasVulkan, all vertex data must be preprocessed at the start of each frame for all subsequent stages, including rasterization and hardware ray tracing. Each distinct animation state requires a separate TpvScene3D.TGroup.TInstance, increasing memory usage.

To avoid excessive memory consumption, PasVulkan requires the use of intelligent animation-state-grouping. Developers must manually cluster similar animation states to reduce the number of unique instances.

This technique involves trade-offs:

  • Reduces memory usage and preprocessing time.
  • May lead to animation state time-jumping when no suitable instance is available, causing minor visual artifacts.
  • Preferred over rendering failure or complete duplication of data.

Animation-state-grouping is a necessary optimization in GPU-driven rendering architectures, especially in those being compatible with hardware ray tracing, demanding thoughtful preprocessing and grouping logic from developers. Hardware ray tracing requires static vertex data for BLAS (Bottom-Level Acceleration Structures), which must be precomputed and stored in a single buffer. This design choice ensures consistency between rasterization and ray tracing, as both processes rely on the same vertex data.

In older GPU pipelines and render implementations, per-instance animations were often recalculated dynamically in the vertex shader at runtime. This allowed each instance to maintain a fully unique animation state without consuming additional memory. However, this method becomes increasingly inefficient in modern rendering pipelines, as the continuous per-frame recalculation introduces significant performance overhead.

Furthermore, such dynamic vertex transformations are fundamentally incompatible with hardware ray tracing, which requires static vertex data for building Bottom-Level Acceleration Structures (BLAS). Any runtime-calculated animation data would violate this consistency, rendering the approach unusable for ray tracing. In addition, these structures must be constructed from the same precomputed vertex data used during hybrid rasterization, ensuring consistency across both stages. Otherwise, the ray tracing process would not be able to accurately represent the geometry as it was rendered, leading to potential visual artifacts and inconsistencies in the final image, such as incorrect shadows, reflections, and intersections.

Modern GPU-driven architectures such as PasVulkan therefore trade flexibility for performance and compatibility. While per-instance uniqueness is still supported, it relies on explicit preprocessing and memory allocation. Developers must carefully manage animation-state grouping and memory layout to avoid unnecessary duplication as well as both excessive memory and runtime cost.

This requirement for explicit preprocessing and duplication of animation states contributes to higher memory consumption in modern games. As a result, even titles with similar or only marginally improved visual quality compared to older games may demand significantly more video RAM (vRAM). This increased memory footprint is partly driven by the need to store multiple precomputed animation states and related data structures, which were previously avoided by dynamic runtime calculation but are now necessary for compatibility with advanced rendering features like hardware ray tracing as well as other modern rendering techniques and performance optimizations.

Dynamic Level of Detail (LOD)

PasVulkan implements a GPU-driven dynamic Level of Detail (LOD) system that automatically adjusts model detail based on screen-space coverage. The LOD selection runs entirely on the GPU inside the mesh culling compute pass (mesh_cull.comp), which rewrites draw commands to use the appropriate LOD level for each visible instance.

Key aspects of the implementation:

  • Per-submesh LOD metadata: Each LOD-enabled submesh stores a TGPULODInfo structure (128 bytes) containing up to four LOD levels (CountLODs = 1..4), along with screen-coverage thresholds (Thresholds[0..3]), index offsets (FirstIndices), index counts (CountIndices), vertex offsets (FirstVertices), and meshlet range descriptors (MeshletLocalOffsets, MeshletCounts). CountLODs = 1 means no LOD variation (noop).

  • GPU-side selection: During the MeshCullPass0 and MeshCullPass1 compute passes, the shader evaluates per-instance screen coverage (the minimum over all active views of max(projected AABB width, projected AABB height)) against the stored thresholds and selects the appropriate LOD level. The command rewriting — updating the index/vertex offsets in cmd0 draw commands — happens directly inside mesh_cull.comp via buffer device address writes. In temporal mode, the selected LOD level is additionally written to per-in-flight-frame LODLevelBuffers for use in the following frame.

  • FinalView pass only: LOD command rewriting is currently active only for the final view render pass (TpvScene3DRendererCullRenderPass.FinalView). Shadow-map passes (e.g. cascaded shadow maps) and other auxiliary passes receive no LOD simplification and always use the full-detail base level.

  • Temporal stability: To avoid LOD popping, the system supports an optional temporal mode controlled by FLAG_LOD_TEMPORAL. When LODTransformAllLevels is false, temporal mode is enabled: the shader reads the previous frame's selected LOD from LODLevelBuffers to rewrite commands one frame ahead of the threshold crossing, avoiding one-frame visual glitches. When LODTransformAllLevels is true (the default), temporal mode is disabled and all LOD levels are transformed each frame. FLAG_LOD_RESET_FRAME is set during the first CountInFlightFrames frames after startup and also on any camera reset, causing all LOD levels to be treated as active to fully prime the state. The lodNeeded bitfield (per nodeMatricesIndex, atomically OR'd with a renderer-instance bitmask) tracks which nodes require vertex transform in the current frame; this is separate from the per-instance LOD level history stored in LODLevelBuffers.

  • Integration with occlusion culling: LOD selection occurs inside the same GPU-driven culling pipeline as Hi-Z occlusion culling, ensuring that distant or small objects are both occluded and simplified with minimal CPU overhead.

  • glTF import and MSFT_lod extension: During glTF import, the engine reads the Microsoft MSFT_lod extension from nodes (node.extensions.MSFT_lod.ids) to build per-node LOD variant lists (fLODNodeIndices). Optional screen-coverage thresholds are read from node.extras.MSFT_screencoverage (fLODScreenCoverages). Materials also support MSFT_lod via material.extensions.MSFT_lod.ids (fLODMaterialIndices), allowing both geometry and material to vary per LOD level. If no explicit thresholds are provided, the engine falls back to a default power-of-two halving scheme (0.25, 0.125, 0.0625, ...) for the thresholds stored in TGPULODInfo. This fallback is independent of the default CPU-side heuristic in SelectNodeLODLevel.

  • Asset preprocessing: LOD data is generated during asset import / build time and serialized with the scene. The engine stores precomputed LOD metadata in its own binary format (TGPULODInfo) alongside the imported geometry, so no glTF re-parsing is required at runtime.

The GPULODEnabled property on TpvScene3D toggles the feature (enabled by default), while LODTransformAllLevels controls whether temporal mode is active: false enables temporal mode (only the previously selected LOD level is transformed each frame); true (the default) disables temporal mode and transforms all LOD levels every frame.

Meshlet Rendering

PasVulkan supports GPU-driven meshlet rendering as an optional tier on top of the Hi-Z two-pass culling pipeline, available when the device exposes mesh shader support (VK_EXT_mesh_shader). Meshlets partition each primitive into small, independently cullable triangle clusters, enabling fine-grained GPU-side visibility determination that goes beyond node-level (per TGroup mesh node) culling.

Meshlet Data Structures

A meshlet is a self-contained cluster of up to 64 vertices and 126 triangles — the practical hardware limits across current GPU generations (the Vulkan specification allows up to 256, but exceeding real hardware limits triggers slow emulation). Three shared global buffers hold all meshlet data across the entire scene:

  • MeshletDescriptorBuffer — one TGPUMeshletDescriptor (32 bytes) per meshlet, containing: bounding sphere (vec4: center XYZ + radius), vertex offset and count within MeshletVertexBuffer, primitive offset and count within MeshletPrimitiveBuffer.
  • MeshletVertexBuffer — remapped per-meshlet vertex indices (uint32), referencing the global vertex buffer.
  • MeshletPrimitiveBuffer — packed triangle index triples (3× uint8 per triangle, stored as uint32).

Meshlets are built during glTF import (BuildMeshlets) for triangle-list primitives. Per-meshlet bounding spheres are updated to world space each frame for accurate culling. Culling is enabled per-node via FLAG_MESHLET_CULLING_ENABLED (bit 3 of the cull flags).

LOD Integration

TGPULODInfo stores MeshletLocalOffsets[0..3] and MeshletCounts[0..3] alongside the standard index/vertex ranges, so LOD level switching operates at meshlet granularity. When the GPU selects a lower LOD, only the corresponding meshlet sub-range is dispatched, with no CPU involvement.

Rendering Paths

Two distinct rendering paths are available depending on whether MESHLET_EXPAND is defined at shader compile time:

1. Normal mesh-shader path (default)

mesh_cull.comp performs per-node (per TGroup mesh node) frustum and Hi-Z culling and, for each surviving node, emits one indirect task-shader dispatch with groupCountX = ceil(meshletCount / 32). The task shader (mesh.task, TASK_GROUP_SIZE = 32) then runs one workgroup per 32 meshlets: in Pass 0 it applies per-meshlet frustum culling only; in Pass 1 it additionally tests each meshlet's bounding sphere against the Hi-Z pyramid. Meshlets that survive are forwarded via the task payload to the mesh shader (mesh.mesh) for rasterization.

2. MESHLET_EXPAND mode (alternative compile-time variant)

The task shader is bypassed entirely. mesh_cull.comp itself performs per-meshlet culling: Pass 0 submits all meshlets unconditionally; Pass 1 applies frustum and Hi-Z culling per meshlet and appends each surviving meshlet as a separate command entry to a global scratch buffer via atomicAdd. A subsequent sort compute pass (mesh_cull_sort.comp) scatters the unsorted scratch entries into per-range output positions. The mesh shader is then dispatched directly with one workgroup per meshlet, with no task shader involvement.

Fallback Path

When mesh shader support is unavailable, PasVulkan falls back transparently to standard vkCmdDrawIndexedIndirect using the conventional vertex/index pipeline. No meshlet culling is performed in this path; node-level Hi-Z culling (per TGroup mesh node, independent of meshlets) still applies. Because culling granularity is already at the mesh-node level rather than the whole-object level, this fallback path can achieve culling effectiveness comparable to the mesh-shader path — provided the glTF content is well-subdivided into mesh nodes. Content authors can therefore influence culling quality directly through their scene graph structure, even on hardware without mesh shader support. There is however a natural limit to this approach: mesh-shader culling can cull at meshlet granularity within a single node, which is critical for large, spatially extended meshes (terrain tiles, long bridges, large buildings) where further node subdivision would become impractical or break asset management workflows. Node-level subdivision thus scales well up to a point, but mesh shaders remain the superior solution for scenes containing individually large meshes.

Missing Features

PasVulkan does not currently support the following features:

Summary

PasVulkan builds upon the GLTF format as its foundational model format, extending it to provide efficient and flexible management of 3D models within modern GPU-driven rendering pipelines.

The system is organized into three key layers:

  • TpvScene3D.TGroup: Holds shared model data such as vertex attributes, indices, materials, and textures. Materials and textures are globally deduplicated to save memory. The system supports up to 32,768 textures, limited by internal constraints. Short: A group is a GLTF model.

  • TpvScene3D.TGroup.TInstance: Contains instance-specific data like animation states, transformations, and dynamic vertex data. This data is preprocessed each frame and double-buffered, enabling correct motion vectors and compatibility with hardware ray tracing. The structure supports flexible bone and morph target management, allowing unique animations at the cost of increased memory and compute load.

  • TpvScene3D.TGroup.TInstance.TRenderInstance: Represents individual render occurrences of the same animated instance with varying root transforms and optional shader effects, without duplicating animation data.

PasVulkan uses a single-buffer architecture with bindless access, allowing shaders direct and efficient random access to mesh, material, and texture data. This reduces overhead and boosts performance, which is critical for modern techniques like forward+ rendering and hardware ray tracing.

Animations are no longer calculated dynamically in the vertex shader but are instead baked as static vertex data at the start of each frame by a compute shader. While this approach increases memory usage, it is necessary for hardware ray tracing compatibility and other modern rendering techniques. Developers must intelligently group animation states to reduce memory and preprocessing costs. This trade-off results in higher VRAM demands but ensures consistency, performance, and advanced rendering capabilities.

Overall, PasVulkan offers a well-balanced solution combining flexibility and performance while meeting the demands of modern graphics technologies.

Animation system

Introduction

PasVulkan's animation system is designed to efficiently handle complex animations in a simple way. It leverages the GLTF format as its base, extending it to support advanced features like bone animations, morph targets, and animated materials. It's a linear list of animations with weights (blended or additive animations), allowing for simple but flexible and efficient animation management. It's pretty much designed like threeJS's animation system, but with some differences to better fit the PasVulkan architecture and design principles.

Key Features

  1. Linear Animation List:

    The animation system uses a linear list of animations, where each animation is defined by a set of times and weights. This allows for efficient blending and additive animations, enabling smooth transitions between different animation states. No complex animation tree graphs or state machines are used, simplifying the animation management process. Instead, animations are simply defined as a list of times with associated weights, which can be blended together or applied additively to achieve the desired effect.

  2. Time based

    Animations are time-based rather than keyframe-based. This means they are defined in terms of continuous time progression instead of relying on discrete keyframes. Such an approach enables more fluid and continuous motion, as well as smoother blending between animations.

    Each animation progresses linearly over a defined duration, with a specific start time, end time, and total length. This structure allows for precise control over playback and enables smooth transitions between different animation states.

    The time-based nature of the system also makes it easier to synchronize animations with other subsystems in a game or application, such as physics or audio. This synchronization improves realism and contributes to a more cohesive user experience.

    This concept aligns with the animation model used in GLTF.

  3. Explicit animation time management:

    Animations are explicitly managed in time, allowing for precise control over playback, blending, and synchronization with other systems. The developer sets the current time of the animation, and the system updates the animation state accordingly. This is crucial for achieving realistic animations in real-time applications.

    Animation time can also be used as a state factor. For example, it allows controlling the hip angles of a character, where the animation time determines the hip rotation based on the current progress of the animation. This enables more complex animations that can be influenced by the developer, including procedural animations or those driven by game logic.

    In this way, the animation system supports more dynamic and responsive animations that can adapt to the current state of the game or application, rather than being strictly time-based. A representative example of this is character animations, where the hip angles can reflect the character’s movement speed, direction, and other contextual factors, resulting in more realistic and fluid motion.

    In addition to that, this gives the model designer more precise control over the fine-grained aspects of a model's dynamic movement possibilities by baking them into animations, which can then be controlled via animation time by the developer.

  4. Additive and Blended Animations:

    The system supports both additive and blended animations, allowing for complex animation compositions. Additive animations can be layered on top of base animations to introduce secondary motion or corrective adjustments. Blended animations enable smooth interpolation between different animation states, improving realism and fluidity in character movements.

  5. Most everything animatable:

    The system supports animating various properties, including:

    • Bone Transformations: Each bone in a skeleton can be animated independently, allowing for complex character animations.
    • Morph Targets (also known as blend shapes): Supports morph target animations for facial expressions and other deformations.
    • Material Properties: Materials can have animated properties, such as color, texture offsets, and other shader parameters.
    • Scene Graph Nodes: Allows for animating the transformations of scene graph nodes, enabling hierarchical animations where parent-child relationships are respected.
    • Camera Animations: Cameras can be animated to create dynamic viewpoints and transitions.
    • Light Animations: Lights can have animated properties, such as intensity, color, and position, allowing for dynamic lighting effects in the scene.
    • And much more: And even much store, as GLTF KHR_animation_pointer extension is supported.

Summary

PasVulkan's animation system is designed to be simple yet powerful, allowing for efficient management of complex animations. By using a linear list of animations with explicit time management, it provides flexibility and control over animation playback, blending, and synchronization with other systems. The support for additive and blended animations, along with the ability to animate various properties, makes it a versatile solution for modern rendering applications.

Global Illumination

Introduction

PasVulkan supports different realtime Global Illumination (GI) techniques. The purpose of Global Illumination (GI) is understood as an approach to provide realistic lighting effects in 3D scenes by simulating the indirect lighting that occurs when light bounces off surfaces.

Supported Techniques

PasVulkan currently supports the following Global Illumination techniques:

  1. Plain Image Based Lighting (IBL):

    • Uses precomputed environment maps to simulate indirect lighting.
    • Provides a simple and efficient way to achieve realistic lighting effects without complex calculations.
    • Suitable for static scenes or where high performance is required.
  2. Cascaded Radiance Hints:

    • Based on the concept of reflection maps, think as of shadow maps, but instead of just storing depth information, they store also albedo and normal information of the scene.
    • Discrete points (Voxel-grid) in camera space (“radiance hints”) are calculated from the reflection map, which serve as representatives for the surrounding luminance field. This technique makes it possible to simulate diffuse reflections, such as those caused by multiple bounces of light, in real time.
    • The radiance hints are sampled at discrete points in frustum voxel volumes, creating a radiance hint volume with cascaded hierarchical levels of detail (LOD) for different distances from the camera, which is then used to approximate indirect lighting.
    • Spherical harmonics are used to represent the radiance hints, allowing for efficient storage and interpolation of the lighting information.
    • Instead of continuously calculating the luminance field, “radiance hints” are stored at discrete points in space and interpolated. This technique is particularly useful for real-time calculation of global illumination in games or other interactive applications where fast calculations are required.
    • Secondary bounces are also supported, allowing for more realistic lighting effects.
    • The cascaded radiance hints are stored in a 3D textures, which allows for efficient smooth sampling and interpolation of the radiance hints in the shader.
  3. Cascaded Voxel Cone Tracing (CVCT):

    • An advanced technique that approximates indirect lighting using a voxel-based representation of the scene, divided into cascades of grid cells (voxels) at varying distances from the camera.
    • By tracing cones through this voxel grid, the system gathers lighting data that enables detailed and realistic global illumination.
    • Designed to support dynamic scenes and moving objects, making it well-suited for complex environments.
    • Capable of handling reflections and multiple bounces of indirect light, which enhances overall lighting realism.
    • The voxel grid is derived from the scene geometry and updated each frame to reflect any changes.
    • It is stored in a 3D texture, enabling efficient sampling and smooth interpolation within shaders.
    • The current implementation is visually broken and considered buggy.
    • However, the feature may eventually be removed due to the complexity and performance challenges involved in implementing it correctly and efficiently, especially since it relies on geometry shaders to voxelize the scene geometry. Geometry shaders are fundamentally unsuitable for real-time use and have always been discouraged, as they are slow and inefficient across all GPU generations. Other voxelization methods, such as compute shader-based approaches, are likewise impractical in real-time contexts, as they take too long to rebuild the voxel grid every frame, and as of now, no alternative voxelization methods are implemented in PasVulkan, although that said, the feature may be retained in the future if a suitable and efficient solution is found, and otherwise, the feature will be removed, just as simple as that.
  4. Ray Traced Global Illumination (RTGI):

    • It is planned to be implemented in the future, but it is not yet implemented. DDGI (Dynamic Diffuse Global Illumination) will be used as the starting point for the implementation, as it is a well-known and widely used technique for real-time ray traced global illumination. But however not in exactly the same way as DDGI, but rather in a more changed and extended way, as it will have more features and will be more flexible and efficient than DDGI in its original form. But let's see how it will turn out in the end.

Summary

PasVulkan supports various Global Illumination techniques to achieve realistic lighting effects in 3D scenes.


Pascube Src Pasvulkan Docs Scene3d Decals (`pascube_src/pasvulkan/docs/scene3d_decals.md`)

Scene3D Decal System Documentation

Table of Contents


Overview

The Scene3D decal system provides a high-performance, order-stable solution for projecting textures onto surfaces in real-time. Decals are commonly used for:

  • Bullet impacts - Bullet holes, scorch marks
  • Environmental details - Graffiti, posters, dirt, stains
  • Dynamic effects - Blood splatters, footprints, tire tracks
  • Gameplay indicators - Target markers, navigation arrows

Key Features

  • ✅ Forward-rendered integration - No extra geometry or render passes
  • ✅ Dual-mode rendering - Frustum cluster grid (for rasterization) and BVH skip-tree (for pathtracing/raytracing and similar uses)
  • ✅ Full PBR workflow - Modifies albedo, normals, metallic, roughness, occlusion, and specular
  • ✅ Order-stable rendering - Consistent overlap ordering, no flickering
  • ✅ Six blend modes - AlphaBlend, Multiply, Overlay, Additive, JustPBR, JustNormalMap
  • ✅ Lifetime management - Automatic expiration, smooth fade-out, and cleanup
  • ✅ Pass filtering - Selective application to mesh/planet/grass passes
  • ✅ Holder tracking - Associate decals with objects (planets, vehicles, etc.)
  • ✅ Rotation support - Arbitrary rotation around decal forward axis
  • ✅ PBR blend factor - Independent control over PBR property blending
  • ✅ Efficient deletion - Deferred compaction for stable ordering

Quick Start

Spawning a Simple Decal

pascal
var Decal:TpvScene3D.TDecal;
    HitOrientation:TpvQuaternion;
begin
 // Create orientation from surface normal
 HitOrientation:=TpvScene3D.TDecal.QuaternionFromNormal(HitNormal);
 
 // Spawn a bullet hole decal
 Decal:=Scene3D.SpawnDecal(
  HitPosition,                // TpvVector3D - World position
  HitOrientation,             // TpvQuaternion - Decal orientation
  0.0,                        // Rotation in radians around forward axis
  TpvVector2.Create(0.2,0.2), // Size in meters (width, height)
  BulletHoleAlbedoTexture,    // Texture index for color
  BulletHoleNormalTexture,    // Texture index for normal map
  BulletHoleORMTexture        // Texture index for ORM (occlusion/roughness/metallic)
 );
 
 // Decal is now active and will render automatically
end;

Creating a Timed Decal

pascal
// Create a decal that fades out after 10 seconds
Decal:=Scene3D.SpawnDecal(
 Position,Orientation,0.0,Size,
 AlbedoTex,NormalTex,ORMTex,0,0,
 TpvScene3D.TDecalBlendMode.AlphaBlend,
 1.0,    // PBR blend factor
 1.0,    // Full opacity
 1.0,    // Angle fade
 0.1,    // Edge fade
 10.0    // Lifetime: 10 seconds
);

Creating a Decal with Smooth Fadeout

pascal
// Create a decal that smoothly fades out over last 2 seconds
Decal:=Scene3D.SpawnDecal(
 Position,Orientation,0.0,Size,
 AlbedoTex,NormalTex,ORMTex,0,0,
 TpvScene3D.TDecalBlendMode.AlphaBlend,
 1.0,    // PBR blend factor
 1.0,    // Full opacity
 1.0,    // Angle fade
 0.1,    // Edge fade
 10.0,   // Lifetime: 10 seconds
 2.0     // FadeOut: 2 seconds (fades from t=8s to t=10s)
);

// Or fade over entire lifetime (spawn at full opacity, fade to nothing)
Decal:=Scene3D.SpawnDecal(
 Position,Orientation,0.0,Size,
 AlbedoTex,NormalTex,ORMTex,0,0,
 TpvScene3D.TDecalBlendMode.AlphaBlend,
 1.0,    // PBR blend factor
 1.0,    // Full opacity
 1.0,    // Angle fade
 0.1,    // Edge fade
 5.0,    // Lifetime: 5 seconds
 5.0     // FadeOut: 5 seconds (fades entire lifetime)
);

Custom Blend Modes

pascal
// Multiply mode - darkens surfaces (dirt, shadows)
Decal:=Scene3D.SpawnDecal(...,TpvScene3D.TDecalBlendMode.Multiply,...);

// Overlay mode - painted markings
Decal:=Scene3D.SpawnDecal(...,TpvScene3D.TDecalBlendMode.Overlay,...);

// Additive mode - glowing effects
Decal:=Scene3D.SpawnDecal(...,TpvScene3D.TDecalBlendMode.Additive,...);

// JustPBR mode - only modify metallic/roughness/occlusion, no albedo
Decal:=Scene3D.SpawnDecal(...,TpvScene3D.TDecalBlendMode.JustPBR,...);

// JustNormalMap mode - only apply normal map, no other changes
Decal:=Scene3D.SpawnDecal(...,TpvScene3D.TDecalBlendMode.JustNormalMap,...);

API Reference

TpvScene3D.SpawnDecal

Creates and spawns a new decal in the scene.

pascal
function SpawnDecal(
  const aPosition:TpvVector3D;
  const aOrientation:TpvQuaternion;
  const aRotation:TpvFloat=0.0;
  const aSize:TpvVector2;
  const aAlbedoTexture:TpvInt32=-1;
  const aNormalTexture:TpvInt32=-1;
  const aORMTexture:TpvInt32=-1;
  const aSpecularTexture:TpvInt32=-1;
  const aEmissiveTexture:TpvInt32=-1;
  const aBlendMode:TDecalBlendMode=TDecalBlendMode.AlphaBlend;
  const aPBRBlendFactor:TpvFloat=1.0;
  const aOpacity:TpvFloat=1.0;
  const aAngleFade:TpvFloat=1.0;
  const aEdgeFade:TpvFloat=0.1;
  const aLifetime:TpvDouble=-1.0;
  const aFadeOutTime:TpvDouble=0.0;
  const aPasses:TDecalPasses=[TDecalPass.Mesh,TDecalPass.Planet,TDecalPass.Grass];
  const aHolder:TObject=nil
):TDecal;

Parameters:

  • aPosition - World-space position (64-bit precision)
  • aOrientation - Decal orientation as quaternion (use TDecal.QuaternionFromNormal to create from surface normal)
  • aRotation - Rotation in radians around the decal's forward axis (0.0 = no rotation)
  • aSize - Width and height in world units (depth is automatically 0.5)
  • aAlbedoTexture - Texture index for base color (-1 = white/none)
  • aNormalTexture - Texture index for normal map (-1 = flat)
  • aORMTexture - Texture index for ORM map (-1 = defaults)
    • R channel: Occlusion
    • G channel: Roughness
    • B channel: Metallic
  • aSpecularTexture - Texture index for specular properties (-1 = defaults)
  • aEmissiveTexture - Texture index for emissive glow (-1 = none)
  • aBlendMode - How decal blends with surface material
    • AlphaBlend (0) - Standard alpha blending (default)
    • Multiply (1) - Darkens surface (dirt, grime, shadows)
    • Overlay (2) - Painted markings
    • Additive (3) - Glowing effects (lights, magic)
    • JustPBR (4) - Only modify PBR properties (metallic, roughness, occlusion, specular), no albedo
    • JustNormalMap (5) - Only apply normal map, no other material changes
  • aPBRBlendFactor - Independent blend factor for PBR material properties (0.0 to 1.0)
    • Controls how strongly metallic/roughness/occlusion/specular are blended
    • 1.0 = full PBR blending (default), 0.0 = no PBR change
  • aOpacity - Overall opacity multiplier (0.0 to 1.0)
  • aAngleFade - Power for angle-based fade (higher = sharper falloff)
    • 1.0 = linear falloff, 2.0 = quadratic, etc.
  • aEdgeFade - Distance from edge for soft fade (in UV space, 0.0 to 0.5)
  • aLifetime - Time in seconds before auto-removal (-1.0 = infinite)
  • aFadeOutTime - Duration of fade-out before expiration (0.0 = instant removal)
    • Smoothly fades opacity to zero over the last N seconds of lifetime
    • 0.0 = instant removal (default)
    • 1.0 = fade out over last 1 second
    • Can be equal to or greater than lifetime for full-lifetime fade
  • aPasses - Which render passes to apply decal to
  • aHolder - Object whose surface this decal is on (e.g. planet, mesh, vehicle). Used for bulk removal via RemoveDecalsForHolder.

Returns: TDecal instance that can be modified or manually removed

TDecal Properties

text
/* Detailed source-code truncated for AI context efficiency. */

TDecal Class Methods

pascal
class function QuaternionFromNormal(const aNormal:TpvVector3):TpvQuaternion; static;
// Creates a quaternion orientation from a surface normal vector.
// Useful for orienting decals to surfaces from raycasts.

procedure Update(const aInFlightFrameIndex:TpvSizeInt=-1);
// Updates internal state (matrix, AABB). Called automatically.

TpvScene3D.UpdateDecals

pascal
procedure UpdateDecals(const aDeltaTime:TpvDouble);

Updates all decal ages and removes expired decals. Call this once per frame with your delta time:

pascal
Scene3D.UpdateDecals(FrameDeltaTime);

Fix-Your-Timestep Interpolation (Optional)

For physics-style fixed timestep loops, the decal system supports store/interpolate to achieve smooth fade-outs independent of the render framerate.

Enabling Timestep Mode

pascal
Scene3D.DecalTimeSteps:=true;  // Enable store/interpolate mode (default: false)

When DecalTimeSteps is true:

  • UpdateDecals advances ages but does not remove expired decals (deferred to interpolation)
  • Fade-out opacity is computed from interpolated age, not raw age
  • You must call StoreDecalStates and InterpolateDecalStates yourself

API

pascal
procedure StoreDecalStates;
// Snapshots current age of all decals into fLastAge.
// Call BEFORE the fixed-timestep physics/logic update.

procedure InterpolateDecalStates(const aAlpha:TpvDouble);
// Interpolates age between stored (fLastAge) and current (fAge) using aAlpha.
// Computes fInterpolatedOpacity including fade-out.
// Removes decals whose interpolated age exceeds lifetime.
// Call AFTER the update loop, before rendering, with the interpolation alpha.

Usage Pattern

pascal
// Fixed timestep game loop
Scene3D.DecalTimeSteps:=true;

// Each frame:
Scene3D.StoreDecalStates;                    // 1. Snapshot ages

Accumulator:=Accumulator+FrameDeltaTime;     // 2. Accumulate frame time
while Accumulator>=FixedDeltaTime do begin
 Scene3D.UpdateDecals(FixedDeltaTime);       // 3. Advance ages at fixed rate
 Accumulator:=Accumulator-FixedDeltaTime;
end;

Alpha:=Accumulator/FixedDeltaTime;
Scene3D.InterpolateDecalStates(Alpha);       // 4. Interpolate for smooth rendering

Internal Fields

Field Type Description
fLastAge TpvDouble Stored age from previous timestep
fInterpolatedAge TpvDouble Interpolated age for current render frame
fInterpolatedOpacity TpvFloat Effective opacity including fade-out (used by GPU upload)

When DecalTimeSteps is false (default), fade-out opacity is computed directly from fAge during GPU buffer collection, and StoreDecalStates/InterpolateDecalStates are not needed.


Shader Integration

Rendering Modes

The decal system supports two rendering modes controlled by the LIGHTCLUSTERS define:

1. Frustum Cluster Grid Mode (for rasterization)

  • Compute shader pre-assigns decals to 3D clusters
  • O(D) lookup per fragment, where D = avg decals per cluster
  • Best for: Most use cases, scales well with many decals
  • Default: Enabled by #define LIGHTCLUSTERS (standard configuration)
glsl
#define LIGHTCLUSTERS
#include "decals.glsl"

2. BVH Skip-Tree Mode (for pathtracing/raytracing and similar uses)

  • Fragment shader traverses a hierarchical BVH tree
  • O(log N) lookup per fragment
  • Primary use: Future pathtracing/raytracing rendering passes
  • Available when LIGHTCLUSTERS is not defined
glsl
// BVH mode for pathtracing (when LIGHTCLUSTERS not defined)
#include "decals.glsl"

Shader Functions

applyDecals() - Full PBR

Modifies all material properties for physically-based rendering:

glsl
void applyDecals(
  inout vec4 baseColor,           // Albedo + alpha
  inout float metallic,
  inout float perceptualRoughness,
  inout float occlusion,
  inout vec3 F0Dielectric,        // Base reflectance
  inout vec3 F90Dielectric,       // Grazing reflectance
  inout float specularWeight,
  inout vec3 decalNormal,         // Accumulated normal (tangent space)
  inout float decalNormalBlend,   // Normal blend factor
  in vec3 worldPosition,
  in vec3 worldNormal,
  in vec3 viewSpacePosition,
  in vec3 baseIORF0Dielectric
);

applyDecalsUnlit() - Simple Color

Only modifies color for unlit materials:

glsl
void applyDecalsUnlit(
  inout vec3 color,
  in vec3 worldPosition,
  in vec3 worldNormal,
  in vec3 viewSpacePosition
);

Integration Example (mesh.frag)

glsl
#include "decals.glsl"

// After sampling base material, before lighting:
vec3 decalNormal = vec3(0.0, 0.0, 1.0);
float decalNormalBlend = 0.0;

applyDecals(
  baseColor, metallic, perceptualRoughness, occlusion,
  F0Dielectric, F90Dielectric, specularWeight,
  decalNormal, decalNormalBlend,
  inWorldSpacePosition, workNormal, inViewSpacePosition,
  baseIORF0Dielectric
);

// Later: Blend decal normals with material normals
if (decalNormalBlend > 0.0) {
  normalTangentSpace = blendNormals(normalTangentSpace, decalNormal, decalNormalBlend);
}

Performance Considerations

Memory Usage

Per decal in GPU memory:

  • TDecalItem: 128 bytes
    • WorldToDecalMatrix: 48 bytes (mat4x3)
    • UV/Blend params: 48 bytes
    • Texture indices: 32 bytes
  • BVH Node: ~32 bytes (when using skip-tree mode)
  • Total: ~160 bytes per decal

Example: 1000 active decals = ~160 KB GPU memory

CPU Performance

  • Spawning: O(log N) - AABB tree insertion
  • Deletion: O(1) - mark nil, deferred compaction
  • Compaction: O(N) - single pass, amortized over multiple deletions
  • Update: O(N) - age tracking per frame
  • Collection: O(N) - copy to GPU buffers

GPU Performance

BVH Mode

  • Per-fragment cost: O(log N) tree traversal, raytracing/pathtracing with coherent rays
  • Best case: Few decals, well-distributed
  • Worst case: Many overlapping decals at same position
  • Primary use: Optimized for future pathtracing rendering passes

Cluster Mode

  • Per-fragment cost: O(D) where D = decals in cluster
  • Compute overhead: One dispatch to assign decals to clusters
  • Best case: Many decals, clustered distribution
  • Worst case: All decals in few clusters

Optimization Tips

  1. Use appropriate blend modes

    • Multiply/Additive are cheaper than AlphaBlend (fewer material property updates)
  2. Set reasonable lifetimes

    • Avoid accumulating hundreds of permanent decals
    • Use shorter lifetimes for frequently spawned decals (footprints, particles)
    • Use FadeOutTime for smooth visual transitions instead of instant removal
  3. Use pass filtering

    • Only render decals in passes where they're visible
    • Example: Blood decals only on mesh pass, not grass
  4. Texture optimization

    • Use texture atlases to reduce binding overhead
    • Share textures between similar decals
  5. Clustering is default

    • LIGHTCLUSTERS is the standard configuration
    • BVH mode is reserved for future pathtracing features

Technical Architecture

Data Flow Overview

text
/* Detailed source-code truncated for AI context efficiency. */

Transform Pipeline

Decals use position + orientation + rotation to build the transform matrix:

  1. Creation

    pascal
    fPosition:TpvVector3D;         // 64-bit world position
    fOrientation:TpvQuaternion;    // Decal orientation
    fRotation:TpvFloat;            // Rotation around forward axis (radians)
    fMatrix:TpvMatrix4x4;          // Computed world-to-decal matrix
  2. Matrix computation (in TDecal.Update)

    • Build rotation matrix from orientation quaternion
    • Apply additional rotation around forward axis
    • Scale by decal size
    • Invert for world-to-decal transform
    • Apply origin offset for numerical stability
  3. GPU upload (32-bit)

    • Matrix stored as 3×vec4 (48 bytes), compatible with buffer references
    • Column-major layout for direct GLSL consumption
    • Origin offset applied for distant decals

Order Stability Mechanism

The decal system guarantees stable rendering order through deferred compaction:

  1. Deletion: O(1) - Set array entry to nil, set flag

    pascal
    fSceneInstance.fDecals.Items[fIndex]:=nil;
    fSceneInstance.fDecalNeedsCompaction:=true;
  2. Compaction: O(N) - Two-index algorithm in PrepareFrame()

    pascal
    WriteIndex:=0;
    for ReadIndex:=0 to fDecals.Count-1 do begin
     if assigned(fDecals[ReadIndex]) then begin
      if WriteIndex<>ReadIndex then begin
       fDecals[WriteIndex]:=fDecals[ReadIndex];
      end;
      inc(WriteIndex);
     end;
    end;
    fDecals.Count:=WriteIndex;
  3. Benefits:

    • Multiple deletions batched into single compaction
    • Original insertion order preserved
    • No flickering from order changes
    • Amortized O(1) deletion cost

Deep Technical Details

GPU Data Layout

TDecalItem Structure (128 bytes, 16-byte aligned)

glsl
struct Decal {
  // World to decal OBB transform (3x4 matrix as three vec4) - 48 bytes
  vec4 matrix0;
  vec4 matrix1;
  vec4 matrix2;

  vec4 uvScaleOffset;          // xy=scale, zw=offset - 16 bytes
  uvec4 blendParams;           // x=opacity(float bits), y=angleFade(float bits), z=edgeFade(float bits), w=pbrBlendFactor(float bits) - 16 bytes
  ivec4 textureIndices;        // albedo, normal, ORM, specular texture indices (-1 = none) - 16 bytes
  ivec4 textureIndices2;       // emissive, unused, unused, unused - 16 bytes
  uvec4 decalUpFlags;          // xyz=up direction for angle fade(float bits), w=flags(uint bits) - 16 bytes
};                             // Total: 128 bytes

Memory layout rationale:

  • Column-major mat4x3 avoids padding (3×vec4 = 48 bytes exactly)
  • All fields 16-byte aligned for optimal GPU cache access
  • Packed floats as uint bits to avoid padding between blend params
  • Total size is power-of-2-friendly (128 bytes)

Pass and Mode Flags Encoding

The flags field (decalUpFlags.w) encodes both the blend mode and pass filters:

pascal
// Blend mode in lower 4 bits (mask: $0000000F)
const DECAL_FLAG_MASK_MODE=(1 shl 4)-1;  // Bits 0-3: blend mode value (0-5)

// Pass flags in bits 4-6
const DECAL_FLAG_PASS_MESH=1 shl 4;     // $00000010
      DECAL_FLAG_PASS_PLANET=1 shl 5;   // $00000020
      DECAL_FLAG_PASS_GRASS=1 shl 6;    // $00000040

// Debug flags in upper bits
const DECAL_FLAG_DEBUG_DECAL=1 shl 30;  // $40000000
      DECAL_FLAG_DEBUG_CULL=1 shl 31;   // $80000000

Shader extraction:

glsl
const uint decalFlags = decal.decalUpFlags.w;
uint blendMode = decalFlags & DECAL_FLAG_MODE_MASK;  // 0-5
if ((decalFlags & DECAL_FLAG_PASS) != 0u) {
  // Apply decal in this pass
}
text
### Matrix Transformation Details

#### Why three vec4 instead of mat4x3/mat3x4?

Traditional mat4x4 (64 bytes) has a bottom row always [0,0,0,1] — 16 bytes wasted.

GLSL's native `mat3x4`/`mat4x3` types would save those 16 bytes in theory, but in practice they break 16-byte alignment rules in `std430` buffers and still round up to 64 bytes according to RenderDoc observations. This makes them no better than a full `mat4x4` in terms of actual memory consumption.

Instead, the matrix is stored as **three explicit `vec4`** (3×16 = 48 bytes), which:
- Maintains strict 16-byte alignment per row
- Actually saves 16 bytes (no padding to 64)
- Is fully compatible with buffer references
- Allows the shader to construct a `mat4` with an implicit `vec4(0,0,0,1)` fourth row

vec4 matrix0: [ Xx Xy Xz Tx ] 16 bytes
vec4 matrix1: [ Yx Yy Yz Ty ] 16 bytes
vec4 matrix2: [ Zx Zy Zz Tz ] 16 bytes

text
**Savings**: 16 bytes per decal vs mat4x4 (12.5% reduction), without the alignment pitfalls of native mat3x4/mat4x3.

#### Matrix Layout and Transposition

The matrix is stored as three `vec4` rows on the CPU/GPU buffer (row-major). In the shader, it is transposed at runtime to construct a column-major `mat4` for correct `mat4 * vec4` multiplication:

```glsl
// Shader reconstructs column-major mat4 by transposing the three stored rows:
mat4 worldToDecalMatrix = mat4(
  decal.matrix0.x, decal.matrix1.x, decal.matrix2.x, 0.0,  // Column 0
  decal.matrix0.y, decal.matrix1.y, decal.matrix2.y, 0.0,  // Column 1
  decal.matrix0.z, decal.matrix1.z, decal.matrix2.z, 0.0,  // Column 2
  decal.matrix0.w, decal.matrix1.w, decal.matrix2.w, 1.0   // Column 3 (translation)
);
// Equivalent to: transpose(mat4(matrix0, matrix1, matrix2, vec4(0,0,0,1)))

The three vec4 are stored row-major on the CPU side for natural matrix indexing, and the shader handles the transpose inline.

Origin Offset Technique

For numerical stability near the origin, we offset the decal transform:

pascal
// In TDecal.Update():
OriginOffset:=TpvVector3.InlineableCreate(
 fDecalToWorldMatrix.Translation.x,
 fDecalToWorldMatrix.Translation.y,
 fDecalToWorldMatrix.Translation.z
);

// Apply to 32-bit matrix
Matrix32.Translation:=Matrix32.Translation-OriginOffset;

This reduces floating-point precision loss for distant decals.

BVH Skip-Tree Implementation

The skip-tree is a flattened BVH optimized for GPU traversal:

Node Structure

glsl
struct DecalTreeNode {
  uvec4 aabbMinSkipCount;  // xyz=min bounds (as bits), w=skip count
  uvec4 aabbMaxUserData;   // xyz=max bounds (as bits), w=decal index or 0xFFFFFFFFu
};

Traversal Algorithm

glsl
uint nodeIndex = 0;
uint nodeCount = decalTreeNodes[0].aabbMinSkipCount.w;

while (nodeIndex < nodeCount) {
  DecalTreeNode node = decalTreeNodes[nodeIndex];
  
  vec3 aabbMin = uintBitsToFloat(node.aabbMinSkipCount.xyz);
  vec3 aabbMax = uintBitsToFloat(node.aabbMaxUserData.xyz);
  
  if (pointInAABB(worldPosition, aabbMin, aabbMax)) {
    if (node.aabbMaxUserData.w != 0xFFFFFFFFu) {
      // Leaf node - test this decal
      Decal decal = decals[node.aabbMaxUserData.w];
      // ... apply decal ...
    }
    nodeIndex++;  // Descend to child
  } else {
    // Skip this subtree
    nodeIndex += max(1u, node.aabbMinSkipCount.w);
  }
}

Skip count optimization: When a fragment is outside a node's AABB, skip the entire subtree (stored in aabbMinSkipCount.w).

Frustum Cluster Grid (for rasterization)

Cluster Grid Dimensions

glsl
Tile size: 64×64 pixels
Depth slices: 16 (log-scale distribution)
Total clusters = ceil(width/64) × ceil(height/64) × 16

Data Structure

glsl
// Per-cluster data (uvec4)
frustumClusterGridData[clusterIndex] = uvec4(
  lightIndexOffset,      // Start of light indices in index list
  countVisibleLights,    // Number of lights in this cluster
  decalIndexOffset,      // Start of decal indices in index list
  countVisibleDecals     // Number of decals in this cluster
);

// Global index list (shared for lights and decals)
frustumClusterGridIndexList[offset + i] = decalIndex;

Compute Shader Assignment (frustumclustergridassign.comp)

  1. Load decal meta-info into shared memory

    glsl
    shared LightDecalMetaInfo sharedDecalMetaInfos[8×8×8];
  2. Test AABB intersection in batches

    glsl
    for (uint batchIndex = 0; batchIndex < countDecalBatches; batchIndex++) {
      barrier();  // Sync shared memory
      
      for (uint decalIndex = 0; decalIndex < countThreads; decalIndex++) {
        if (clusterAABB intersects decalAABB) {
          visibleDecalIndices[countVisible++] = globalDecalIndex;
        }
      }
    }
  3. Write indices to global list

    glsl
    uint offset = atomicAdd(globalCounter, countVisible);
    for (uint i = 0; i < countVisible; i++) {
      globalIndexList[offset + i] = visibleDecalIndices[i];
    }

Fragment Shader Lookup

glsl
// Calculate cluster XYZ
uvec3 clusterXYZ = uvec3(
  gl_FragCoord.xy / 64,
  log2ZToSlice(viewSpacePosition.z)
);
uint clusterIndex = flatten3D(clusterXYZ);

// Read cluster data
uvec4 clusterData = frustumClusterGridData[clusterIndex];
uint decalOffset = clusterData.z;
uint decalCount = clusterData.w;

// Iterate only decals in this cluster
for (uint i = 0; i < decalCount; i++) {
  uint decalIndex = frustumClusterGridIndexList[decalOffset + i];
  Decal decal = decals[decalIndex];
  // ... apply decal ...
}

Blend Mode Mathematics

Alpha Blend (mode 0)

glsl
result = mix(base, decal, alpha);
// Equivalent to: result = base * (1 - alpha) + decal * alpha

Multiply (mode 1)

glsl
result = base * mix(vec3(1.0), decal, alpha);
// Darkens: decal acts as a mask (0=black, 1=preserve)

Overlay (mode 2)

glsl
vec3 overlayBlend(vec3 base, vec3 blend) {
  return mix(
    2.0 * base * blend,              // < 0.5: multiply
    1.0 - 2.0*(1.0-base)*(1.0-blend),// >= 0.5: screen
    step(0.5, base)
  );
}
result = mix(base, overlayBlend(base, decal), alpha);

Additive (mode 3)

glsl
result = base + decal * alpha;
// Brightens: useful for glowing effects

Normal Blending: Reoriented Normal Mapping (RNM)

Standard normal blending (mix()) doesn't preserve tangent space:

glsl
// WRONG: Simple lerp loses normal properties
vec3 blended = mix(baseNormal, decalNormal, alpha);  // Not unit length!

RNM preserves tangent space structure:

glsl
vec3 blendNormals(vec3 base, vec3 detail, float blend) {
  base = normalize(base);
  detail = normalize(detail);
  
  vec3 t = base + vec3(0.0, 0.0, 1.0);
  vec3 r = detail * vec3(-1.0, -1.0, 1.0);
  
  vec3 blended = t * dot(t, r) / t.z - r;
  return normalize(mix(base, blended, blend));
}

Why this works: RNM reorients the detail normal's tangent frame to align with the base normal before blending.

Angle Fade Implementation

Fade based on surface orientation relative to decal up direction:

glsl
float angleFade = clamp(
  dot(normalize(worldNormal), normalize(decalUp)),
  0.0, 1.0
);
angleFade = pow(angleFade, angleFadePower);
  • angleFadePower = 1.0: Linear falloff
  • angleFadePower = 2.0: Quadratic falloff (sharper)
  • angleFadePower = 4.0: Very sharp falloff (only on directly facing surfaces)

Edge Fade Implementation

Soft edges prevent hard cutoff at decal boundaries:

glsl
vec2 edgeDist = min(decalUV, 1.0 - decalUV);  // Distance from edges
float edgeFade = smoothstep(0.0, edgeFadeDistance, min(edgeDist.x, edgeDist.y));

/* Detailed source-code truncated for AI context efficiency. */

glsl
void applyDecals(
  inout vec4 baseColor,
  inout float metallic,
  inout float perceptualRoughness,
  inout float occlusion,
  inout vec3 F0Dielectric,
  inout vec3 F90Dielectric,
  inout float specularWeight,
  inout vec3 decalNormal,
  inout float decalNormalBlend,
  in vec3 worldPosition,
  in vec3 worldNormal,
  in vec3 viewSpacePosition,
  in vec3 baseIORF0Dielectric
) {
  // Initialize accumulation
  decalNormal = vec3(0.0, 0.0, 1.0);
  decalNormalBlend = 0.0;
  
  #if defined(LIGHTCLUSTERS)
    // Cluster-based lookup
    uvec3 clusterXYZ = calculateClusterXYZ(gl_FragCoord.xy, viewSpacePosition.z);
    uint clusterIndex = flattenClusterXYZ(clusterXYZ);
    uvec2 clusterDecalData = frustumClusterGridData[clusterIndex].zw;
    
    for (uint i = 0; i < clusterDecalData.y; i++) {
      uint decalIndex = frustumClusterGridIndexList[clusterDecalData.x + i];
      Decal decal = decals[decalIndex];
  #else
    // BVH skip-tree lookup
    uint nodeIndex = 0;
    uint nodeCount = decalTreeNodes[0].aabbMinSkipCount.w;
    
    while (nodeIndex < nodeCount) {
      DecalTreeNode node = decalTreeNodes[nodeIndex];
      if (testAABB(worldPosition, node)) {
        if (node.aabbMaxUserData.w != 0xFFFFFFFF) {
          Decal decal = decals[node.aabbMaxUserData.w];
  #endif
  
      // Check pass flags
      if ((decal.decalUpFlags.w & DECAL_FLAG_PASS) != 0u) {
        // Transform to decal space
        vec3 decalSpacePos = (decal.worldToDecalMatrix * vec4(worldPosition, 1.0)).xyz;
        
        // OBB test
        if (all(greaterThan(decalSpacePos + 0.5, vec3(0.0))) && 
            all(lessThan(decalSpacePos, vec3(0.5)))) {
          
          // Calculate UVs
          vec2 decalUV = decalSpacePos.xy + 0.5;
          decalUV = decalUV * decal.uvScaleOffset.xy + decal.uvScaleOffset.zw;
          
          // Fade calculations
          vec2 edgeDist = min(decalUV, 1.0 - decalUV) * 2.0;
          float edgeFade = smoothstep(0.0, uintBitsToFloat(decal.blendParams.z), 
                                      min(edgeDist.x, edgeDist.y));
          
          float angleFade = clamp(dot(normalize(worldNormal), 
                                      normalize(uintBitsToFloat(decal.decalUpFlags.xyz))), 
                                 0.0, 1.0);
          angleFade = pow(angleFade, uintBitsToFloat(decal.blendParams.y));
          
          // Sample textures
          vec4 decalAlbedo = sampleDecalTexture(decal.textureIndices.x, decalUV);
          vec3 decalNormalTS = sampleDecalNormal(decal.textureIndices.y, decalUV);
          vec3 decalORM = sampleDecalTexture(decal.textureIndices.z, decalUV).xyz;
          vec4 decalSpecular = sampleDecalTexture(decal.textureIndices.w, decalUV);
          
          // Calculate blend
          float blend = decalAlbedo.a * uintBitsToFloat(decal.blendParams.x) * 
                       angleFade * edgeFade;
          float pbrBlendFactor = uintBitsToFloat(decal.blendParams.w);
          
          // Apply based on blend mode (stored in lower 4 bits of flags)
          uint blendMode = decal.decalUpFlags.w & DECAL_FLAG_MODE_MASK;
          switch(blendMode) {
            case 0u: // AlphaBlend
            case 1u: // Multiply
            case 2u: // Overlay
            case 3u: // Additive
            case 4u: // JustPBR (no albedo change)
            case 5u: // JustNormalMap (no material changes)
            // ... apply blend with pbrBlendFactor for PBR properties
          }
          
          // Accumulate normals
          decalNormal = blendNormals(decalNormal, decalNormalTS, blend);
          decalNormalBlend = 1.0 - ((1.0 - decalNormalBlend) * (1.0 - blend));
        }
      }
      
  #if defined(LIGHTCLUSTERS)
    }
  #else
        }
        nodeIndex++;
      } else {
        nodeIndex += max(1u, node.aabbMinSkipCount.w);
      }
    }
  #endif
}

Pascube Src Pasvulkan Docs Scene3d Virtualinstances (`pascube_src/pasvulkan/docs/scene3d_virtualinstances.md`)

PasVulkan Scene3D Virtual Instance System

Overview

The Virtual Instance System provides automatic, intelligent management of Scene3D rendering resources through a sophisticated assignment algorithm. It eliminates manual resource management by automatically sharing GPU resources across similar instances while maintaining high rendering performance.

Key Features

  • Automatic Resource Sharing: Virtual instances automatically assigned to non-virtual instances based on similarity
  • GPU Instancing: Multiple similar virtual instances share GPU resources via hardware instancing
  • Temporal Coherence: Frame-to-frame stability prevents flickering/popping
  • Frustum Culling Integration: Only visible instances participate in assignment
  • Zero Configuration: Works out-of-the-box with sensible defaults
  • Thread-Safe: All operations protected by locks

Architecture

Three-Tier Instance Hierarchy

text
TGroup (Model Definition)
  └─ TVirtualInstanceManager (Assignment Engine)
       ├─ Non-Virtual Instances (GPU Resource Pool)
       │    ├─ Non-Virtual Instance #1 [Active/Inactive]
       │    │    └─ Preallocated Render Instances (Hardware Instancing Pool)
       │    │         ├─ Render Instance #1 [Active/Inactive]
       │    │         ├─ Render Instance #2 [Active/Inactive]
       │    │         └─ Render Instance #N [Active/Inactive]
       │    ├─ Non-Virtual Instance #2
       │    └─ Non-Virtual Instance #N
       └─ Virtual Instances (Lightweight User Objects)
            ├─ Virtual Instance #1 → Assigned to Non-Virtual #1
            ├─ Virtual Instance #2 → Assigned to Non-Virtual #1 (via render instance)
            └─ Virtual Instance #N → Unassigned (culled or no capacity)

Instance Types

1. Virtual Instances (User Creates)

  • Lightweight (~few hundred bytes)
  • Created by application: Group.CreateInstance(Virtual:=true)
  • Contains: Transform, animation state, scene index
  • Automatically registered with manager on creation
  • Automatically unregistered on destruction

2. Non-Virtual Instances (Manager Owns)

  • Heavy GPU resources (vertex buffers, joint matrices, etc.)
  • Created by manager in fixed pool
  • Never freed during gameplay, only recycled
  • Can be activated/deactivated as needed
  • Each can optionally have a render instance pool

3. Render Instances (Hardware Instancing)

  • Used when multiple similar instances share one non-virtual
  • Preallocated per non-virtual instance
  • Contains: Per-instance matrix, bounds
  • Enables GPU hardware instancing

Assignment Algorithm

Two-Step Greedy Assignment

The manager runs a sophisticated assignment algorithm each frame via UpdateAssignments():

Step 1: Primary Assignment (Dissimilar Preference)

pascal
for each Non-Virtual Instance do
  Find best DISSIMILAR virtual instance
  Assign virtual → non-virtual
  Copy state (matrix, animation, etc.)
  Activate non-virtual instance
end

Goal: Maximize diversity - each non-virtual gets a different animation state

Step 2: Instancing Assignment (Similar Preference)

pascal
for each remaining Virtual Instance do
  Find best SIMILAR non-virtual instance (already active)
  Assign virtual → non-virtual's render instance pool
  Share GPU resources via hardware instancing
end

Goal: Pack similar instances together for efficient instancing

Similarity Scoring

The default heuristic (DefaultAssignmentHeuristic) computes a score based on:

  1. Animation State Similarity (±10.0)

    • Compares animation times, blend factors
    • Higher score = more similar states
  2. Distance to Camera (-0.001 per unit)

    • Closer objects get slightly higher priority
    • Minimal impact on final score
  3. Temporal Coherence Bonus (+5.0)

    • If assigned to same non-virtual as last frame
    • Prevents flickering
  4. Switching Penalty (-1.0)

    • If previously assigned to different non-virtual
    • Encourages stability

Score Formula (Step 1 - Dissimilar):

pascal
Score = (-Similarity × 10.0) - (Distance × 0.001) + Temporal Bonus/Penalty

Score Formula (Step 2 - Similar):

pascal
Score = (Similarity × 10.0) - (Distance × 0.001) + Temporal Bonus/Penalty

State Similarity Computation

pascal
function ComputeStateSimilarity(const aInstanceA,aInstanceB:TInstance):TpvDouble;
var Index:TpvSizeInt;
    Similarity,TimeDifference:TpvDouble;
begin
 result:=0.0;
 
 // Scene must match
 if aInstanceA.Scene<>aInstanceB.Scene then begin
  exit;
 end;
 
 Similarity:=1.0;
 
 // Animation state comparison
 if aInstanceA.UseAnimationStates and aInstanceB.UseAnimationStates and
    (length(aInstanceA.AnimationStates)=length(aInstanceB.AnimationStates)) then begin
  for Index:=0 to length(aInstanceA.AnimationStates)-1 do begin
   // Time similarity (within 1 second = similar)
   TimeDifference:=abs(aInstanceA.AnimationStates[Index].Time-aInstanceB.AnimationStates[Index].Time);
   Similarity:=Similarity*(1.0/(1.0+TimeDifference));
   
   // Blend factor similarity
   Similarity:=Similarity*(1.0-abs(aInstanceA.AnimationStates[Index].Factor-aInstanceB.AnimationStates[Index].Factor));
  end;
 end;
 
 // Per-animation similarity
 if (length(aInstanceA.Animations)>0) and (length(aInstanceA.Animations)=length(aInstanceB.Animations)) then begin
  for Index:=0 to length(aInstanceA.Animations)-1 do begin
   Similarity:=Similarity*aInstanceA.Animations[Index].GetSimilarityTo(aInstanceB.Animations[Index]);
  end;
 end;
 
 result:=Similarity; // 0.0 (dissimilar) to 1.0 (identical)
end;

Basic Usage

1. Initialize Manager (One-Time Setup)

pascal
var Group:TpvScene3D.TGroup;
    Manager:TpvScene3D.TGroup.TVirtualInstanceManager;
begin
 // Load model
 Group:=LoadModelFromGLTF('models/character.gltf');
 
 // Create manager with capacity
 Manager:=Group.GetOrCreateVirtualInstanceManager(50,100);
 // Parameters: MaxNonVirtualInstances=50, MaxRenderInstancesPerNonVirtual=100
end;

Parameters:

  • MaximumNonVirtualInstances: How many different animation states you expect simultaneously
  • MaximumRenderInstancesPerNonVirtualInstance: How many similar objects can share GPU resources

Rule of Thumb:

  • Non-virtuals ≈ unique animations visible at once (e.g., 20-100)
  • Render instances ≈ max crowd density (e.g., 50-200)

2. Create Virtual Instances

pascal
var Character:TGameCharacter;
    VirtualInstance:TpvScene3D.TGroup.TInstance;
begin
 // Create virtual instance
 VirtualInstance:=Group.CreateInstance(false,true); // Headless=false, Virtual=true
 
 // Set properties
 VirtualInstance.ModelMatrix:=CharacterTransform;
 VirtualInstance.Scene:=0;  // Scene index
 VirtualInstance.Active:=true;  // Participate in culling/assignment
 
 // Setup animations
 VirtualInstance.Animations[0].Time:=1.5;
 VirtualInstance.Animations[0].Factor:=1.0;
 
 Character.VirtualInstance:=VirtualInstance;
end;

Automatic Registration: Virtual instances automatically register with the manager in AfterConstruction.

3. Update Loop

pascal
procedure TGame.Update(const aDeltaTime:TpvDouble);
var Character:TGameCharacter;
begin
 // Update all virtual instances (transforms, animations)
 for Character in fCharacters do begin
  Character.Update(aDeltaTime);
  Character.VirtualInstance.ModelMatrix:=Character.Transform;
 end;
 
 // Manager automatically handles assignment during rendering
 // No manual intervention needed!
end;

4. Trigger Assignment (Automatic)

Assignment happens automatically during rendering:

pascal
// In Scene3D.Prepare or similar rendering code
Manager.UpdateAssignments(InFlightFrameIndex);

You don't need to call this manually - the engine handles it!

5. Cleanup (Automatic)

pascal
// When character is destroyed:
VirtualInstance.Free;  // Automatically unregisters from manager

Advanced Features

Custom Assignment Heuristic

Override the default assignment logic:

pascal
function TMyGame.CustomAssignmentHeuristic(const aInstance:TInstance;
                                           const aTargetInstance:TInstance;
                                           const aCandidates:TInstances;
                                           const aInFlightFrameIndex:TpvSizeInt;
                                           const aCameraPosition:PpvVector3D;
                                           const aPreferDissimilar:Boolean;
                                           out aInstanceIndex:TpvSizeInt):TInstance;
begin
 // Your custom logic here
 // Must return best candidate from aCandidates
 result:=nil;
end;

// Set custom callback
Manager.CustomAssignmentCallback:=CustomAssignmentHeuristic;

Debug Visualization

Enable debug mode to track assignments:

pascal
var DebugInfoIndex:TpvSizeInt;
    DebugInfo:TpvScene3D.TGroup.TVirtualInstanceManager.TAssignmentDebugInfo;
begin
 Manager.DebugEnabled:=true;

 // After UpdateAssignments:
 for DebugInfoIndex:=0 to Manager.CountDebugInfos-1 do begin
  DebugInfo:=Manager.DebugInfos[DebugInfoIndex];
  
  writeln('Virtual: ',TpvPtrUInt(DebugInfo.VirtualInstance));
  writeln('→ NonVirtual: ',TpvPtrUInt(DebugInfo.AssignedNonVirtualInstance));
  writeln('Distance: ',DebugInfo.Distance:0:2);
  writeln('Priority: ',DebugInfo.Priority:0:2);
  writeln('StateHash: ',DebugInfo.StateHash);
 end;
end;

Animation State Structure

Virtual instances track animation state automatically:

pascal
// Animation state per virtual instance
VirtualInstance.Animations[0].Time:=AnimTime;
VirtualInstance.Animations[0].Factor:=BlendWeight;
VirtualInstance.Animations[0].Additive:=false;
VirtualInstance.Animations[0].Complete:=true;

// Manager compares these for similarity scoring

Game Integration Example

Character Class

pascal
type TGameCharacter=class
      private
       fGroup:TpvScene3D.TGroup;
       fVirtualInstance:TpvScene3D.TGroup.TInstance;
       fAnimationTime:TpvDouble;
       fAnimationState:TAnimationState;
      public
       constructor Create(const aGroup:TpvScene3D.TGroup);
       destructor Destroy; override;
       procedure Update(const aDeltaTime:TpvDouble);
     end;

constructor TGameCharacter.Create(const aGroup:TpvScene3D.TGroup);
begin
 inherited Create;
 fGroup:=aGroup;
 
 // Create virtual instance
 fVirtualInstance:=fGroup.CreateInstance(false,true); // Headless=false, Virtual=true
 
 fVirtualInstance.Active:=true;
 fVirtualInstance.Scene:=0;
 fAnimationTime:=0.0;
end;

destructor TGameCharacter.Destroy;
begin
 // Automatically unregisters from manager
 fVirtualInstance.Free;
 inherited Destroy;
end;

procedure TGameCharacter.Update(const aDeltaTime:TpvDouble);
begin
 // Update animation
 fAnimationTime:=fAnimationTime+aDeltaTime;
 
 // Update virtual instance
 fVirtualInstance.Animations[0].Time:=fAnimationTime;
 fVirtualInstance.Animations[0].Factor:=fAnimationState.BlendWeight;
 fVirtualInstance.ModelMatrix:=GetWorldTransform;
 
 // Manager automatically handles rest!
end;

Game Loop

pascal
procedure TGame.Initialize;
var CharacterIndex:TpvSizeInt;
begin
 // Load character model
 fCharacterGroup:=Scene3D.LoadGroup('character.gltf');
 
 // Initialize manager
 fCharacterGroup.GetOrCreateVirtualInstanceManager(50,100);
 
 // Spawn characters
 for CharacterIndex:=0 to 99 do begin
  fCharacters.Add(TGameCharacter.Create(fCharacterGroup));
 end;
end;

procedure TGame.Update;
var Character:TGameCharacter;
begin
 for Character in fCharacters do begin
  Character.Update(DeltaTime);
 end;
 
 // Assignment happens automatically during rendering
end;

Performance Characteristics

Memory Usage

Per Virtual Instance: ~200-500 bytes

  • Transform matrix (64 bytes)
  • Animation state (~100 bytes)
  • Bookkeeping (~100 bytes)

Per Non-Virtual Instance: ~5-50 MB (model dependent)

  • Animated vertex buffer
  • Joint matrices
  • Render instance pool

Total Example (100 characters, 10 unique animations):

  • 100 virtual instances: ~50 KB
  • 10 non-virtual instances: ~50-500 MB
  • Render instances: ~10-50 KB

CPU Performance

UpdateAssignments Complexity:

  • O(N × M) where N = non-virtuals, M = virtual instances
  • Typical: O(50 × 100) = 5,000 comparisons
  • With optimizations: <1ms on modern CPUs

Per-Frame Cost:

  • Frustum culling: ~0.1ms (100 instances)
  • Assignment: ~0.5ms (100 virtuals, 50 non-virtuals)
  • State update: ~0.2ms
  • Total: <1ms

GPU Performance

Instancing Benefits:

  • Draw calls: N (non-virtuals) instead of M (total objects)
  • Example: 100 characters → 10 draw calls (10x reduction)
  • Batch size: Up to 100 instances per draw call

Memory Transfers:

  • Only active non-virtual GPU buffers uploaded
  • Render instance matrices uploaded per-frame (~1KB each)

Migration Guide

From Manual Management

Before:

pascal
// Manual creation
Instance1:=Group.CreateInstance(false,false); // Virtual=false
Instance1.Animations[0].Time:=1.0;

Instance2:=Group.CreateInstance(false,false); // Virtual=false
Instance2.Animations[0].Time:=1.0;  // Duplicate GPU resources!

After:

pascal
// Initialize manager once
Group.GetOrCreateVirtualInstanceManager(50,100);

// Create virtual instances
Virtual1:=Group.CreateInstance(false,true); // Virtual=true
Virtual1.Animations[0].Time:=1.0;

Virtual2:=Group.CreateInstance(false,true); // Virtual=true
Virtual2.Animations[0].Time:=1.0;  // Shares GPU resources automatically!

From Old DynamicGroupManager

The old system required manual AcquireInstance / ReleaseInstance calls and explicit state keys. The new system:

  • ✅ No manual acquire/release
  • ✅ No state key management
  • ✅ Automatic registration on creation
  • ✅ Automatic unregistration on destruction
  • ✅ Animation state extracted automatically
  • ✅ Temporal coherence built-in

Implementation Details

Automatic Registration

Virtual instances register automatically in TInstance.AfterConstruction:

pascal
procedure TInstance.AfterConstruction;
begin
 if fVirtual and assigned(fGroup.fVirtualInstanceManager) then begin
  fGroup.fVirtualInstanceManager.fVirtualInstances.Add(self);
 end;
end;

Automatic Unregistration

Virtual instances unregister in TInstance.Remove:

pascal
procedure TInstance.Remove;
begin
 if fVirtual and assigned(fVirtualInstanceManager) then begin
  fVirtualInstanceManager.fVirtualInstances.Remove(self);
 end;
end;

Assignment State Tracking

Each virtual instance tracks its assignment:

pascal
type TInstance=class
      fAssignedNonVirtualInstance:TInstance;  // Current assignment
      fPreviousAssignedNonVirtualInstance:TInstance;  // Last frame (for temporal coherence)
     end;

Thread Safety

All public methods protected by TPasMPSpinLock:

pascal
procedure UpdateAssignments(const aInFlightFrameIndex:TpvSizeInt);
begin
 fLock.Acquire;
 try
  // Assignment logic
 finally
  fLock.Release;
 end;
end;

Best Practices

1. ⚠️ CRITICAL: Dependencies and Update Order Safety

Problem: Virtual Instance Properties Not in DAG Dependency Tracking

The TInstance.Update DAG system handles dependency ordering for regular instances (parent updates before child). Virtual instances are part of the DAG, but they're treated like non-virtual instances - the DAG system doesn't know about the virtual-to-non-virtual assignment relationship.

The Issue:

  • Non-virtual instance A gets updated by DAG
  • Non-virtual instance A has virtual instances B and C assigned to it
  • Virtual instances B and C will update later in unpredictable order
  • If B or C have dependencies on each other, ordering is wrong!

When MaxRenderInstanceCount = 0 (Direct Assignment):

text
❌ UNSAFE for virtual instances with dependencies/appendages!

Non-Virtual Instance X (updates first - via DAG)
├─ Virtual Instance A assigned → updates X.ModelMatrix (happens later, unpredictable order)
└─ Virtual Instance B assigned → updates X.ModelMatrix (happens later, unpredictable order)

Problem: If Virtual B depends on Virtual A (parent-child), but B updates before A:
- B reads stale/incorrect transform from A
- B writes incorrect ModelMatrix to Non-Virtual X
- Result: Incorrect positioning, visual glitches, race conditions

When MaxRenderInstanceCount > 0 (Render Instance Assignment):

text
✅ SAFE for virtual instances with dependencies/appendages!

Non-Virtual Instance X (updates first - via DAG)
├─ Virtual Instance A → Render Instance X[0] (writes own slot)
└─ Virtual Instance B → Render Instance X[1] (writes own slot)

Each virtual gets independent render instance slot
No race condition - separate memory locations
Virtual A updates Render Instance X[0].ModelMatrix
Virtual B updates Render Instance X[1].ModelMatrix
Parent-child computation happens in each virtual's own Update (before writing)
Unpredictable update order doesn't matter - isolated writes

Best Practice:

  • Simple standalone objects (trees, rocks, NPCs without attachments): MaxRenderInstanceCount = 0 OK
  • Objects with dependencies/appendages (characters with weapons, vehicles with parts): MaxRenderInstanceCount > 0 REQUIRED
  • Default recommendation: Always use MaxRenderInstanceCount > 0 unless you're certain instances are independent

Why Render Instances Are Safe:

  1. Each virtual instance writes to its own render instance slot
  2. No shared ModelMatrix between dependent virtuals
  3. Transform hierarchy resolved during virtual's Update (before writing to render instance)
  4. Unpredictable update order doesn't matter - isolated writes

Example:

pascal
// Character with attached weapon (dependency)
CharacterGroup.GetOrCreateVirtualInstanceManager(
 50,   // Non-virtual instances
 100   // ✅ Render instances > 0 for safety!
);

// Simple trees (no dependencies)
TreeGroup.GetOrCreateVirtualInstanceManager(
 20,   // Non-virtual instances  
 0     // ✅ Can use 0 - trees are independent
);

2. Right-Size Your Pools

pascal
var Manager:TpvScene3D.TGroup.TVirtualInstanceManager;
begin
 // Too small: Will run out of capacity
 Manager:=Group.GetOrCreateVirtualInstanceManager(5,10);  // ❌ Only 5 animations

 // Too large: Wastes GPU memory  
 Manager:=Group.GetOrCreateVirtualInstanceManager(1000,1000);  // ❌ Huge waste

 // Just right: Covers peak usage with headroom
 Manager:=Group.GetOrCreateVirtualInstanceManager(50,100);  // ✅ Perfect
end;

3. Keep Virtual Instances Active

pascal
// Only set Active=true for instances that should render
VirtualInstance.Active:=IsInWorld and IsVisible;

// Inactive instances don't participate in assignment
// (Saves CPU in UpdateAssignments)

4. Minimize State Changes

pascal
// Good: Smooth animation
Animations[0].Time:=Animations[0].Time+DeltaTime;  // ✅ Continuous, stays similar

// Bad: Random jumps
Animations[0].Time:=Random*10.0;  // ❌ Breaks similarity, causes reassignment

5. Use Scene Indices

pascal
// Separate by scene/level
VirtualInstance.Scene:=CurrentLevelIndex;

// Manager only matches instances with same scene

6. Profile Your Assignment Cost

pascal
var StartTime,AssignmentTime:TpvDouble;
begin
 StartTime:=GetTickCount;
 Manager.UpdateAssignments(FrameIndex);
 AssignmentTime:=GetTickCount-StartTime;

 if AssignmentTime>2.0 then begin
  writeln('WARNING: Assignment taking too long!');
 end;
end;

Troubleshooting

Problem: Objects Not Rendering

Cause: Virtual instance not assigned

Check:

pascal
begin
 if not Manager.IsVirtualInstanceAssigned(VirtualInstance) then begin
  writeln('Not assigned! Check pool capacity');
 end;
end;

Solution: Increase MaximumNonVirtualInstances

Problem: Flickering Between Frames

Cause: Poor temporal coherence (too much reassignment)

Check: Enable debug mode, watch Priority values

Solution:

  • Increase temporal bonus in custom heuristic
  • Reduce animation state granularity
  • Check for state "thrashing"

Problem: Low FPS Despite Instancing

Cause: Too many unique animation states (defeats instancing)

Check: Count active non-virtual instances

Solution:

  • Quantize animation times (round to 0.1s)
  • Reduce animation blend precision
  • Use fewer unique animations

Problem: Memory Usage Too High

Cause: Too many non-virtual instances allocated

Check: MaximumNonVirtualInstances parameter

Solution: Reduce pool size to what's actually needed

Technical Notes

Why Virtual Instances?

Traditional approach: Each game object owns a heavy TInstance

  • 100 objects = 100 × 50MB = 5 GB GPU memory
  • Each with duplicate GPU buffers
  • No sharing possible

Virtual instance approach: Game objects own lightweight virtual instances

  • 100 virtual instances = 100 × 500 bytes = 50 KB
  • Manager shares 10 non-virtual instances = 10 × 50MB = 500 MB
  • 10x memory reduction!

GPU Instancing Details

When multiple virtual instances share a non-virtual:

  1. Non-virtual uploads animated vertices once
  2. Each virtual's render instance uploads just a matrix (~64 bytes)
  3. GPU hardware instancing duplicates geometry
  4. One draw call renders all similar instances

This is why render instance pool size matters - it's the max batch size for instancing.

State Similarity Philosophy

The system treats animation as continuous state space:

  • Similar times → similar poses → can share GPU vertex buffer
  • Dissimilar times → different poses → need separate buffers

This is why smooth animations work best - neighboring frames share resources naturally.

Summary

The Virtual Instance System provides:

✅ Automatic resource management - no manual acquire/release
✅ Efficient GPU memory usage - sharing via similarity
✅ Scalable to hundreds of instances - O(N×M) assignment
✅ Stable frame-to-frame - temporal coherence built-in
✅ Flexible - custom heuristics for special cases
✅ Thread-safe - concurrent updates supported

Perfect for games with many animated characters/objects like crowd simulations, RTS units, or MMO players!


Pascube Src Pasvulkan Docs Skybox Temporal Reprojection Caching (`pascube_src/pasvulkan/docs/skybox_temporal_reprojection_caching.md`)

Skybox Temporal Reprojection Caching

Overview

The skybox temporal reprojection caching system is an optimization for expensive procedural sky rendering (primarily the getStarlight() function for starfield rendering). Instead of computing the full starlight calculation for every pixel every frame, we cache the results and reuse them across frames via reprojection.

How It Works

Core Concept

  1. Render to history buffer: Each frame, the skybox shader writes its computed sky color to a per-frame history image (fHistoryImages[aInFlightFrameIndex]).

  2. Reproject from previous frame: Before computing new values, the shader attempts to reproject the current pixel's world direction into the previous frame's clip space to sample the cached result.

  3. Selective recomputation: Only pixels that fail reprojection (moved off-screen, hidden, or stochastically selected for refresh) are fully recomputed.

Shader Flow (Fragment Shader)

text
1. Get current world direction from vertex shader
2. Compute previous frame's clip-space position (passed from vertex shader)
3. Convert to UV coordinates in previous frame's history buffer
4. Check if UV is valid (within [0,1] range)
5. If valid:
   - Sample previous frame's cached color
   - Check if pixel was written (alpha != 0 for RGBA16F, or non-zero for RGB9E5)
   - If valid cached value exists, use it (with optional stochastic refresh)
6. If invalid or needs refresh:
   - Compute fresh starlight value
   - Store to current frame's history buffer

Vertex Shader Changes

The cached variant of the vertex shader (skybox_cached_vert.spv) computes and outputs an additional varying:

  • outPreviousClipSpacePosition: The vertex position transformed using the previous frame's view/projection matrix and previous frame's skybox orientation quaternion

This allows the fragment shader to know where each pixel "was" in the previous frame.

Push Constants

The system uses additional push constant fields for the cached mode:

Field Type Purpose
currentOrientation vec4 Current frame's skybox orientation (quaternion)
previousOrientation vec4 Previous frame's skybox orientation (quaternion)
countAllViews uint Total view count, used to index previous frame's views
frameIndex uint Frame counter for stochastic refresh patterns

History Buffer Format

Two formats are supported, selected automatically based on GPU capabilities:

  1. RGB9E5 (preferred):

    • Uses VK_FORMAT_E5B9G9R9_UFLOAT_PACK32 with R32_UINT alias for imageStore
    • More memory efficient (4 bytes/pixel)
    • Zero value used as "unwritten pixel" sentinel
    • Requires GPU support for RGB9E5 storage images
  2. RGBA16F (fallback):

    • Uses VK_FORMAT_R16G16B16A16_SFLOAT
    • Alpha channel = 0.0 indicates unwritten pixel
    • Alpha channel = 1.0 indicates valid cached value
    • 8 bytes/pixel

Image Layout Tracking

The system maintains explicit layout tracking via fHistoryImageLayouts[] array to handle the complex transitions:

Per-Frame Transitions (in ForwardComputePass)

text
Frame N:
  1. Current image [N]: Any → TRANSFER_DST → clear → GENERAL (for shader write)
  2. Previous image [N-1]: Any → SHADER_READ_ONLY (for shader read)

The system tracks layouts to set correct srcAccessMask and oldLayout for each transition:

Previous Layout srcAccessMask
SHADER_READ_ONLY_OPTIMAL VK_ACCESS_SHADER_READ_BIT
GENERAL VK_ACCESS_SHADER_READ_BIT | VK_ACCESS_SHADER_WRITE_BIT
UNDEFINED 0

When Cache Is Invalidated

The cache is partially invalidated (stochastic refresh) continuously, but fully invalidated in these cases:

  1. Resolution change: When fWidth, fHeight, or fCountSurfaceViews change, all history images are recreated.

  2. First frame: No previous history exists, all pixels must be computed fresh.

  3. Large orientation change: If PreviousOrientation.DistanceTo(CurrentOrientation) > 0.1, the previous orientation is snapped to current (forcing fresh computation for all pixels, as reprojection would fail anyway).

Reprojection Validation

Before using a cached value, the shader performs several validation checks:

1. Screen Bounds Check

glsl
vec2 margin = 1.0 / vec2(screenSize);
bool isValid = all(greaterThanEqual(previousUV, margin)) && 
               all(lessThanEqual(previousUV, vec2(1.0) - margin));
  • Checks if the reprojected UV is within the screen (with 1-pixel margin to avoid edge artifacts)
  • Pixels that were off-screen in the previous frame are recomputed

2. Behind Camera Check

glsl
isValid = isValid && (previousClip.w > 0.0);
  • For skybox direction vectors, clip.w corresponds to the view-space Z direction
  • Positive w means the direction was forward-facing in the previous frame
  • Rejects directions that were behind the camera

3. Motion Vector Rejection

glsl
vec2 motionVector = abs(previousUV - currentUV);
bool tooMuchMotion = any(greaterThan(motionVector, vec2(0.15)));
isValid = isValid && !tooMuchMotion;
  • Rejects reprojection if the pixel moved more than 15% of screen size
  • Prevents feedback loop artifacts during rapid camera rotation
  • Large motion indicates the reprojection is unreliable (interpolation errors accumulate)

Why 15%?

The 15% threshold balances two concerns:

  • Too low: Rejects valid reprojections during normal camera movement, wasting computation
  • Too high: Allows unreliable reprojections that may cause visible artifacts or ghosting

At 60 FPS with smooth camera rotation, 15% per frame corresponds to roughly 9 full rotations per second before rejection kicks in.

Stochastic Refresh

To prevent the cache from becoming stale and to avoid floating-point precision drift over time, pixels are stochastically selected for forced recomputation:

glsl
uvec2 pixelCoord = uvec2(currentUV * vec2(screenSize));
uint refreshPattern = (pixelCoord.x ^ pixelCoord.y ^ pushConstants.frameIndex) & 0x3fu;
bool forceRefresh = (refreshPattern == 0u);

How It Works

  1. XOR pattern: Combines pixel X, pixel Y, and frame index with XOR
  2. Mask with 0x3F (63): Limits the pattern to 6 bits (values 0-63)
  3. Force refresh when zero: Triggers recomputation when pattern equals 0

Result

  • Each pixel is forced to recompute approximately every 64 frames
  • The XOR pattern ensures neighboring pixels refresh at different frames (no visible "block" artifacts)
  • Over 64 frames, every pixel will have been refreshed at least once
  • At any given frame, roughly 1/64th (1.56%) of pixels are forcibly recomputed

Why This Matters

Even with perfect reprojection, repeatedly sampling and rewriting cached values can accumulate floating-point errors. The stochastic refresh ensures:

  • No pixel relies on indefinitely old cached data
  • Animated/time-varying effects eventually update everywhere
  • Numerical stability is maintained over long sessions

Hidden Pixel Detection

When a pixel is reprojected but the sampled history value is invalid (the pixel wasn't visible in the previous frame), it must be detected and recomputed.

Sentinel Values

The history buffer is cleared to zero before each frame. The shader detects unwritten pixels by checking for sentinel values:

RGBA16F format:

glsl
if(historySample.a < 0.5){
  // Pixel was not rendered in previous frame, recompute
}
  • Alpha = 0.0 means unwritten (cleared state)
  • Alpha = 1.0 means valid cached value

RGB9E5 format:

glsl
if(all(equal(historySample.rgb, vec3(0.0)))){
  // Pixel was not rendered in previous frame, recompute  
}
  • Pure black (0,0,0) is the sentinel
  • This works because pure black is physically impossible for a starfield sky

Debug Mode

When SKYBOX_CACHED_REPROJECTION_DEBUG is defined, cached pixels have their red/green channels zeroed to visualize cache usage (cached pixels appear blue/dark, freshly computed pixels appear normal).

When Caching Is Effectively Used

Important: The temporal reprojection caching is only effectively active in realtime starlight mode (pushConstants.mode == 1).

glsl
switch(pushConstants.mode){
  case 1u:{
    // Realtime starlight - CACHING IS EFFECTIVE HERE
    // Uses reprojectStarlight() to reuse previous frame's expensive computation
    ...
  }
  default:{
    // Cube map mode - CACHING FULLY INACTIVE
    // Simply reads from cubemap texture (already fast)
    // No reprojection, no history read/write
    ...
  }
}

Why?

  • Starlight mode: The getStarlight() function is computationally expensive (procedural star generation, atmospheric scattering, etc.). Caching provides significant speedup.
  • Cubemap mode: Reading from a cubemap texture is already very fast. The reprojection overhead would exceed any savings, so caching is completely bypassed.

Descriptor Set Bindings (Cached Mode)

Binding Type Content
0 Uniform Buffer View matrices (current + previous frames)
1 Combined Image Sampler Sky cubemap texture
2 Combined Image Sampler Previous frame's history (for reading)
3 Storage Image Current frame's history (for writing)

Performance Considerations

  • GPU Memory: 2 history buffers (one per in-flight frame) at screen resolution
  • Bandwidth: Reading previous + writing current history per pixel
  • ALU: Significant reduction when cache hits (skips expensive starlight computation)
  • Best case: Static camera = nearly 100% cache hits
  • Worst case: Rapid rotation = mostly cache misses (but still writes to history for next frame)

Files Involved

Pascal Source

  • PasVulkan.Scene3D.Renderer.SkyBox.pas - Main Pascal implementation

Shader Sources

  • skybox.vert - Vertex shader source (handles both modes via preprocessor)
  • skybox.frag - Fragment shader source (handles both modes via preprocessor)
  • skybox.glsl - Shared definitions and push constants

Compiled Shader Variants (Vertex)

  • skybox_vert.spv - Standard vertex shader (no reprojection)
  • skybox_cached_vert.spv - Cached variant with previous clip-space position output

Compiled Shader Variants (Fragment)

  • skybox_frag.spv - Standard fragment shader (no caching)
  • skybox_cached_rgba16f_frag.spv - Cached variant using RGBA16F history buffer
  • skybox_cached_rgb9e5_frag.spv - Cached variant using RGB9E5 history buffer

Enabling/Disabling

The caching is controlled by the SkyBoxCaching property on TpvScene3D:

pascal
Scene3D.SkyBoxCaching := true;  // Enable caching
Scene3D.SkyBoxCaching := false; // Disable caching (default)

This property is read by TpvScene3DRendererPassesForwardRenderPass when creating the skybox renderer and passed to TpvScene3DRendererSkyBox.Create() as the aCached parameter.

Note: The skybox in PasVulkan.Scene3D.Renderer.Passes.ReflectionProbeRenderPass.pas always uses non-cached mode for simplicity, as reflection probes are rendered infrequently and at lower resolution.


Pascube Src Pasvulkan Docs Vectorpath (`pascube_src/pasvulkan/docs/vectorpath.md`)

PasVulkan Vector Path Rendering

Overview

This document provides technical documentation for PasVulkan's vector path rendering capabilities, covering both the existing SDF-based approach and the work-in-progress Pathfinder-like on-GPU vector shape rendering feature.

PasVulkan provides multiple rendering algorithms for vector graphics:

  1. SDF-Based Rendering (Current, Production) - Using TpvSignedDistanceField2D for font rendering and pre-rasterized vector shapes
  2. CPU-Tessellated Direct Rendering (Current, Production) - CPU tessellates vector paths into triangles with SDF-based edge anti-aliasing in fragment shader, optimized for opaque shapes where overdraw is minimal
  3. Coverage-Mask-then-Cover Approach (Current, Production) - Two-pass transparent shape rendering (four passes including barriers) using a coverage buffer to handle overlapping transparent shapes correctly
  4. Direct Spatial Grid GPU Vector Rendering (WIP) - Direct GPU-based vector path rasterization using TpvVectorPathGPUShape

These algorithms are complementary rendering modes, allowing users to choose the best approach for their specific use case.


1. Architecture Overview

1.1 Core Types and Structures

Host-Side (Pascal)

Basic Vector Types:

  • TpvVectorPathVector - 2D vector with double precision (x, y) - with automatic implicit and explicit conversion to/from TpvVector2 (single precision) and TpvVector2D (double precision)
  • TpvVectorPathVectors - Dynamic array of vectors
  • TpvVectorPathBoundingBox - AABB with MinMax[0..1] structure

Segment Types:

  • TpvVectorPathSegment (abstract base class)
  • TpvVectorPathSegmentLine - Linear segments
  • TpvVectorPathSegmentQuadraticCurve - Quadratic Bézier curves
  • TpvVectorPathSegmentCubicCurve - Cubic Bézier curves (converted to quadratic for GPU rendering to keep complexity manageable)
  • TpvVectorPathSegmentMetaWindingSettingLine - Special winding control segments

Shape Representation:

  • TpvVectorPathContour - Collection of connected segments (open or closed)
  • TpvVectorPathShape - Collection of contours with fill rule (EvenOdd or NonZero)
  • TpvVectorPath - Command-based path builder (SVG-like interface with all SVG path commands)

GPU Shape Acceleration:

  • TpvVectorPathGPUShape - Main GPU-accelerated shape container
  • TpvVectorPathGPUShape.TGridCell - Spatial subdivision cell

GPU-Side (GLSL)

GPU Data Structures (defined in both Pascal and GLSL):

glsl
// Segment data: 32 bytes per segment
struct VectorPathGPUSegment {
  uvec4 typeWindingPoint0;  // [Type, Winding, Point0.x, Point0.y] as uints
  vec4 point1Point2;         // [Point1.x, Point1.y, Point2.x, Point2.y]
};

// Indirect segment: 4 bytes
#define VectorPathGPUIndirectSegment uint  // Index into segment buffer

// Grid cell: 8 bytes
#define VectorPathGPUGridCell uvec2  // [startIndex, count]

// Shape metadata: 32 bytes
struct VectorPathGPUShape {
  vec4 minMax;                        // [min.x, min.y, max.x, max.y]
  uvec4 flagsStartGridCellIndexGridSize;  // [flags, startGridCell, gridSizeX, gridSizeY]
};

Segment Type Constants:

  • TypeUnknown = 0 - Invalid/uninitialized
  • TypeLine = 1 - Line segment
  • TypeQuadraticCurve = 2 - Quadratic Bézier curve
  • TypeMetaWindingSettingLine = 3 - Winding initialization segment

Flags:

  • Bit 0: Fill rule (1 = Even-Odd, 0 = Non-Zero)

2. Rendering Approaches

2.1 SDF-Based Rendering (Production)

Used by: Font rendering (TpvFont, and TpvFont is used by TpvTrueTypeFont as well for vector glyph rendering of TrueType and OpenType fonts), pre-processed shapes

Location: PasVulkan.SignedDistanceField2D.pas, PasVulkan.Font.pas

Approach:

  • Pre-compute signed distance field textures from vector shapes
  • Supports SDF, SSAASDF (4x multisampled 4-rook/RGSS SDF with 4 samples per pixel per RGBA channel), MSDF (Multi-channel SDF), and MTSDF variants
  • GPU fragment shader samples pre-computed texture
  • Uses linearstep() for smooth anti-aliasing, not smoothstep, needed for correct SDF evaluation on a linear color space (not gamma-corrected one!)

Advantages:

  • Very fast at runtime (single texture lookup)
  • High quality anti-aliasing
  • Efficient for repeated rendering (glyphs)

Disadvantages:

  • Requires pre-processing step
  • Memory overhead for texture storage
  • Limited resolution scalability

2.2 CPU-Tessellated Direct Rendering (Production)

Used by: Default Canvas path rendering (when Coverage mode is disabled, fTransparentShapes=false) in TpvCanvas

Location: PasVulkan.Canvas.pas (TpvCanvasShape, TpvCanvasPath)

Approach:

  • CPU tessellates arbitrary vector paths into triangles (TpvCanvasShape.FillFromPath / StrokeFromPath)
  • CPU-side triangulation supports full fill rules (Non-Zero, Even-Odd)
  • Curves are adaptively flattened to line segments based on tessellation tolerance
  • Resulting triangles encode signed distance field evaluation in vertex metadata
  • Fragment shader evaluates analytical SDFs for smooth anti-aliasing at triangle edges
  • Single-pass rendering with standard alpha blending
  • Automatic batching of geometry into indexed triangle lists

Path Processing Flow:

text
TpvCanvasPath (MoveTo, LineTo, Curves, etc.)
       ↓
TpvCanvasShape.FillFromPath() / StrokeFromPath()
       ↓
CPU tessellation:
  ├─ Flatten curves to line segments (adaptive tolerance)
  ├─ Build segment list with BVH for intersection tests
  ├─ Triangulate using scanline algorithm
  ├─ Encode SDF parameters in vertex MetaInfo
  └─ Generate indexed triangle mesh
       ↓
DrawShape() → GPU rendering with SDF anti-aliasing

Fragment Shader Distance Functions:

  • pcvvaomLineEdge (0x01) - Line segments with thickness (stroking)
  • pcvvaomRoundLineCapCircle (0x02) - Rounded line caps
  • pcvvaomRoundLine (0x03) - Rounded lines (polygon edges)
  • pcvvaomCircle (0x04) - Circles (filled primitives)
  • pcvvaomEllipse (0x05) - Ellipses
  • pcvvaomRectangle (0x06) - Axis-aligned rectangles
  • pcvvaomRoundedRectangle (0x07) - Rounded rectangles
  • pcvvaomCircleArcRingSegment (0x08) - Arc ring segments

GUI Element Mode:

Canvas supports a specialized GUI element rendering mode via DrawGUIElement() with shader define GUI_ELEMENTS:

  • Theme-aware procedural UI elements (windows, buttons, panels, etc.)
  • Focused/unfocused state visualization
  • Complex SDF combinations (rounded rectangles, drop shadows, gradients)
  • Configurable via uniform buffer colors and parameters
  • Supports both opaque and transparent rendering

GUI Element Types:

  • GUI_ELEMENT_WINDOW_HEADER - Window title bars with gradients
  • GUI_ELEMENT_WINDOW_FILL - Window body backgrounds
  • GUI_ELEMENT_WINDOW_DROPSHADOW - Drop shadow effects
  • GUI_ELEMENT_BUTTON_* - Buttons (unfocused, focused, pushed, disabled states)
  • GUI_ELEMENT_PANEL_* - Various panel types
  • GUI_ELEMENT_CHECKBOX_* - Checkboxes and radio buttons
  • GUI_ELEMENT_SCROLLBAR_* - Scrollbar components
  • GUI_ELEMENT_TAB_BUTTON_* - Chrome-style tab buttons
  • GUI_ELEMENT_SLIDER_* - Slider tracks and knobs
  • GUI_ELEMENT_PROGRESSBAR_* - Progress bar components
  • And many more specialized UI elements

GUI SDF Helper Functions:

  • sdRoundedRect() - Rounded rectangle distance
  • sdTabButton() - Chrome-style angled tab shape
  • sdTriangle() - Triangle distance with barycentric coords
  • Color space conversions (RGB↔HSV) for dynamic theming

Shape Caching for Performance:

To avoid CPU tessellation/triangulation overhead on repeated rendering, shapes can be pre-tessellated and cached:

pascal
// Cache the tessellated shape once
var CachedFillShape:TpvCanvasShape;
begin
 CachedFillShape:=Canvas.GetFillShape;  // Tessellate once
 try
  // Render multiple times without re-tessellation
  Canvas.DrawShape(CachedFillShape);
  // ... change transforms, colors, etc.
  Canvas.DrawShape(CachedFillShape);
 finally
  CachedFillShape.Free;
 end;
end;

Shape Caching Methods:

  • GetFillShape() - Returns cached tessellation of current path as filled shape
  • GetStrokeShape() - Returns cached tessellation of current path as stroked shape
  • DrawShape(aShape) - Renders a pre-tessellated shape directly

Benefits:

  • Amortize tessellation cost across multiple frames
  • Render same shape with different transforms/colors efficiently
  • Useful for animated or repeatedly drawn elements
  • No re-tessellation when only visual properties change

Advantages:

  • Supports arbitrary vector paths (full SVG-like path API)
  • CPU tessellation handles complex fill rules correctly
  • Automatic batching reduces draw calls
  • SDF-based anti-aliasing provides smooth edges
  • No buffer uploads beyond standard vertex/index data
  • Works with standard blending
  • Shape caching eliminates re-tessellation overhead for repeated rendering
  • Efficient rendering of same shape with different transforms/colors via cached shapes

Disadvantages:

  • Overdraw artifacts with transparent overlapping shapes (alpha blending issues)
  • CPU tessellation cost for complex paths
  • Manual Z-ordering required for proper transparency
  • Tessellation granularity affects quality vs performance
  • Higher vertex count for curved paths

Best Use Cases:

  • Opaque vector graphics (UI elements, diagrams)
  • Simple to moderately complex paths without heavy overlap
  • Scenarios where CPU tessellation cost is acceptable
  • Applications needing full path API support

When to Avoid:

  • Complex transparent overlapping shapes → Use Coverage-Mask-then-Cover
  • Very large, complex paths requiring spatial optimization → Use Direct Spatial Grid GPU Vector Rendering
  • Scenes with many small, repeated shapes → Use SDF pre-baking

2.3 Coverage-Mask-then-Cover (Production)

Used by: Transparent shape rendering in Canvas

Location: canvas.frag with COVERAGE_MASK_PASS and COVERAGE_COVER_PASS defines

Shader Defines:

  • COVERAGE_MASK_PASS - First pass: write coverage
  • COVERAGE_COVER_PASS - Second pass: resolve and composite

GPU Resources:

  • Coverage buffer: R32_UINT format image (set 1, binding 0)
  • Format: [24-bit stamp | 8-bit coverage]

Note on Terminology: In this context, "pass" refers to a logical stage of the algorithm. The barrier stages are synchronization points between render passes, not rendering passes themselves. Two-pass rendering (Mask + Cover) with two synchronization barriers (one after mask, one after cover), so four logical stages total, hence "Four-Pass Algorithm".

Four-Pass Algorithm:

Pass 1 - Mask (Coverage Writing):

glsl
uint shapeStamp = pushConstants.data[7].y;
uint coverage8 = uint((clamp(color.a, 0.0, 1.0) * 255.0) + 0.5);
uint packed = (shapeStamp << 8) | coverage8;
imageAtomicMax(uCoverageBuffer, pixelPosition, packed);

where the highest 24 bits are the shape stamp (unique per shape group) and the lowest 8 bits are the coverage value (0-255), and where the highest value wins (atomic max) for the current pixel.

Pass 2 - MaskBarrier:

  • Memory barrier to ensure mask pass writes are visible to cover pass reads

Pass 3 - Cover (Compositing):

glsl
uint packed = imageLoad(uCoverageBuffer, pixelPosition).r;
uint storedStamp = packed >> 8;
uint storedCoverage8 = packed & 0xFFu;
if ((storedStamp == shapeStamp) && (storedCoverage8 > 0u)) {
  float coverage = float(storedCoverage8) / 255.0;
  outFragColor = vec4(color.xyz * coverage, coverage);
}

with a quad covering the transparent shape's bounding box (not the entire viewport!), reading the coverage buffer and compositing the color based on coverage. Note: No per-pixel clearing is performed—the coverage buffer retains previous shape data until stamp exhaustion forces a full clear.

Pass 4 - CoverBarrier:

  • Memory barrier after cover pass to avoid race conditions on overlapped shapes
  • Ensures all cover pass writes to framebuffer are visible before next shape's operations

Algorithm Repeatability and Stamp Management:

  • Shape Stamping: Each transparent shape group receives a unique 24-bit stamp ID, enabling correct order-independent rendering of overlapping transparent shapes, group order still defines compositing order
  • Four-Pass Cycle: The algorithm repeats (Mask → MaskBarrier → Cover → CoverBarrier) for each shape group with incrementing stamp IDs until the 24-bit stamp space (16,777,216 unique IDs) is exhausted, at which point the coverage buffer is cleared and stamps wrap back to zero
  • Deferred Buffer Clearing: Coverage buffer is not cleared between shape groups to maximize performance; clearing only occurs on stamp exhaustion
  • Renderpass Restart Requirement: Due to Vulkan renderpass barrier limitations, each Mask → MaskBarrier → Cover → CoverBarrier cycle requires renderpass restarts, which is architecturally necessary but impacts performance on TBDR mobile GPUs
    • Subpass Limitation: Vulkan subpasses with internal dependencies cannot be used here due to the repeatable nature of the algorithm—subpasses are designed for linear sequencing (subpass 0 → 1 → 2 → 3), but this algorithm requires a cyclical pattern (Mask → MaskBarrier → Cover → CoverBarrier → Mask → MaskBarrier → Cover → CoverBarrier...) that necessitates full renderpass restarts
    • TBDR Impact: Tile-Based Deferred Rendering architectures suffer performance degradation from renderpass interruptions because they must flush on-chip tile memory to main memory when the renderpass is suspended, then reload it on restart—this defeats the core TBDR optimization of keeping tile data on-chip throughout the renderpass

Advantages:

  • Order-independent transparency, group order still defines compositing order
  • Handles overlapping transparent shapes correctly
  • Analytical SDF anti-aliasing (high quality)
  • No geometry sorting required
  • Memory efficient compared to alternatives: R32_UINT per pixel (4 bytes) vs MSAA (16-32 bytes/pixel), A-Buffer (variable/large), or Depth Peeling (multiple full buffers)

Disadvantages:

  • Four passes per transparent shape group with two rendering passes and two barrier passes per shape
  • Coverage buffer memory overhead (requires additional R32_UINT image)
  • Atomic operations may have performance cost
  • Requires renderpass suspend/resume (restart) due to barrier limitations inside renderpasses
    • Mask => MaskBarrier => Cover => CoverBarrier requires renderpass restarts for each transparent shape group
    • Subpasses with internal dependencies cannot be used due to the repeatable nature of the algorithm here
  • Problematic for TBDR (Tile-Based Deferred Rendering) mobile GPUs due to renderpass interruptions

2.4 Direct Spatial Grid GPU Vector Rendering (WIP)

Used by: Direct vector path rendering (planned)

Location: PasVulkan.VectorPath.pas, canvas.frag with FILLTYPE_VECTOR_PATH

Shader Mode: FILLTYPE == FILLTYPE_VECTOR_PATH

GPU Resources:

  • Segment buffer (set 2, binding 0) - VectorPathGPUSegments[]
  • Indirect segment buffer (set 2, binding 1) - VectorPathGPUIndirectSegments[]
  • Grid cell buffer (set 2, binding 2) - VectorPathGPUGridCells[]
  • Shape buffer (set 2, binding 3) - VectorPathGPUShapes[]

Algorithm Overview:

The approach uses spatial subdivision and per-pixel ray-casting:

  1. Preprocessing (CPU):

    • Subdivide shape bounding box into N×N grid cells
    • For each grid cell, collect intersecting segments
    • Build indirect segment lists per cell
    • Insert winding meta-lines for scanline initialization
  2. Runtime (GPU Fragment Shader):

    • Determine which grid cell the pixel falls into
    • Iterate segments in that cell
    • Compute distance to each segment
    • Update winding number using horizontal ray test
    • Apply fill rule (Even-Odd or Non-Zero)
    • Output smooth anti-aliased coverage

Key CPU-Side Classes:

pascal
TpvVectorPathGPUShape=class
 const CoordinateExtents=1.41421356237; // sqrt(2.0) - grid cell padding
 type TGridCell=class
       private
        fBoundingBox:TpvVectorPathBoundingBox;
        fExtendedBoundingBox:TpvVectorPathBoundingBox; // Padded by CoordinateExtents
        fSegments:TpvVectorPathSegments; // Segments intersecting this cell
      end;
 private
  fVectorPathShape:TpvVectorPathShape;
  fResolution:TpvInt32; // Grid resolution (N×N)
  fSegments:TpvVectorPathSegments; // All segments
  fSegmentDynamicAABBTree:TpvVectorPathBVHDynamicAABBTree; // Spatial acceleration
  fGridCells:TGridCells; // Grid subdivision
end;

Key GPU-Side Function:

text
/* Detailed source-code truncated for AI context efficiency. */

Meta Winding Lines:

Meta winding lines are virtual segments inserted between Y-coordinate bands within each grid cell to initialize the winding number for scanline-based evaluation. They solve a fundamental challenge: when a fragment shader evaluates a pixel, it needs to know the correct winding number, but the pixel's horizontal ray may not intersect any actual path segments (e.g., when the pixel is deep inside a closed shape).

Why Meta Winding Lines?

Without proper initialization, pixels in grid cells that don't contain segment intersections would have incorrect winding values. Alternative approaches have significant drawbacks:

  • Prefix sums: Precompute winding for every cell, but this is complex to implement and requires global dependencies, making random access inefficient on GPUs
  • Per-pixel full traversal: Trace from negative infinity to every pixel, but this is prohibitively expensive for complex shapes with many segments
  • Stencil-based methods: Require additional passes and stencil buffer manipulation

How Meta Winding Lines Work:

  1. During preprocessing, identify Y-coordinate bands where path segments intersect grid cell boundaries
  2. Insert meta winding lines at these boundaries, encoding the cumulative winding contribution from segments below
  3. At runtime, the fragment shader reads the meta winding line for the pixel's Y-coordinate to get the base winding value
  4. Then incrementally update winding as it processes actual segments in the cell

This approach provides efficient random access (any pixel can query its grid cell independently) while maintaining correct winding semantics with minimal computational overhead.

Winding Number Calculation:

The winding number is computed using a horizontal ray cast from negative infinity to the pixel position:

  • Line segments: Check if horizontal ray intersects, update winding based on edge orientation
  • Quadratic curves: Solve quadratic equation for y-intersection, check x-coordinates
  • Meta winding lines: Initialize winding for scanline based on previous row's state

Fill Rules:

  • Even-Odd: Inside if (winding & 1) != 0
  • Non-Zero: Inside if winding != 0

Advantages:

  • No pre-processing or texture atlas required
  • Dynamic, arbitrary resolution rendering
  • Memory efficient for large/complex shapes
  • Direct control over quality vs performance

Disadvantages (Current WIP Status):

  • Higher per-pixel computational cost
  • Requires buffer storage for segments/grid
  • More complex shader code

3. Data Flow and Integration

3.1 Path Creation

text
User API (TpvVectorPath)
  ├─ MoveTo / LineTo / QuadraticCurveTo / CubicCurveTo
  ├─ Arc / Circle / Rectangle / RoundedRectangle
  └─ Close
       ↓
TpvVectorPath.GetShape
       ↓
TpvVectorPathShape
  ├─ Contours: TpvVectorPathContours
  ├─ FillRule: EvenOdd / NonZero
  └─ ConvertCubicCurvesToQuadraticCurves (optional)

3.2 GPU Shape Generation

text
TpvVectorPathShape
       ↓
TpvVectorPathGPUShape.Create(shape, resolution, boundingBoxExtent)
       ↓
  ├─ Build segment list from contours
  ├─ Create BVH acceleration structure (TpvVectorPathBVHDynamicAABBTree)
  ├─ Subdivide into N×N grid cells
  ├─ For each grid cell:
  │    ├─ Compute extended bounding box (padding = CoordinateExtents)
  │    ├─ Query intersecting segments via BVH
  │    ├─ Compute segment intersection points
  │    ├─ Sort Y-coordinates
  │    └─ Insert meta winding lines between Y-bands
  └─ Generate GPU buffers:
       ├─ TpvVectorPathGPUSegmentData[]
       ├─ TpvVectorPathGPUIndirectSegmentData[]
       ├─ TpvVectorPathGPUGridCellData[]
       └─ TpvVectorPathGPUShapeData

3.3 Rendering Pipeline

text
TpvCanvas.DrawVectorPath (or similar)
       ↓
Upload GPU buffers (if not cached)
       ↓
Bind descriptor sets:
  ├─ Set 0: Textures & mask
  ├─ Set 1: Coverage buffer (if coverage mode)
  └─ Set 2: Vector path GPU buffers
       ↓
Draw call with push constants:
  ├─ Transform matrices
  ├─ Color
  ├─ Shape stamp (for coverage mode)
  └─ Flags (fill rule, premultiplied alpha, etc.)
       ↓
Fragment Shader:
  ├─ Determine shape coordinates (inTexCoord.z = shape index)
  ├─ Call sampleVectorPathShape(shapeCoord)
  ├─ Apply color and blending
  └─ Output final color

4. Current Implementation Status

4.1 Completed (✓)

  • Core vector path types and API (TpvVectorPath, TpvVectorPathShape)
  • Segment types (Line, Quadratic, Cubic, Meta winding)
  • Bounding box and intersection calculations
  • Grid cell subdivision algorithm
  • GPU data structure definitions (Pascal and GLSL)
  • BVH spatial acceleration structure
  • Meta winding line insertion logic
  • Fragment shader implementation (distance + winding calculation)
  • Quadratic curve distance calculation (analytical solution)
  • Line segment distance calculation
  • Fill rule support (Even-Odd and Non-Zero)
  • Anti-aliasing via fwidth() and linearstep()
  • SDF-based rendering (production, for fonts)
  • Coverage-Mask-then-Cover rendering (production)

4.2 Work In Progress (WIP)

  • CPU→GPU buffer upload integration
  • Canvas API integration for FILLTYPE_VECTOR_PATH
  • Descriptor set management for vector path buffers
  • Pipeline creation for vector path rendering mode
  • Caching and buffer reuse strategies
  • Performance profiling and optimization
  • Memory management for large shape sets

4.3 Planned Enhancements in Future

  • Stroke rendering support
  • Gradient fills integration
  • Texture mapping on vector paths
  • Transform caching
  • Multi-shape batching
  • LOD (Level of Detail) system
  • Cubic curve support (direct, without conversion, but quadratic is sufficient for most cases, even with from-cubic-to-quadratic conversion)
  • GPU-side shape preprocessing (compute shaders)
  • Tessellation shader alternative approach

5. TODO: Completion Steps for Direct Spatial Grid GPU Vector Rendering

Phase 1: Buffer Management and Upload

Priority: HIGH
Estimated Effort: 2-3 days

  • TODO-1.1: Implement TpvCanvas methods for vector path buffer management

    • Add buffer pools for segments, indirect segments, grid cells, shapes
    • Implement buffer allocation and deallocation strategies
    • Add buffer growth and shrinking logic
  • TODO-1.2: Create GPU buffer upload mechanism

    • Implement TpvVectorPathGPUShape.UploadToGPU() method
    • Handle staging buffers for large uploads
    • Add synchronization primitives (fences/semaphores)
  • TODO-1.3: Implement shape handle system

    • Create TpvCanvasVectorPathHandle type
    • Implement handle→buffer mapping
    • Add reference counting for automatic cleanup

Phase 2: Descriptor Set Integration

Priority: HIGH
Estimated Effort: 2 days

  • TODO-2.1: Create descriptor set layout for vector path buffers (set 2)

    • Binding 0: Segment buffer (SSBO)
    • Binding 1: Indirect segment buffer (SSBO)
    • Binding 2: Grid cell buffer (SSBO)
    • Binding 3: Shape buffer (SSBO)
  • TODO-2.2: Implement descriptor set allocation and updates

    • Add descriptor pool management
    • Implement UpdateVectorPathDescriptorSet() method
    • Handle dynamic buffer binding (for multi-shape scenarios)
  • TODO-2.3: Integrate with existing Canvas descriptor sets

    • Ensure compatibility with set 0 (textures) and set 1 (coverage)
    • Update pipeline layout creation

Phase 3: Pipeline Creation

Priority: HIGH
Estimated Effort: 1-2 days

  • TODO-3.1: Compile shader variants with FILLTYPE_VECTOR_PATH

    • Update shader compilation system
    • Create shader module for vector path fragment shader
    • Handle shader permutations (with/without coverage, with/without textures)
  • TODO-3.2: Create graphics pipeline for vector path rendering

    • Configure vertex input state
    • Configure blend state (premultiplied alpha)
    • Configure depth/stencil state
    • Set up dynamic state (viewport, scissor)
  • TODO-3.3: Add pipeline caching

    • Implement pipeline variant selection logic
    • Add pipeline cache serialization

Phase 4: Canvas API Integration

Priority: MEDIUM
Estimated Effort: 3-4 days

  • TODO-4.1: Extend TpvCanvas with vector path methods

    pascal
    function DrawVectorPathDirect(const aVectorPathGPUShape:TpvVectorPathGPUShape;
                                  const aTransform:TpvMatrix4x4;
                                  const aColor:TpvVector4):TpvCanvas;
    
    function FillPath(const aPath:TpvVectorPath;
                      const aRenderMode:TpvCanvasVectorPathRenderMode):TpvCanvas;
    // aRenderMode: DirectSpatialGridGPU, Coverage, SDF
  • TODO-4.2: Implement render mode selection

    • Add TpvCanvasVectorPathRenderMode enum
    • Implement mode switching logic
    • Add configuration hints (quality vs performance)
  • TODO-4.3: Add stroke support (future)

    • Implement stroke expansion to segments
    • Support line caps and joins
    • Integrate with direct rendering path

Phase 5: Optimization and Caching

Priority: MEDIUM
Estimated Effort: 2-3 days

  • TODO-5.1: Implement shape caching

    • Add shape hash calculation
    • Create cache lookup mechanism
    • Implement LRU eviction policy
  • TODO-5.2: Add transform-aware caching

    • Separate shape data from transform
    • Support transform matrices via push constants
    • Avoid re-upload for transformed instances
  • TODO-5.3: Optimize grid cell generation

    • Profile grid cell intersection tests
    • Consider compute shader preprocessing (future)
    • Implement adaptive grid resolution

Phase 6: Multi-Shape Batching

Priority: LOW
Estimated Effort: 3-5 days

  • TODO-6.1: Implement shape atlas/array system

    • Pack multiple shapes into single buffer set
    • Use shape index in texture coordinates (z component)
    • Update shader to support shape array
  • TODO-6.2: Add batching logic

    • Group draw calls by material/state
    • Implement instancing for identical shapes
    • Sort by depth/transparency
  • TODO-6.3: Optimize draw call submission

    • Reduce pipeline binds
    • Merge compatible shapes
    • Add batching statistics

Phase 7: Testing and Validation

Priority: HIGH (before release)
Estimated Effort: 2-3 days

  • TODO-7.1: Create test suite

    • Unit tests for winding number calculation
    • Visual regression tests (compare with SDF/coverage modes)
    • Performance benchmarks
  • TODO-7.2: Test edge cases

    • Self-intersecting paths
    • Degenerate segments (zero-length)
    • Very large/small shapes
    • Complex paths (thousands of segments)
  • TODO-7.3: Validate correctness

    • Compare with reference rasterizer
    • Test both fill rules thoroughly
    • Verify anti-aliasing quality

Phase 8: Documentation and Examples

Priority: MEDIUM
Estimated Effort: 1-2 days

  • TODO-8.1: Update API documentation

    • Document new Canvas methods
    • Add usage examples
    • Explain render mode trade-offs
  • TODO-8.2: Create sample projects

    • Basic vector path rendering demo
    • Performance comparison (Direct vs SDF vs Coverage)
    • Complex scene demo (UI elements, icons)
  • TODO-8.3: Write performance guidelines

    • When to use each rendering mode
    • Grid resolution recommendations
    • Memory usage estimates

6. Technical Design Decisions

6.1 Why Quadratic Curves Only?

  • Simpler intersection calculations
  • Lower polynomial degree in fragment shader
  • Cubic curves are converted using adaptive subdivision
  • Quality loss is negligible at typical resolutions

6.2 Why Meta Winding Lines?

  • Grid cells may have incomplete path coverage
  • Winding number needs initialization for interior cells
  • Meta lines provide correct winding "state" for random access
  • Alternative would be prefix-sum approach (more complex)

6.3 Why Grid Subdivision?

  • Reduces per-pixel segment iteration count
  • Spatial coherence: nearby pixels hit same cell
  • Scalable: adjust resolution for performance/quality trade-off
  • Enables efficient culling of distant segments

6.4 Why Multiple Rendering Modes?

  • SDF: Best for small, repeated shapes (fonts, icons)
  • CPU-Tessellated Direct Rendering: Best for opaque shapes with full path support, where artifacts from overdraw are minimal or almost non-existent, and for sprite rendering and similar use cases
  • Coverage: Best for transparent, order-dependent scenes
  • Direct Spatial Grid GPU vector rendering: Best for dynamic, high-resolution, memory-constrained scenarios
  • No single approach is optimal for all use cases

7. Performance Considerations

7.1 Grid Resolution Trade-offs

Resolution Segment/Cell Quality Memory Performance
4×4 High Lower Low Fast
8×8 Medium Medium Medium Moderate
16×16 Low High High Slower
32×32 Very Low Very High Very High Slowest

Recommendation: Start with 8×8, adjust based on profiling.

7.2 Bottlenecks

CPU-Side:

  • Grid cell intersection tests (mitigated by BVH)
  • Segment intersection point calculation
  • Y-coordinate sorting

GPU-Side:

  • Fragment shader complexity (per-pixel segment iteration)
  • Distance calculation (analytical curve solution)
  • Atomic operations (coverage mode)

7.3 Optimization Strategies

  • Use compute shaders for grid generation (future)
  • Implement hierarchical grid (quadtree/octree)
  • Cache transformed shapes
  • Batch shapes with identical topology

8.1 Pathfinder

  • Project: Pathfinder
  • Papers: "Fast GPU-Based Vector Graphics" (2017)
  • Approach: Similar grid-based rasterization with compute shaders

8.2 Loop-Blinn Algorithm

  • Paper: "Resolution Independent Curve Rendering using Programmable Graphics Hardware" (2005)
  • Approach: Implicit curve representation using texture coordinates
  • Difference: We use distance fields + winding, not implicit forms

8.3 Slug Library

  • Project: Slug
  • Approach: Analytical fragment shader evaluation
  • Similarity: Direct evaluation without tessellation

8.4 Vello (piet-gpu)

  • Project: Vello
  • Approach: GPU-accelerated vector rendering with prefix sums
  • Difference: Uses prefix sum algorithms

8.5 Skia

  • Project: Skia Graphics Library
  • Approach: Multiple rendering backends (Ganesh/Graphite GPU backends, CPU rasterization)
    • Tessellation-based path rendering
    • Stencil-then-cover approach (based on NV_path_rendering)
    • MSAA and MSAA-based anti-aliasing
    • Distance fields for text rendering only
  • Difference: Uses tessellation and stencil approaches rather than per-pixel analytical evaluation; no analytical SDF evaluation for general vector paths (only for text)

9. Known Issues and Limitations (WIP Status)

9.1 Current Limitations

  • Stroke rendering not yet implemented - will be emulated by converting strokes to filled outline shapes (simplifies implementation and leverages existing fill infrastructure)
  • Cubic Bézier curves converted to quadratic curves during preprocessing (quadratic approximation is sufficient for visual quality at typical resolutions, with lower computational cost than direct cubic evaluation)
  • Grid resolution is fixed per shape (no adaptive subdivision)
  • No GPU-side preprocessing

9.2 Potential Issues

  • High segment count per cell may cause performance degradation
  • Very small features may be lost in grid subdivision
  • Numerical precision issues with extreme scale factors

9.3 Future Improvements

  • Adaptive grid resolution based on curvature
  • GPU-based grid generation (compute shader)
  • Stroke path support with proper joins/caps
  • Hierarchical culling for complex scenes

10. API Usage Examples (Future)

10.1 Basic Direct Rendering

pascal
var Path:TpvVectorPath;
    Shape:TpvVectorPathShape;
    GPUShape:TpvVectorPathGPUShape;
begin
 Path:=TpvVectorPath.Create;
 try
  // Build path
  Path.MoveTo(100,100)
      .LineTo(200,100)
      .LineTo(150,200)
      .Close;
  // Convert to shape
  Shape:=Path.GetShape;
  try
   Shape.FillRule:=TpvVectorPathFillRule.NonZero;
   // Create GPU shape
   GPUShape:=TpvVectorPathGPUShape.Create(Shape,8); // 8 = grid resolution
   try
    // Render using Canvas
    Canvas.FillPath(GPUShape,TpvCanvasVectorPathRenderMode.Direct)
          .Color(TpvVector4.Create(1,0,0,1));
   finally
    GPUShape.Free;
   end;
  finally
   Shape.Free;
  end;
 finally
  Path.Free;
 end;
end;

10.2 Mode Comparison

pascal
// Mode 1: SDF (for small, cached shapes like fonts)
Canvas.FillPath(IconPath,TpvCanvasVectorPathRenderMode.SDF);

// Mode 2: Coverage (for transparent overlapping shapes)
Canvas.FillPath(TransparentShape,TpvCanvasVectorPathRenderMode.Coverage);

// Mode 3: Direct Spatial Grid GPU vector rendering (for dynamic high-resolution rendering)
Canvas.FillPath(DynamicPath,TpvCanvasVectorPathRenderMode.DirectSpatialGridGPU);

11. Contribution Guidelines

When working on the Pathfinder-like rendering feature:

  1. Maintain Compatibility: Do not break existing SDF or Coverage rendering modes
  2. Add Tests: Include unit tests for new functionality
  3. Profile: Measure performance impact before and after changes
  4. Document: Update this document with significant changes
  5. Code Style: Follow existing PasVulkan conventions

12. Glossary

  • AABB: Axis-Aligned Bounding Box
  • BVH: Bounding Volume Hierarchy
  • Coverage Buffer: GPU buffer storing per-pixel coverage masks
  • Even-Odd Rule: Fill rule where regions are filled based on odd crossing count
  • Grid Cell: Spatial subdivision unit containing segment references
  • Meta Winding Line: Virtual segment used to initialize winding state
  • Non-Zero Rule: Fill rule where regions are filled based on non-zero winding
  • SDF: Signed Distance Field
  • SSBO: Shader Storage Buffer Object
  • Winding Number: Count of path crossings, determines inside/outside

End of Document


--- METRICS ---