TextureCraft: clean-room 3D texture painting in pure Rust

An open-source, clean-room implementation of a Substance 3D Painter-style texturing
workflow, written in pure Rust with egui and wgpu.

- Layer stack with 32 blend modes, masks, generators, content effects and anchor points
- Painting, projection, smudge, clone, path, lasso fill, particle brush and quick mask
- 43 procedural materials, 17 smart materials and 10 smart masks
- Mesh map baking with high-poly, cage and match-by-name support
- PBR viewport with HDR environments, TAA and a path-traced Rendering mode
- glTF, FBX, COLLADA, OBJ, PLY and STL import; texture export presets; OBJ and GLB export
- Dockable Painter-style UI, shortcut editor, web build, MCP server and CLI

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
bflatasticandClaude Opus 5.5 committed 2026-10-15 01:33:13 +07:00
commit ec859420d5
229 files changed
+46344

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
[alias]
xtask = "run -p xtask --"
+5
View File
@@ -0,0 +1,5 @@
* text=auto eol=lf
*.png binary
*.ico binary
*.icns binary
*.ps1 text eol=crlf
+65
View File
@@ -0,0 +1,65 @@
# Format, lint, test, dependency layering and the wasm32 check on Linux and Windows.
# No macOS here: the org's macOS runner slots are reserved for release.yml
# (craftrules release/cut-a-release.md, Gotchas).
name: CI
on:
push:
branches: [main]
pull_request:
workflow_dispatch:
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
# A newer push to a PR branch cancels its older run. Runs on main are never cancelled, so every
# main state that gets a run is checked to the end.
concurrency:
group: ci-${{ github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
check:
name: check (${{ matrix.os }})
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [ubuntu-latest, windows-latest]
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install Linux system dependencies (egui/winit/wgpu/rfd)
if: runner.os == 'Linux'
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev \
libgl1-mesa-dev libgtk-3-dev
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
components: clippy, rustfmt
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
- name: Format
run: cargo fmt --all -- --check
- name: Clippy
run: cargo clippy --workspace --all-targets --locked -- -D warnings
- name: Test
run: cargo test --workspace --locked
- name: Dependency layering
run: cargo xtask layers
- name: wasm32 check
run: cargo xtask wasm
+59
View File
@@ -0,0 +1,59 @@
# Builds and tests the workspace on FreeBSD, inside a FreeBSD VM on a Linux runner
# (GitHub has no FreeBSD runners). It then runs packaging/freebsd/package.sh, the script the
# release job runs, and checks the tarball, so a broken FreeBSD package fails here before it can
# fail a release. Nothing is uploaded and no secrets are used.
name: FreeBSD
# The VM build takes one to several hours, so it runs nightly on main rather than on every push.
# PRs that change the FreeBSD packaging itself still run it.
on:
schedule:
- cron: "17 2 * * *"
pull_request:
paths:
- .github/workflows/freebsd.yml
- packaging/freebsd/**
- packaging/env.sh
workflow_dispatch:
concurrency:
group: freebsd-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
freebsd:
name: FreeBSD 14 (build + test + package)
runs-on: ubuntu-latest
timeout-minutes: 300
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Build, test and package in a FreeBSD VM
# vmactions/freebsd-vm v1.5.9, pinned by commit (it runs our build).
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1.5.9
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
# Nothing to bring back; copying the target dir out of the VM fails on large builds.
copyback: false
prepare: |
pkg install -y bash git curl pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
run: |
set -e
. "$HOME/.cargo/env"
# The checkout is synced in under another owner; let tests that call git read it.
git config --global --add safe.directory "*"
rustc --version
# One test thread: the VM's software Vulkan driver crashes when several tests set up a
# GPU device at once (PhotoCraft). GPU tests must skip themselves when there is no adapter.
CARGO_PROFILE_DEV_DEBUG=0 cargo test --workspace --locked -- --test-threads=1
# The release package, as release.yml builds it. Free the debug build's disk first.
rm -rf target/debug
CARGO_BUILD_JOBS=4 bash packaging/freebsd/package.sh
tar -tzf dist/release/texturecraft-*-freebsd-x86_64.tar.gz \
| grep -E '/bin/texturecraft$|/bin/texturecraft-cli$|/share/applications/ai\.storyteller\.texturecraft\.desktop$|/share/doc/texturecraft/LICENSE-MIT$'
+70
View File
@@ -0,0 +1,70 @@
# Quick static checks for the release pipeline (seconds, no Rust build): workflow syntax,
# packaging shell/PowerShell scripts, and the Linux desktop/AppStream/Flatpak metadata.
name: Packaging lint
on:
push:
branches: [main, release]
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
pull_request:
paths: [".github/workflows/**", "packaging/**", "assets/app-icon/**"]
workflow_dispatch:
permissions:
contents: read
concurrency:
group: packaging-lint-${{ github.ref }}
cancel-in-progress: true
jobs:
lint:
runs-on: ubuntu-latest
env:
ACTIONLINT_VERSION: 1.7.12
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends shellcheck desktop-file-utils appstream libxml2-utils python3-yaml
curl -fsSL "https://github.com/rhysd/actionlint/releases/download/v${ACTIONLINT_VERSION}/actionlint_${ACTIONLINT_VERSION}_linux_amd64.tar.gz" \
| tar -xz -C "$RUNNER_TEMP" actionlint
- name: actionlint
run: |
"$RUNNER_TEMP/actionlint" -color
- name: shellcheck
run: shellcheck packaging/*.sh packaging/*/*.sh packaging/linux/AppRun
- name: AppImage AppRun desktop integration
run: bash packaging/linux/apprun-test.sh
- name: PowerShell
shell: pwsh
run: |
foreach ($f in Get-ChildItem packaging/windows/*.ps1) {
$errors = $null
[System.Management.Automation.Language.Parser]::ParseFile($f.FullName, [ref]$null, [ref]$errors) | Out-Null
if ($errors) { $errors | ForEach-Object { Write-Output "::error file=$($f.Name)::$_" }; exit 1 }
Write-Output "ok $($f.Name)"
}
- name: XML, desktop entry, AppStream, Flatpak manifest
run: |
xmllint --noout packaging/windows/texturecraft.wxs packaging/macos/*.plist* packaging/linux/*.xml*
# Windows Installer needs Icon ids ending in .ico or .exe, or shortcuts show a blank icon (ICE50).
if grep -oE '<Icon Id="[^"]*"' packaging/windows/texturecraft.wxs | grep -vE '\.(ico|exe)"$'; then
echo "::error::Icon Id must end in .ico or .exe"; exit 1
fi
desktop-file-validate packaging/linux/ai.storyteller.texturecraft.desktop
sed -e 's/@VERSION@/0.0.0/' -e 's/@DATE@/2026-01-01/' packaging/linux/ai.storyteller.texturecraft.metainfo.xml.in >"$RUNNER_TEMP/ai.storyteller.texturecraft.metainfo.xml"
appstreamcli validate --no-net --explain "$RUNNER_TEMP/ai.storyteller.texturecraft.metainfo.xml"
python3 - <<'EOF'
import yaml
src = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.TextureCraft.yml"))
bundle = yaml.safe_load(open("packaging/linux/flatpak/ai.storyteller.TextureCraft.bundle.yml"))
for m in (src, bundle):
assert m["id"] == "ai.storyteller.texturecraft" and m["command"] == "texturecraft", m["id"]
for key in ("runtime", "runtime-version", "sdk", "finish-args"):
assert src[key] == bundle[key], f"Flatpak manifests disagree on {key}: {src[key]} vs {bundle[key]}"
print("Flatpak manifests ok")
EOF
- name: FreeBSD tarball layout (stub binaries)
run: bash packaging/freebsd/package.sh --dry-run
+381
View File
@@ -0,0 +1,381 @@
# Release pipeline: every push to `release` builds platform artifacts (signed where credentials
# are configured) and creates or updates the draft GitHub Release "TextureCraft v<version>".
# See docs/releasing.md and craftrules release/playbook.md.
#
# The signing jobs (macOS, Windows) and the draft-release job run in the `release` environment
# (restricted to the `release` branch), which holds the signing secrets. Every secret is optional:
# missing ones produce unsigned artifacts and a warning, never a failed build. The jobs that sign
# nothing (version, Linux, Flatpak, FreeBSD, web) run without it, so a dispatch on any branch is a
# dry run of them; the release job needs the signed jobs, so a branch run never drafts a release.
name: Release
on:
push:
branches: [release]
workflow_dispatch:
inputs:
version:
description: "Version override for a test run, e.g. 0.2.0-rc.1 (empty: Cargo.toml)"
type: string
default: ""
permissions:
contents: read
concurrency:
group: release-${{ github.ref }}
# Never cancel a run mid-notarization or mid-upload; a newer push waits its turn.
cancel-in-progress: false
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
RUST_BACKTRACE: 1
TEXTURECRAFT_BUILD_SHA: ${{ github.sha }}
INPUT_VERSION: ${{ inputs.version }}
jobs:
version:
name: version
runs-on: ubuntu-latest
# No `environment: release` here or on the other jobs that sign nothing: no release secrets.
outputs:
version: ${{ steps.v.outputs.version }}
date: ${{ steps.v.outputs.date }}
prerelease: ${{ steps.v.outputs.prerelease }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- id: v
name: Resolve version
run: |
. packaging/env.sh
v="${INPUT_VERSION#v}"
v="${v:-$VERSION}"
if ! printf '%s' "$v" | grep -Eq '^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z-]+(\.[0-9A-Za-z-]+)*)?$'; then
echo "::error::'$v' is not a version like 1.2.3 or 1.2.3-rc.1"
exit 1
fi
case "$v" in *-*) pre=true ;; *) pre=false ;; esac
{
echo "version=$v"
echo "date=$(date -u +%Y-%m-%d)"
echo "prerelease=$pre"
} >>"$GITHUB_OUTPUT"
echo "### TextureCraft v$v (\`${GITHUB_SHA::9}\`)" >>"$GITHUB_STEP_SUMMARY"
macos:
name: macOS universal
needs: version
runs-on: macos-15-xlarge # M2 Pro larger runner; use only in release.yml (actions_macos_xl budget caps spend)
environment: release
env:
TEXTURECRAFT_VERSION: ${{ needs.version.outputs.version }}
TEXTURECRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
targets: aarch64-apple-darwin, x86_64-apple-darwin
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-macos-universal
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$TEXTURECRAFT_VERSION"
- name: Import signing certificate
env:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
run: bash packaging/macos/import-cert.sh
- name: Build, sign, notarize
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: bash packaging/macos/package.sh --arch universal
# Unpacks the CLI zip and checks the binary users get: Developer ID, hardened runtime,
# timestamp, and Gatekeeper's notarization lookup; also the DMG's stapled ticket. Strict when
# the signing secrets are present, warnings otherwise.
- name: Verify signatures and notarization
env:
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
run: bash packaging/macos/verify.sh --arch universal
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-macos
path: dist/release/*
if-no-files-found: error
- name: Remove temporary keychain
if: always()
run: |
if [ -n "${MACOS_KEYCHAIN:-}" ]; then security delete-keychain "$MACOS_KEYCHAIN" || true; fi
windows:
name: Windows ${{ matrix.arch }}
needs: version
runs-on: windows-latest
environment: release
strategy:
fail-fast: false
matrix:
include:
- { arch: x64, target: x86_64-pc-windows-msvc }
- { arch: x86, target: i686-pc-windows-msvc }
# Windows on ARM: cross-compiled on the x64 runner, so signing and WiX run as above.
# .github/workflows/windows-arm64.yml installs and runs it on ARM64 hardware.
- { arch: arm64, target: aarch64-pc-windows-msvc }
env:
TEXTURECRAFT_VERSION: ${{ needs.version.outputs.version }}
TEXTURECRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
targets: ${{ matrix.target }}
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-windows-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
shell: bash
run: cargo xtask version set "$TEXTURECRAFT_VERSION"
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
- name: Build, sign, package
shell: pwsh
env:
WINDOWS_CERTIFICATE: ${{ secrets.WINDOWS_CERTIFICATE }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
run: ./packaging/windows/package.ps1 -Arch ${{ matrix.arch }}
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-windows-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
linux:
name: Linux ${{ matrix.arch }}
needs: version
# The oldest GitHub-hosted image, so the binaries only need glibc >= 2.35 (Ubuntu 22.04+,
# Debian 12+, Fedora 36+, RHEL 10). See docs/releasing.md.
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-22.04, deb: amd64 }
- { arch: aarch64, runner: ubuntu-22.04-arm, deb: arm64 }
env:
TEXTURECRAFT_VERSION: ${{ needs.version.outputs.version }}
TEXTURECRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
NFPM_VERSION: 2.47.0
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Install build and packaging tools
run: |
sudo apt-get update
sudo apt-get install -y --no-install-recommends \
libxkbcommon-dev libwayland-dev libx11-dev libxrandr-dev libxi-dev libgl1-mesa-dev libgtk-3-dev \
desktop-file-utils appstream python3-yaml zsync
curl -fsSL -o "$RUNNER_TEMP/nfpm.deb" \
"https://github.com/goreleaser/nfpm/releases/download/v${NFPM_VERSION}/nfpm_${NFPM_VERSION}_${{ matrix.deb }}.deb"
sudo dpkg -i "$RUNNER_TEMP/nfpm.deb"
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-linux-${{ matrix.arch }}
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$TEXTURECRAFT_VERSION"
- name: Build and package (AppImage, deb, rpm, tar.gz)
run: bash packaging/linux/package.sh
- name: Check the packages
run: |
dpkg-deb --info dist/release/*.deb
dpkg-deb --contents dist/release/*.deb | grep -E 'usr/bin/texturecraft$|metainfo|applications'
ldd target/release/texturecraft
python3 -c "import yaml; m = yaml.safe_load(open('packaging/linux/flatpak/ai.storyteller.TextureCraft.yml')); assert m['id'] == 'ai.storyteller.texturecraft'"
for appimage in dist/release/*.AppImage; do
chmod +x "$appimage"
APPIMAGE_EXTRACT_AND_RUN=1 "$appimage" --version
# Update information is embedded, and the .zsync for delta updates sits beside it.
"$appimage" --appimage-updateinformation | grep -F 'gh-releases-zsync|'
test -s "$appimage.zsync"
done
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-linux-${{ matrix.arch }}
path: dist/release/*
if-no-files-found: error
flatpak:
name: Flatpak ${{ matrix.arch }}
needs: [version, linux]
# Repackages the Linux job's tarball (the same binaries as the AppImage/deb/rpm); no Rust
# build here. 24.04 for a newer flatpak-builder (1.4) than 22.04 ships.
runs-on: ${{ matrix.runner }}
strategy:
fail-fast: false
matrix:
include:
- { arch: x86_64, runner: ubuntu-24.04 }
- { arch: aarch64, runner: ubuntu-24.04-arm }
env:
TEXTURECRAFT_VERSION: ${{ needs.version.outputs.version }}
TEXTURECRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: release-linux-${{ matrix.arch }}
path: dist/linux
- name: Install flatpak-builder
run: |
sudo apt-get update
# librsvg2-common: the SVG pixbuf loader. flatpak-builder runs the host's
# `appstreamcli compose`, which renders the scalable icon and fails without it.
sudo apt-get install -y --no-install-recommends flatpak flatpak-builder librsvg2-common
# Ubuntu 24.04's AppArmor blocks the unprivileged user namespaces bubblewrap needs.
sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0
- name: Build the Flatpak bundle
run: bash packaging/linux/flatpak-bundle.sh "dist/linux/texturecraft-$TEXTURECRAFT_VERSION-linux-${{ matrix.arch }}.tar.gz"
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-flatpak-${{ matrix.arch }}
path: dist/release/*.flatpak
if-no-files-found: error
freebsd:
name: FreeBSD x86_64
needs: version
# GitHub has no FreeBSD runners: build in a FreeBSD 14.3 VM, the same image and packages as
# .github/workflows/freebsd.yml.
runs-on: ubuntu-latest
timeout-minutes: 180
env:
TEXTURECRAFT_VERSION: ${{ needs.version.outputs.version }}
TEXTURECRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- name: Build and package in a FreeBSD VM (tar.gz)
# vmactions/freebsd-vm v1.5.9, pinned by commit (it runs our build).
uses: vmactions/freebsd-vm@c46abacb49f09938ca4e1702d15d836285d694cc # v1.5.9
with:
release: "14.3"
usesh: true
cpu: 4
mem: 12288
# Passed into the VM by name; never templated into the script below.
envs: "TEXTURECRAFT_VERSION TEXTURECRAFT_BUILD_DATE TEXTURECRAFT_BUILD_SHA INPUT_VERSION"
# The FreeBSD CI packages, plus bash for the packaging script.
prepare: |
pkg install -y bash git curl pkgconf cmake python3 libxkbcommon wayland libX11 libXcursor libXrandr libXi libxcb mesa-libs vulkan-loader gtk3 fontconfig freetype2
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable
run: |
set -e
. "$HOME/.cargo/env"
git config --global --add safe.directory "$PWD"
# Build outside the checkout so only dist/ is copied back out of the VM (copying the
# target dir back fails on large builds). 4 jobs: more runs the VM out of memory.
export CARGO_TARGET_DIR=/var/tmp/texturecraft-target CARGO_BUILD_JOBS=4
if [ -n "$INPUT_VERSION" ]; then cargo xtask version set "$TEXTURECRAFT_VERSION"; fi
bash packaging/freebsd/package.sh
tar -tzf dist/release/texturecraft-*-freebsd-x86_64.tar.gz \
| grep -E '/bin/texturecraft$|/bin/texturecraft-cli$|/share/applications/ai\.storyteller\.texturecraft\.desktop$|/share/doc/texturecraft/LICENSE-MIT$'
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-freebsd-x86_64
path: dist/release/*
if-no-files-found: error
web:
name: Web (wasm)
needs: version
runs-on: ubuntu-latest
env:
TEXTURECRAFT_VERSION: ${{ needs.version.outputs.version }}
TEXTURECRAFT_BUILD_DATE: ${{ needs.version.outputs.date }}
TRUNK_VERSION: 0.21.14
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
targets: wasm32-unknown-unknown
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: release-web
- name: Install trunk
run: |
curl -fsSL "https://github.com/trunk-rs/trunk/releases/download/v${TRUNK_VERSION}/trunk-x86_64-unknown-linux-gnu.tar.gz" \
| tar -xz -C "$HOME/.cargo/bin" trunk
trunk --version
- name: Apply version override
if: inputs.version != ''
run: cargo xtask version set "$TEXTURECRAFT_VERSION"
- name: Build and zip
run: bash packaging/web/package.sh
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: release-web
path: dist/release/*
if-no-files-found: error
release:
name: Draft GitHub Release
needs: [version, macos, windows, linux, flatpak, freebsd, web]
runs-on: ubuntu-latest
environment: release
permissions:
contents: write
env:
VERSION: ${{ needs.version.outputs.version }}
PRERELEASE: ${{ needs.version.outputs.prerelease }}
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
GH_REPO: ${{ github.repository }}
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
pattern: release-*
path: artifacts
merge-multiple: true
- name: Checksums
working-directory: artifacts
run: |
sha256sum -- * | tee SHA256SUMS.txt
- name: Create or update the draft release
working-directory: artifacts
run: |
tag="v$VERSION"
title="TextureCraft v$VERSION"
pre=()
if [ "$PRERELEASE" = true ]; then pre=(--prerelease); fi
if draft="$(gh release view "$tag" --json isDraft --jq .isDraft 2>/dev/null)"; then
if [ "$draft" != "true" ]; then
echo "::error::Release $tag is already published. Bump the version (cargo xtask version set) before pushing to release."
exit 1
fi
echo "Updating draft $tag: replacing its assets"
gh release view "$tag" --json assets --jq '.assets[].name' | while read -r asset; do
gh release delete-asset "$tag" "$asset" --yes
done
gh release edit "$tag" --draft --title "$title" --target "$GITHUB_SHA" --prerelease="$PRERELEASE"
gh release upload "$tag" --clobber -- *
else
echo "Creating draft $tag"
gh release create "$tag" --draft --title "$title" --target "$GITHUB_SHA" --generate-notes "${pre[@]}" -- *
fi
{
echo "Draft release **$title** at \`${GITHUB_SHA::9}\`:"
echo
sed 's/^/ /' SHA256SUMS.txt
} >>"$GITHUB_STEP_SUMMARY"
+91
View File
@@ -0,0 +1,91 @@
# Windows on ARM: package the ARM64 release the way release.yml does (cross-compiled on an x64
# runner, unsigned here), then install that MSI on a Windows 11 ARM64 runner, check the installed
# binaries are ARM64, run the CLI natively, and uninstall. (A native ARM64 `cargo test` job is left
# out for now: PdfCraft saw an intermittent access violation in egui UI tests there.)
name: Windows ARM64
# Nightly on main (dependency and runner-image drift shows up within a day), and on PRs that
# change the Windows packaging itself.
on:
pull_request:
paths:
- .github/workflows/windows-arm64.yml
- packaging/windows/**
schedule:
- cron: "41 4 * * *"
workflow_dispatch:
concurrency:
group: windows-arm64-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
env:
CARGO_TERM_COLOR: always
CARGO_INCREMENTAL: 0
jobs:
package:
name: package (cross-compiled on x64)
runs-on: windows-latest
timeout-minutes: 90
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stable
with:
targets: aarch64-pc-windows-msvc
- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2.9.2
with:
key: windows-arm64-package
- name: Install WiX
shell: pwsh
run: dotnet tool install --global wix --version 5.0.2
- name: Build and package (unsigned)
shell: pwsh
env:
DIST: ${{ github.workspace }}\dist\arm64
run: ./packaging/windows/package.ps1 -Arch arm64
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
with:
name: texturecraft-windows-arm64
path: dist/arm64/*
if-no-files-found: error
retention-days: 7
install:
name: install and run on ARM64
needs: package
runs-on: windows-11-arm
timeout-minutes: 30
steps:
- uses: actions/download-artifact@9000827ccba6bdab643e8b6fd33ac0654aef8333 # v8.0.2
with:
name: texturecraft-windows-arm64
path: dist
- name: Install the MSI, check it, run it, uninstall it
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
$msi = (Get-ChildItem dist/*.msi | Select-Object -First 1).FullName
$p = Start-Process msiexec.exe -ArgumentList '/i', "`"$msi`"", '/qn', '/l*v', 'install.log' -Wait -PassThru
if ($p.ExitCode -ne 0) { Get-Content install.log -Tail 60; throw "msiexec /i exited $($p.ExitCode)" }
$dir = Join-Path $env:ProgramFiles 'TextureCraft'
foreach ($exe in 'texturecraft.exe', 'texturecraft-cli.exe') {
$path = Join-Path $dir $exe
if (-not (Test-Path $path)) { throw "$exe not installed in $dir" }
$bytes = [System.IO.File]::ReadAllBytes($path)
$machine = [BitConverter]::ToUInt16($bytes, [BitConverter]::ToInt32($bytes, 0x3C) + 4)
if ($machine -ne 0xAA64) { throw "$exe is for machine 0x$('{0:X}' -f $machine), not ARM64" }
Write-Output "ok $path (ARM64)"
}
# The installed CLI runs natively on ARM64.
$cli = Join-Path $dir 'texturecraft-cli.exe'
$out = & $cli --version 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) { Write-Output $out; throw "texturecraft-cli --version exited $LASTEXITCODE" }
Write-Output "ok texturecraft-cli --version: $($out.Trim())"
$p = Start-Process msiexec.exe -ArgumentList '/x', "`"$msi`"", '/qn' -Wait -PassThru
if ($p.ExitCode -ne 0) { throw "msiexec /x exited $($p.ExitCode)" }
if (Test-Path (Join-Path $dir 'texturecraft.exe')) { throw 'uninstall left texturecraft.exe behind' }
Write-Output 'ok uninstalled'
+11
View File
@@ -0,0 +1,11 @@
*~
plan/
/target
target/
/dist
/corpus
/log
/secrets
/temp
/craft-fonts
*.tcraft.tmp
+166
View File
@@ -0,0 +1,166 @@
# AGENTS.md: guide for AI agents and contributors
TextureCraft is an open-source, native 3D texture painter: a clean-room implementation of the
workflow known from Adobe Substance 3D Painter, written in **Rust only** (no JavaScript or TypeScript). **No Tauri, Electron or webview
shells:** the desktop app is native egui/eframe on wgpu, and the web build is the same Rust compiled
to WebAssembly (trunk + wasm-bindgen). Never add Tauri (or any webview/JS UI framework) as a
dependency, build step or packaging target. The product name is always written **TextureCraft**
(`{Function}Craft` in PascalCase, like its siblings PhotoCraft, VectorCraft, FilmCraft, LightCraft,
PdfCraft, EffectCraft, DesignCraft) in user-facing text: UI, window titles, About, installers,
release names, docs prose. Machine names stay lowercase: crates (`texturecraft-*`), binaries, file
names, ids (`ai.storyteller.texturecraft`), the native project extension `.tcraft`.
Standards and learnings shared across the crafting apps live in `../craftrules` (checked out next
to this repo, or `storytold/craftrules`). Read its `AGENTS.md` at the start of a session, follow its
standards, and contribute reusable learnings back there. Shared code goes only in craft-libs
(`standards/shared-libraries.md`); otherwise copy, don't depend.
The goal is 1:1 parity with Substance 3D Painter's workflow (same panels, menus, shortcuts, layer
stack semantics and export conventions) with better performance, every feature drivable by agents,
and builds for Windows, macOS, Linux, FreeBSD and the web. Read this file first, then `docs/`.
## 1. Orientation (5 minutes)
| Read | Why |
|---|---|
| `docs/architecture.md` | Crate map, layers, the CPU texel engine + GPU viewport split, data flow |
| `docs/control-protocol.md` | The JSON control channel and MCP: how agents drive the running app |
| `ROADMAP.md` | Honest parity estimate, milestones, **current focus** |
| `docs/parity.md` | Generated list of Painter menu items: live or missing |
| `docs/releasing.md` | Versioning (`cargo xtask version`), the `release` branch, packaging |
| `ATTRIBUTION.md` | Every bundled asset with author, source, license |
| `crates/<name>/README.md` (where present) | Public API of that crate |
## 2. Workspace map
```text
crates/
core texel geom L0 document model + blend math; sparse COW tiles, padding, noise; meshes, BVH, UV G-buffer, camera
compose bake L1 CPU layer-stack compositor (the oracle) + display conversion; mesh map bakers
paint formats L2 brush engine (strokes, stamps, visibility, commit); mesh import, texture export, .tcraft
engine render L3 Session + command registry (every action is a command); wgpu viewport renderer
automation L4 MCP server + headless JSON-lines RPC + bridge to the running app
ui-egui L5 egui shell (thin: every action goes through engine commands)
apps/
texturecraft desktop app (eframe/wgpu), `--control <port>` loopback control server
texturecraft-cli headless CLI (info, run, commands, bake, export, render, mcp, serve)
texturecraft-web the same app in the browser (trunk + wasm-bindgen)
xtask/ cargo xtask layers | wasm | ci | version | ico | icns | parity
```
**Layering is enforced** by `cargo xtask layers`: a crate may depend only on lower layers. Nothing
below `ui-egui` may use egui, eframe, winit or rfd; only `render`, `ui-egui` and the apps may use
wgpu. A new crate must be registered in `xtask/src/layers.rs`.
**The UI crate is swappable.** `texturecraft-ui-egui` holds no document logic: it calls engine
commands (`texturecraft_engine::execute`) and the session's stroke API. Another front end could
replace it without touching the engine.
## 3. Golden rules
### Assets, icons and images (absolutely essential)
- **Never use any icon, image, logo, texture, material, brush, environment, font or other asset
from Adobe, Avid, Image-Line or Autodesk products**, and never copy files from any installed
commercial application (proprietary formats such as `.sbsar`, `.spexp`, `.sppr` or `.spsm`, HDR
environments, UI icons). Not as reference files in the repo either.
- Every image or icon must be **open source, public domain, Creative Commons (CC0/CC-BY), or
original** (made by a contributor who has the right to license it). Prefer generating content in
code (TextureCraft's environments, materials, alphas, meshes and thumbnails are all procedural).
- **Every bundled asset gets a row in [`ATTRIBUTION.md`](ATTRIBUTION.md)** (path, title, author,
source, license) **in the same change that adds it**, plus its license file next to it when the
license requires one. Assets compiled in through dependencies (icon fonts, default fonts) get a
row too. No row, no merge.
- Demo images and README screenshots show TextureCraft rendering original or public-domain content
only. Never personal photos.
- The ArtCraft logos in `docs/brand/` are not open source (`docs/brand/LICENSE-brand.txt`).
- Fonts live in [storytold/craft-fonts](https://github.com/storytold/craft-fonts); never commit font
files here.
### Clean room
TextureCraft is an independent, clean-room implementation of a professional texture-painting
workflow. Work from public documentation, general domain knowledge, public algorithms
(GGX/Smith/Schlick, split-sum IBL, MikkTSpace, jump-flood/BFS dilation, Möller–Trumbore, SAH BVH,
spherical harmonics, reoriented normal mapping, W3C blend modes) and public engine conventions
(glTF, Unreal, Unity packing). Never copy proprietary code, shaders, presets or file formats;
Painter file compatibility (`.spp`, `.spexp`, `.sbsar`) is a non-goal. Always describe TextureCraft
as a clean-room implementation, in code, docs and commits.
### Never crash (outranks feature work)
People trust TextureCraft with hours of painting. A malformed mesh or project, a bad command or MCP
param, an odd keystroke or a full disk must produce an error the user or agent can act on, never a
panic. The shared standard is `../craftrules/standards/never-crash.md`.
- Non-test code never panics: no `unwrap()`, `expect()`, `panic!`, `unreachable!`, `todo!` or
`unimplemented!`. Every production crate root carries
`#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]`.
- No `unsafe` (`unsafe_code = "forbid"` for the workspace).
- Input-derived numbers are hostile: `get()` instead of `[i]`, checked/saturating arithmetic, caps
on allocations (mesh triangles, image sizes, zip entries), NaN guards.
- Every crash fix comes with a regression test. The engine's `panic_hunt` test runs every command
with hostile params; keep it green when adding commands.
### Architecture rules
1. **Everything is a command.** New user-visible behaviour = a command in the engine
(`crates/engine/src/*_cmds.rs`, registered in `commands.rs`) with id, label, menu path,
shortcut, params doc, `enabled` and `run`, plus tests. The menus, shortcuts, CLI, control channel
and MCP all dispatch commands by id. Menu items come from the catalog in
`crates/ui-egui/src/menus.rs`; an item goes live when its id is implemented.
2. **Programmatic calls never open dialogs.** A command run through the control channel or MCP runs
with defaults; only `ui.menu.invoke` behaves like a menu click.
3. **Inspect shows the agent's work.** `project.inspect` / `session.inspect` must reveal every
layer, mask, effect, fill source and painted tile count an agent changed.
4. **CPU oracle, GPU display.** Layers live as sparse copy-on-write 64×64 tiles; compositing,
painting, baking and export run on the CPU per dirty tile (rayon) and are fully testable; dirty
tiles are uploaded to wgpu textures for the viewport. Any GPU acceleration must match the CPU
compositor in parity tests.
5. **Undo is snapshots.** `Session::edit` clones the document (copy-on-write tiles make this cheap)
and restores it on error, so every command is atomic.
6. **Never break wasm.** L0–L5 must `cargo check --target wasm32-unknown-unknown`
(`cargo xtask wasm`). File-system code is `cfg(not(target_arch = "wasm32"))` with byte-based
alternatives.
7. **Performance is a feature.** Never scan a full texture set per frame; work on dirty tiles.
Benchmark heavy paths (bake, composite, export) in release and record numbers in the dev log.
8. **Verify UI changes visually.** Launch with `--control <port>` and call `ui.screenshot` (whole
window) or `viewport.screenshot`; look at the PNG.
## 4. Picking work
1. `ROADMAP.md` → **Current focus** and the parity table.
2. `docs/parity.md` → missing menu items, grouped by menu.
3. Run the app, take screenshots of TextureCraft and fix the biggest visible gaps in the workflow.
4. `log/devlog.md` (local) → the "Still open" bullets of recent entries.
## 5. Before you finish a task
```sh
cargo fmt --all
cargo test -p <crates you touched> --release
cargo clippy --workspace --all-targets -- -D warnings
cargo xtask layers
cargo xtask wasm # if you touched L0–L5
cargo test -p texturecraft-engine --test session panic_hunt # if you added/changed commands
```
Then append a terse entry to `log/devlog.md` (what landed, numbers, what's still open). Commit
after every arc of work that builds and passes.
## 6. Parallel agents
- Use your own target dir (`CARGO_TARGET_DIR=target/agent-<name>`) and edit only the files you own.
Shared files (`engine/src/commands.rs`, `engine/src/lib.rs`, `ui-egui/src/menus.rs`,
`ui-egui/src/lib.rs`, the root `Cargo.toml`) get small, surgical edits; re-read before editing.
- Put new commands in a **new module** with its own `specs()` registered by one line.
- Write manifests atomically; one broken `Cargo.toml` breaks every agent's build.
- Delete your `target/agent-*` dir when done.
## 7. Where things are tracked
- `ROADMAP.md`: milestones, parity estimate and remaining effort.
- `docs/parity.md`: generated Painter menu coverage.
- `docs/releasing.md` and `../craftrules/release/playbook.md`: release builds and signing.
- `plan/` (local, gitignored): execution plan and notes.
- `log/` (local, gitignored): the dev log.
+35
View File
@@ -0,0 +1,35 @@
# Attribution
Every bundled non-code asset in this repository, with its author, source and license. The rule:
**each asset gets a row here in the same change that adds it.** TextureCraft's own code and
original assets are MIT OR Apache-2.0 (see [`LICENSE-MIT`](LICENSE-MIT),
[`LICENSE-APACHE`](LICENSE-APACHE) and [`NOTICE`](NOTICE)); third-party assets must be permissively
licensed and keep their license file next to them.
| Path | Title | Author | Source | License |
|---|---|---|---|---|
| `assets/app-icon/icon.py` | App icon generator (octopus) | TextureCraft contributors | original | MIT OR Apache-2.0 |
| `assets/app-icon/icon.svg` | App icon, master vector (generated by `icon.py`) | TextureCraft contributors | original | MIT OR Apache-2.0 |
| `assets/app-icon/icon-1024.png` | App icon, 1024 px | TextureCraft contributors | original | MIT OR Apache-2.0 |
| `assets/app-icon/texturecraft.ico` | Windows app icon (16-256 px) | TextureCraft contributors | original | MIT OR Apache-2.0 |
| `assets/app-icon/texturecraft.icns` | macOS app icon (16-1024 px) | TextureCraft contributors | original | MIT OR Apache-2.0 |
| `assets/app-icon/hicolor/{16x16,24x24,32x32,48x48,64x64,128x128,256x256,512x512}/apps/ai.storyteller.texturecraft.png` | App icon, hicolor theme PNGs | TextureCraft contributors | original | MIT OR Apache-2.0 |
| `assets/app-icon/hicolor/scalable/apps/ai.storyteller.texturecraft.svg` | App icon, hicolor scalable (copy of `icon.svg`) | TextureCraft contributors | original | MIT OR Apache-2.0 |
| `docs/brand/artcraft-*.svg`, `docs/brand/artcraft-*.png` | ArtCraft logo and mark | ArtCraft Team | storytold/craftrules `assets/brand/` | ArtCraft brand terms, not open source ([`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt)) |
## Third-party assets compiled into the binary
These come from Rust crate dependencies (not files in this repository) and keep their licenses.
| Asset | Used for | Author | Source | License |
|---|---|---|---|---|
| Phosphor Icons (regular), via the `egui-phosphor` crate | Every UI icon (tools, layers, panels) | Phosphor Icons (Helena Zhang, Tobias Fried) | https://phosphoricons.com, https://github.com/amPerl/egui-phosphor | MIT (icons); crate MIT OR Apache-2.0 |
| egui default fonts (Ubuntu-Light, Hack, Noto Emoji, emoji-icon-font), via `epaint_default_fonts` | UI text | Canonical / Source Foundry / Google / Jessie Jung | https://github.com/emilk/egui | Ubuntu Font Licence 1.0, MIT, OFL 1.1, MIT |
## Procedural content (no asset files)
Built-in environments (`crates/render/src/ibl.rs`), smart materials and procedurals
(`crates/engine/src/materials.rs`, `crates/compose/src/pattern.rs`), brush alphas
(`crates/paint/src/brush.rs`), meshes (`crates/geom/src/primitives.rs`) and shelf thumbnails
(`crates/ui-egui/src/thumbs.rs`) are generated in code by TextureCraft contributors (MIT OR
Apache-2.0). None of them is derived from another product's presets, shaders, materials or images.
+5
View File
@@ -0,0 +1,5 @@
# TextureCraft: instructions for Claude
Read [`AGENTS.md`](AGENTS.md) first: it is the guide for every agent working in this repository
(workspace map, golden rules including the asset and attribution rules, the definition of done).
Then read `../craftrules/AGENTS.md` for the standards shared by all Crafting Apps.
Generated
+5080
View File
File diff suppressed because it is too large. Load diff
+100
View File
@@ -0,0 +1,100 @@
[workspace]
resolver = "3"
members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "apps/texturecraft-web", "xtask"]
default-members = ["crates/core", "crates/texel", "crates/geom", "crates/compose", "crates/bake", "crates/formats", "crates/paint", "crates/engine", "crates/render", "crates/automation", "crates/ui-egui", "apps/texturecraft", "apps/texturecraft-cli", "xtask"]
[workspace.package]
version = "0.1.0"
edition = "2024"
license = "MIT OR Apache-2.0"
rust-version = "1.95"
repository = "https://github.com/storytold/texturecraft"
[workspace.dependencies]
# internal
texturecraft-core = { path = "crates/core" }
texturecraft-texel = { path = "crates/texel" }
texturecraft-geom = { path = "crates/geom" }
texturecraft-bake = { path = "crates/bake" }
texturecraft-paint = { path = "crates/paint" }
texturecraft-formats = { path = "crates/formats" }
texturecraft-compose = { path = "crates/compose" }
texturecraft-engine = { path = "crates/engine" }
texturecraft-render = { path = "crates/render" }
texturecraft-automation = { path = "crates/automation" }
texturecraft-ui-egui = { path = "crates/ui-egui" }
# external
thiserror = "2"
serde = { version = "1", features = ["derive"] }
serde_json = "1"
glam = { version = "0.30", features = ["serde", "bytemuck"] }
bytemuck = { version = "1", features = ["derive"] }
rayon = "1"
log = "0.4"
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "tga", "tiff", "exr", "hdr", "bmp", "webp"] }
half = "2"
exr = { version = "1.73", default-features = false }
eframe = { version = "0.36", default-features = false }
egui = "0.36"
wgpu = "30"
rfd = "0.17"
zip = { version = "2", default-features = false, features = ["deflate"] }
gltf = { version = "1.4", default-features = false, features = ["import", "utils", "names", "KHR_materials_emissive_strength"] }
tobj = { version = "4", default-features = false }
flate2 = "1"
quick-xml = "0.41"
mikktspace = { version = "0.3", default-features = false, features = ["glam"] }
proptest = "1"
rmcp = { version = "3.5", default-features = false, features = ["server", "macros", "transport-io"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "io-std", "sync", "net", "io-util", "time"] }
schemars = "1"
base64 = "0.22"
cap-std = "4"
getrandom = "0.3"
[workspace.lints.rust]
unsafe_code = "forbid"
[workspace.lints.clippy]
dbg_macro = "warn"
todo = "warn"
# Index loops read better than zipped iterators in per-texel code.
needless_range_loop = "allow"
field_reassign_with_default = "allow"
[profile.dev.package."*"]
opt-level = 2
[profile.dev]
opt-level = 1
[profile.release]
lto = "thin"
codegen-units = 1
[profile.wasm-release]
inherits = "release"
opt-level = "s"
lto = "fat"
codegen-units = 1
strip = "debuginfo"
[profile.wasm-release.package."*"]
opt-level = "s"
[profile.wasm-release.package.texturecraft-texel]
opt-level = 3
[profile.wasm-release.package.texturecraft-compose]
opt-level = 3
[profile.wasm-release.package.texturecraft-paint]
opt-level = 3
[profile.wasm-release.package.texturecraft-geom]
opt-level = 3
[profile.wasm-release.package.texturecraft-bake]
opt-level = 3
# Path tracing and the vector math under it run per pixel.
[profile.wasm-release.package.texturecraft-render]
opt-level = 3
[profile.wasm-release.package.glam]
opt-level = 3
+177
View File
@@ -0,0 +1,177 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+16
View File
@@ -0,0 +1,16 @@
TextureCraft
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors.
Licensed under the MIT License or the Apache License, Version 2.0, at your option
(LICENSE-MIT, LICENSE-APACHE).
The ArtCraft name, wordmark and logos in docs/brand/ are trademarks of the ArtCraft Team. They are
not open source and are not covered by the license above; their terms are in
docs/brand/LICENSE-brand.txt.
Third-party material
This product bundles third-party material under its own licenses, listed below. The per-file
list (author, source, license) is in ATTRIBUTION.md.
None: every bundled asset is original to TextureCraft (generated in code or drawn for this
project). See ATTRIBUTION.md.
+278
View File
@@ -0,0 +1,278 @@
<p align="center">
<a href="https://getartcraft.com/">
<picture>
<source media="(prefers-color-scheme: dark)" srcset="docs/brand/artcraft-logo-white.svg">
<img alt="ArtCraft" src="docs/brand/artcraft-logo.svg" width="200">
</picture>
</a>
</p>
<h1 align="center">TextureCraft</h1>
<p align="center">
<b>3D texture painting; an open-source, clean-room reimplementation of Adobe Substance 3D Painter, rebuilt in pure Rust.</b><br>
Paint PBR materials straight onto your models in layers with masks, bake mesh maps,<br>
drive smart materials from them, and export textures for any engine. Open source, offline, and yours.
</p>
<p align="center">
<img alt="100% Rust" src="https://img.shields.io/badge/100%25-Rust-b7410e?style=flat-square&logo=rust">
<img alt="macOS · Windows · Linux · FreeBSD · Web" src="https://img.shields.io/badge/macOS%20%C2%B7%20Windows%20%C2%B7%20Linux%20%C2%B7%20FreeBSD%20%C2%B7%20Web-native-c2672b?style=flat-square">
<img alt="License: MIT OR Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2F%20Apache--2.0-3a3a3a?style=flat-square">
<img alt="Status: early alpha" src="https://img.shields.io/badge/status-early%20alpha-d69e2e?style=flat-square">
</p>
<p align="center">
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
</p>
<p align="center">
<a href="https://getartcraft.com/apps/texturecraft"><b>TextureCraft on getartcraft.com</b></a> ·
<a href="https://getartcraft.com/">ArtCraft</a> ·
<a href="https://getartcraft.com/apps">All Crafting Apps</a>
</p>
<br>
<p align="center">
<img src="docs/images/texturecraft-workspace.png" alt="The TextureCraft workspace: the asset shelf on the left, the 3D viewport with a material ball wearing a painted-steel smart material on a rusted iron base, the 2D UV view, and the texture set list, layer stack and properties on the right" width="100%">
<br>
<sub>The workspace: asset shelf, 3D viewport, 2D UV view, texture sets, layer stack and properties.</sub>
</p>
> [!NOTE]
> **ArtCraft is a community of artists from all walks of life.** Painters, sculptors, game
> artists, photographers, filmmakers, illustrators, designers, hobbyists, and people who picked up
> a stylus last week. If you make things, you belong here. **[Come say hi on Discord](https://discord.gg/artcraft).**
<p align="center">
<a href="#features">Features</a> ·
<a href="#paint-in-3d">Painting</a> ·
<a href="#layers-masks-and-smart-materials">Layers</a> ·
<a href="#bake-and-export">Bake and export</a> ·
<a href="#built-for-agents">Agents</a> ·
<a href="#get-started">Get started</a> ·
<a href="#downloads">Downloads</a> ·
<a href="#the-crafting-apps">Crafting Apps</a> ·
<a href="https://discord.gg/artcraft">Discord</a>
</p>
<br>
<table>
<tr>
<td width="25%" valign="top">
<h3>🎨 Familiar by design</h3>
Texture sets, a layer stack with per-channel blending, masks and generators, the tool shelf, the 3D and 2D views: everything sits where a Painter user expects it.
</td>
<td width="25%" valign="top">
<h3>⚡ Native and fast</h3>
A tiled, copy-on-write texel engine on every CPU core and a wgpu viewport (Vulkan, Metal, DX12, WebGPU). No Electron, no web view, no waiting.
</td>
<td width="25%" valign="top">
<h3>🧵 Seamless by construction</h3>
Brush stamps live on the 3D surface, so strokes flow across UV seams, and the camera's visibility keeps paint off the back of your model.
</td>
<td width="25%" valign="top">
<h3>🤖 Agent-ready</h3>
Every action is a command, so you can drive the same engine from the UI, the CLI, a JSON control channel or an MCP server.
</td>
</tr>
</table>
## Features
### Paint in 3D
- **Brushes** with size, flow, stroke opacity, spacing, hardness, angle and follow path; size,
angle, flow and position jitter; tangent or camera alignment, angle fade, backface culling, lazy
mouse, X/Y/Z mirror symmetry and pen pressure. Seven procedural brush alphas (round, square,
spray, grunge, cloud, star, dry streaks), or any imported image as the alpha.
- **Tools:** paint, eraser, **projection** with image stencils (hold S to move, turn and scale the
stencil), polygon fill (triangle, UV island or the whole mesh), **smudge**, **clone** (V + click
sets the source), color picker, Shift+click straight lines, and painting directly in the
**2D UV view**.
- **Quick mask** (Y): paint a temporary mask (U to edit, Ctrl+Shift+I to invert) that protects
everything outside it while you paint.
- **Every channel at once:** base color, metallic, roughness, height, normal, emissive, opacity,
ambient occlusion and specular level, each toggled per stroke, the way Painter's material
properties work.
### Layers, masks and smart materials
- **Paint, fill and folder layers** with **32 blend modes per channel** (Normal through Normal map
detail), per-channel opacity, visibility, color tags, drag-and-drop reordering, duplicate, group,
flatten, cut, copy and paste across texture sets.
- **Content effects** on any layer: fill, paint, levels, blur, sharpen, invert, threshold and
**HSL**, applied to the layer's channels before it blends. **Anchor points** record the stack at a
layer so masks and fills higher up can react to it (for example, edge detail from painted height).
- **Masks** with a white or black background and a stack of effects: painted strokes, fills,
**mesh-map generators** (edge wear, dirt, thin areas, curvature, AO, position and direction
gradients, all with world-space noise), levels, blur, sharpen, invert, threshold, ID color
selection and compare. Alt+click a mask to view it alone.
- **Fill layers** take uniform values, **procedurals** (clouds, Perlin, noise, cells, grunge,
scratches, checker, stripes, gradient, wood grain, bricks, tiles, fabric weave, leather grain,
hammered, brushed lines, marble veins, Voronoi, streaks, fingerprints, pores, paint chips) or your
own **images**, through UV, tri-planar, planar, spherical or cylindrical projection.
- **43 materials** (metals from measured reflectance, woods, stone and masonry, plastics, fabric,
leather, ceramic, glass), **17 smart materials** (rusted iron, worn and rust-streaked paint,
military paint, oxidized copper, bronze statue, weathered wood, chipped paint, dirty concrete,
mossy brick…) and **10 smart masks** (worn and chipped edges, dirt, dust, ground dirt, rust
leaks, scratches, grunge, paint chips, fingerprints), all procedural, so they work at any
resolution. The shelf groups them in tabs, with search across every tab.
- **Your own library:** right-click a layer or folder, choose *Create smart material*, and it
appears under *My smart materials*, pixels and images included.
### Bake and export
- **Bake mesh maps** on every CPU core: ambient occlusion, curvature, thickness, world-space
normal, position, ID, and normal and height maps from a high poly. A 1024² bake of seven maps on
the material ball takes about 1.5 seconds.
- **Export presets** for glTF PBR Metal Roughness, Unreal Engine (packed), Unity HDRP (mask map),
Unity Standard, Blender (Principled BSDF), separate maps, mesh maps and document channels, in
PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR or HDR at 8, 16 or 32 bits, with UV padding, size
override and OpenGL or DirectX normals.
- **Projects** are a single `.tcraft` file: the mesh, every layer (sparse and lossless), baked maps
and imported images.
### The viewport
- Physically based shading (metallic/roughness or specular/glossiness) with image-based lighting
from six procedural studio and outdoor environments or **your own HDR/EXR panoramas**, exposure,
rotation, blur, ACES or linear tone mapping, key-light shadows, bloom, vignette, sharpen and
grain, parallax occlusion, and temporal anti-aliasing that refines the image while you look.
- **Rendering mode** (F10): a progressive, path-traced view of your textures with multi-bounce
light, environment importance sampling and one-click PNG save.
- View any channel, any baked mesh map, or a UV checker; Alt+drag to orbit, middle-drag to pan,
wheel to zoom, F to frame, M / C / B to cycle views.
## Built for agents
Everything you can do in the window, an agent can do too:
- **CLI:** `texturecraft-cli new builtin:material_ball out.tcraft`, `bake`, `export`, `render`,
`run <command> <params>`, `commands`.
- **MCP server:** `texturecraft-cli mcp` gives Claude and other agents tools to create projects,
add layers and masks, paint strokes, bake, export, render previews and inspect everything they
changed.
- **Control channel:** launch the app with `--control <port>` to drive the running UI: run any
command, invoke menu items, paint, and take screenshots.
See [`docs/control-protocol.md`](docs/control-protocol.md) for the full protocol and examples.
## Get started
You need a recent stable Rust toolchain (1.95 or newer).
```sh
git clone https://github.com/storytold/texturecraft
cd texturecraft
cargo run --release -p texturecraft
```
The app opens with a baked sample project. **File ▸ New project** starts from one of the built-in
meshes or your own glTF, GLB, OBJ, PLY or STL file (UVs are generated if the mesh has none).
Run the tests with `cargo test --workspace --release`. The architecture is described in
[`docs/architecture.md`](docs/architecture.md), the plan and parity estimate in
[`ROADMAP.md`](ROADMAP.md), and contributor rules in [`AGENTS.md`](AGENTS.md).
## Downloads
The easiest way to install TextureCraft is from its page on the ArtCraft website:
**[getartcraft.com/apps/texturecraft](https://getartcraft.com/apps/texturecraft)**.
Technical users can grab builds from GitHub: the
[latest release](https://github.com/storytold/texturecraft/releases/latest) or
[all releases](https://github.com/storytold/texturecraft/releases).
| Windows | File |
|---|---|
| Installer (x64, x86, arm64) | `texturecraft-<version>-windows-<arch>.msi` |
| Portable (x64, x86, arm64) | `texturecraft-<version>-windows-<arch>-portable.zip` |
| macOS | File |
|---|---|
| Universal app (Apple silicon and Intel), signed and notarized | `texturecraft-<version>-macos-universal.dmg` |
| Command-line tools | `texturecraft-cli-<version>-macos-universal.zip` |
| Linux (x86_64, aarch64) | File |
|---|---|
| AppImage (any distribution) | `texturecraft-<version>-linux-<arch>.AppImage` |
| Debian, Ubuntu, Mint, Pop!_OS | `texturecraft-<version>-linux-<arch>.deb` |
| Fedora, openSUSE, RHEL | `texturecraft-<version>-linux-<arch>.rpm` |
| Flatpak bundle | `texturecraft-<version>-linux-<arch>.flatpak` |
| Plain archive | `texturecraft-<version>-linux-<arch>.tar.gz` |
| FreeBSD | File |
|---|---|
| x86_64 | `texturecraft-<version>-freebsd-x86_64.tar.gz` |
| Web (WebAssembly) | File |
|---|---|
| Static site to host or embed | `texturecraft-web-<version>.zip` |
## The Crafting Apps
TextureCraft is one of the **Crafting Apps**: free, open-source creative tools from the
[ArtCraft](https://getartcraft.com/) team, each written from scratch in Rust and each able to
stand on its own.
| | App | What it's for | Code | Learn more |
|:-:|---|---|---|---|
| <img src="https://raw.githubusercontent.com/storytold/texturecraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.texturecraft.png" alt="" width="32" height="32"> | **TextureCraft** | **3D texture painting · you are here** | [GitHub](https://github.com/storytold/texturecraft) | [Website](https://getartcraft.com/apps/texturecraft) |
| <img src="https://raw.githubusercontent.com/storytold/photocraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.photocraft.png" alt="" width="32" height="32"> | **PhotoCraft** | Image editing: layers, masks, type and real PSD files | [GitHub](https://github.com/storytold/photocraft) | [Website](https://getartcraft.com/apps/photocraft) |
| <img src="https://raw.githubusercontent.com/storytold/vectorcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.vectorcraft.png" alt="" width="32" height="32"> | **VectorCraft** | Vector illustration | [GitHub](https://github.com/storytold/vectorcraft) | [Website](https://getartcraft.com/apps/vectorcraft) |
| <img src="https://raw.githubusercontent.com/storytold/filmcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.filmcraft.png" alt="" width="32" height="32"> | **FilmCraft** | Video editing, color and sound | [GitHub](https://github.com/storytold/filmcraft) | [Website](https://getartcraft.com/apps/filmcraft) |
| <img src="https://raw.githubusercontent.com/storytold/lightcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.lightcraft.png" alt="" width="32" height="32"> | **LightCraft** | Photo library and raw development | [GitHub](https://github.com/storytold/lightcraft) | [Website](https://getartcraft.com/apps/lightcraft) |
| <img src="https://raw.githubusercontent.com/storytold/pdfcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.pdfcraft.png" alt="" width="32" height="32"> | **PdfCraft** | Reading, organizing and protecting PDFs | [GitHub](https://github.com/storytold/pdfcraft) | [Website](https://getartcraft.com/apps/pdfcraft) |
| <img src="https://raw.githubusercontent.com/storytold/effectcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.effectcraft.png" alt="" width="32" height="32"> | **EffectCraft** | Motion graphics and visual effects | [GitHub](https://github.com/storytold/effectcraft) | [Website](https://getartcraft.com/apps/effectcraft) |
| <img src="https://raw.githubusercontent.com/storytold/designcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.designcraft.png" alt="" width="32" height="32"> | **DesignCraft** | Page layout and publishing | [GitHub](https://github.com/storytold/designcraft) | [Website](https://getartcraft.com/apps/designcraft) |
| <img src="https://raw.githubusercontent.com/storytold/gridcraft/main/assets/app-icon/hicolor/64x64/apps/ai.storyteller.gridcraft.png" alt="" width="32" height="32"> | **GridCraft** | Spreadsheets and data | [GitHub](https://github.com/storytold/gridcraft) | [Website](https://getartcraft.com/apps/gridcraft) |
And [**ArtCraft**](https://getartcraft.com/) itself, our AI image and video studio for artists who want real control.
<br>
<p align="center">
<a href="https://discord.gg/artcraft"><img alt="Join the ArtCraft community on Discord" src="https://img.shields.io/badge/Join%20us%20on%20Discord-5865F2?style=for-the-badge&logo=discord&logoColor=white" height="40"></a>
</p>
<h3 align="center">Come make things with us</h3>
<p align="center">
Our Discord is where artists of every kind hang out: people who paint, sculpt, model, shoot, draw,
cut film, set type, and people still figuring out what they like to make. Share what you're
working on, ask for help, tell us what's broken, or tell us what you wish these tools could do.
Whatever your medium and however long you've been at it, you're welcome here.
</p>
<p align="center">
<a href="https://discord.gg/artcraft"><b>discord.gg/artcraft</b></a> ·
<a href="https://getartcraft.com/">getartcraft.com</a> ·
<a href="https://getartcraft.com/apps">The Crafting Apps</a> ·
<a href="https://getartcraft.com/apps/texturecraft">TextureCraft</a>
</p>
## License and credits
TextureCraft is dual-licensed under [MIT](LICENSE-MIT) or [Apache-2.0](LICENSE-APACHE), at your option.
Copyright (c) 2026 ArtCraft Team and the TextureCraft contributors. Required notices are in [NOTICE](NOTICE).
Bundled fonts, icons, images and other assets keep their own open licenses; each one is listed
with its author, source and license in [ATTRIBUTION.md](ATTRIBUTION.md).
Every material, environment, brush alpha and mesh shown is generated procedurally by TextureCraft
itself; no third-party textures or models appear in the screenshots.
The ArtCraft name, wordmark and logos in [`docs/brand/`](docs/brand/) are trademarks of the
ArtCraft Team and are not covered by this license. They may be used only unmodified, and only as
part of this repository and TextureCraft, under [`docs/brand/LICENSE-brand.txt`](docs/brand/LICENSE-brand.txt).
Forks and modified versions must remove them.
<sub>Adobe, Substance 3D Painter, Photoshop, Illustrator, Premiere Pro, Lightroom, Acrobat, After Effects and InDesign are trademarks or registered trademarks of Adobe Inc. in the United States and/or other countries. TextureCraft is an independent, open-source project and is not affiliated with, sponsored by or endorsed by Adobe Inc.; these names are used only to describe the workflows it is compatible with.</sub>
<p align="center">
<a href="https://getartcraft.com/"><img alt="ArtCraft" src="docs/brand/artcraft-mark.svg" width="28"></a><br>
<sub>Made by the <a href="https://getartcraft.com/">ArtCraft</a> team and community.</sub>
</p>
+52
View File
@@ -0,0 +1,52 @@
# TextureCraft roadmap
TextureCraft aims for 1:1 parity with Adobe Substance 3D Painter's texturing workflow, with better
performance, a smaller footprint, every feature drivable by agents (MCP, CLI, control channel), and
builds for Windows, macOS, Linux, FreeBSD and the web.
## Honest parity estimate (2026-10-14)
Weighted by how much of a professional's daily work each area carries. "Done" counts what works
end to end today (engine + UI + automation + tests), not what is planned.
| Area | Weight | Done | What works | Main gaps |
|---|---:|---:|---|---|
| Project and files | 8 | 75% | New project from glTF/GLB, FBX (binary and ASCII 7.x), COLLADA, OBJ, PLY, STL or built-in meshes (auto-unwrap when UVs are missing), `.tcraft` open/save/save as/save a copy, autosave, recent files, drag and drop (projects, meshes, images), reimport mesh, image resources, remove unused resources, OBJ and textured GLB mesh export, browser open/save/download | USD, Alembic import; FBX 6; project templates; preserving strokes on reimport |
| Texture sets | 6 | 62% | One set per material, list with visibility, sizes 128–8192 with resampling, add/remove channels (11 channel types incl. specular and glossiness), height strength, normal format | UDIM / UV tiles, per-channel bit depth, normal and AO mixing options, UV padding modes |
| Layer stack | 16 | 75% | Paint, fill and folder layers; 32 per-channel blend modes and opacities; white/black/painted masks; generator, fill, levels, invert/threshold, color selection, compare, blur, sharpen and HSL effects on masks **and layer content**; anchor points read by masks and fills above; smart masks; mask view (Alt+click); duplicate, group, drag to reorder, rename, color tags, copy/cut/paste across sets, flatten, instantiate across sets, save layers as smart materials and add them back | Instance layers, mask with height combination, anchor position inside a content stack |
| Painting tools | 14 | 68% | Paint, eraser, projection with image stencils, polygon fill (triangle, UV island, mesh), smudge, clone, color picker, quick mask, Shift+click lines, 2D view painting; size, flow, stroke opacity, spacing, hardness, angle, follow path, jitters, alignment, angle fade, backface culling, lazy mouse, X/Y/Z symmetry, pen pressure, 7 procedural alphas and image alphas, seam-free 3D stamps with camera visibility | Pen tilt, path / filled path / ribbon tools, particle brushes, geometry decals, clone from the current layer only |
| Materials and assets | 8 | 55% | 43 built-in procedural materials, 17 smart materials, 10 smart masks (`mask.smart.apply`), 22 procedurals, 6 environments plus imported HDR/EXR panoramas, image resources, a user smart material library, a tabbed shelf with search across tabs | Filter and alpha libraries; drag from shelf onto layers (Substance `.sbsar` support is a non-goal: the engine is proprietary) |
| Baking | 10 | 60% | AO, curvature, thickness, world normal, position, ID, normal and height from high poly (engine), resolution, antialiasing, dilation, rays, progress and cancel, bake mode UI | High-poly / cage UI, match by name, bent normals, opacity and color transfer, curvature from normal map, GPU ray-traced baking |
| Viewport and display | 12 | 72% | PBR with image-based lighting, 6 procedural environments or imported HDR/EXR panoramas with exposure, rotation, blur, opacity, ACES/linear tone mapping, HDR pipeline with bloom, vignette, sharpen and grain, key-light shadows, 4× MSAA plus idle temporal accumulation, channel / mesh-map / mask / UV checker views, 3D and 2D wireframes, brush cursor, axis gizmos, **path-traced Rendering mode** (F10) with environment importance sampling | Subsurface scattering, depth of field, multiple cameras, GPU path tracing |
| Shader | 6 | 45% | Metallic/roughness and specular/glossiness PBR, height-to-normal, painted normals, parallax occlusion, emissive, opacity (dithered), AO intensity | OpenPBR features (coat, sheen, subsurface, anisotropy, thin film), tessellated displacement |
| Export | 8 | 70% | 8 presets (glTF, Unreal, Unity HDRP/Standard, Blender, separate maps, mesh maps, document channels), PNG/JPEG/TGA/TIFF/BMP/WEBP/EXR/HDR, 8/16/32-bit, padding modes, size override, OpenGL/DirectX normals, template file names, OBJ and textured GLB mesh export, zip download in the browser | Output template editor, USD export |
| UI and UX | 8 | 65% | Painter-style layout: menus, tool shelf, tool bar, asset shelf, texture set list, layer stack with context menu, properties, display/shader/history windows, export dialog, new project dialog, bake mode, rendering mode, settings (interface scale, autosave), saved UI layouts; all 51 menu items live ([docs/parity.md](docs/parity.md)) | Docking, shortcut editor, localization, tooltips everywhere |
| Platforms | 4 | 60% | Windows, macOS (universal, signed and notarized), Linux (AppImage, deb, rpm, tar.gz, Flatpak), FreeBSD and web release workflows | First real release run; web build polish |
| **Total** | **100** | **≈ 65%** | | |
Beyond Painter: every command is available to agents through MCP, the CLI and the app's
control channel, and the whole engine runs headless.
## Remaining effort
Estimated in wall-clock hours of Claude Opus 5.5 agent work, with three or four agents working in
parallel on separate crates:
| Milestone | Scope | Estimate |
|---|---|---:|
| M1 Layer stack depth | Instance layers, height-combined masks | 3 h |
| M2 Tools | Path, filled-path and ribbon tools, particle brushes, decals, pen tilt | 6 h |
| M3 Assets | Filter and alpha libraries, shelf drag and drop | 5 h |
| M4 Baking | High-poly and cage UI, match by name, bent normals, transfers, GPU ray-traced baking | 8 h |
| M5 Viewport | SSS, depth of field, cameras, GPU path tracing | 6 h |
| M6 Shader | OpenPBR lobes (coat, sheen, subsurface, anisotropy), displacement | 4 h |
| M7 Formats | USD, Alembic import; USD export; output template editor; UDIM | 8 h |
| M8 UX | Docking, shortcut editor, localization, performance passes at 4K/8K | 6 h |
| M9 Release | First signed release on every platform, web deployment, README screenshots refresh | 4 h |
| **Total** | | **≈ 50 h** |
## Current focus
1. Baking (M4): high-poly and cage UI, match by name, bent normals, transfers.
2. Tools (M2): path, filled-path and ribbon tools; particle brushes.
3. UX (M8): docking and a shortcut editor; release (M9) once the repository exists.
+22
View File
@@ -0,0 +1,22 @@
[package]
name = "texturecraft-cli"
description = "Headless TextureCraft: info, run, batch, bake, export, render, MCP server, JSON-lines server"
version.workspace = true
edition.workspace = true
license.workspace = true
build = "build.rs"
[lints]
workspace = true
[dependencies]
texturecraft-automation = { workspace = true }
texturecraft-engine = { workspace = true }
serde_json = { workspace = true }
tokio = { workspace = true }
[dev-dependencies]
image = { workspace = true }
[build-dependencies]
winresource = "0.1"
+2
View File
@@ -0,0 +1,2 @@
// The same build provenance and Windows icon/VERSIONINFO as the app; see that file.
include!("../texturecraft/build.rs");
+403
View File
@@ -0,0 +1,403 @@
//! Headless TextureCraft command line: inspect, script, bake, export and render projects, and
//! serve agents over MCP or JSON lines. Never opens a window.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
use std::path::Path;
use std::sync::{Arc, Mutex};
use serde_json::{Value, json};
use texturecraft_automation::security::{client_token, server_token};
use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, RenderOptions, TexturecraftMcp, rpc};
use texturecraft_engine::core::PROJECT_EXT;
use texturecraft_engine::formats::{MeshReport, import_mesh_bytes};
const USAGE: &str = "\
texturecraft-cli: headless TextureCraft
USAGE:
texturecraft-cli --version
texturecraft-cli info <project.tcraft | mesh file>
Texture sets, layers, triangles, materials and the UV report, as JSON.
texturecraft-cli commands [--filter <text>]
List the engine commands (id, label, params).
texturecraft-cli run <input> <command-id> [params-json] [-o <out.tcraft>]
Run one command and print its JSON result; -o saves the project.
texturecraft-cli batch <script.json>
Run [{\"id\", \"params\"}, ...] or {\"open\": <input>, \"steps\": [...], \"save\": <out.tcraft>}.
texturecraft-cli bake <input> [-o <out.tcraft>] [--resolution <px>] [--maps <id,id,...>]
Bake mesh maps for every texture set (a project is saved in place without -o).
texturecraft-cli export <input> <dir> [--preset <name>] [--format <ext>] [--padding <mode>] [--size <px>]
Export textures (default preset: Document channels + Normal + AO).
texturecraft-cli render <input> <out.png> [--size <W>x<H>] [--view 3d|2d] [--yaw <deg>] [--pitch <deg>]
[--samples <n>] [--bounces <n>]
Render the viewport to PNG (needs a GPU or software adapter); --samples path traces it on
the CPU instead (Rendering mode).
texturecraft-cli new <mesh file | builtin:<id>> <out.tcraft> [--resolution <px>] [--sample]
New project; --sample bakes and applies a smart material to every texture set.
texturecraft-cli mcp [--bridge <port>] [--token <token>] [--read-root <dir>] [--write-root <dir>]
MCP server on stdio: headless (file access only below the roots), or bridged to
`texturecraft --control <port>`.
texturecraft-cli serve [--port <port>] [--read-root <dir>] [--write-root <dir>]
JSON lines ({\"id\",\"method\",\"params\"}) on stdio, or on 127.0.0.1:<port> with a token.
<input> is a .tcraft project, a mesh file (.glb .gltf .fbx .dae .obj .ply .stl) or builtin:<id>
(material_ball, sphere, cube, rounded_cube, cylinder, torus, plane, crate).
See docs/control-protocol.md.
";
/// (name, flags taking a value, bare flags)
const SUBCOMMANDS: &[(&str, &[&str], &[&str])] = &[
("info", &[], &[]),
("commands", &["--filter"], &[]),
("run", &["-o"], &[]),
("batch", &[], &[]),
("bake", &["-o", "--resolution", "--maps"], &[]),
("export", &["--preset", "--format", "--padding", "--size"], &[]),
("render", &["--size", "--view", "--yaw", "--pitch", "--samples", "--bounces"], &[]),
("new", &["--resolution"], &["--sample"]),
("mcp", &["--bridge", "--token", "--read-root", "--write-root"], &[]),
("serve", &["--port", "--read-root", "--write-root"], &[]),
];
struct Args {
pos: Vec<String>,
flags: Vec<(String, Option<String>)>,
}
impl Args {
fn get(&self, k: &str) -> Option<&str> {
self.flags.iter().rev().find(|(f, _)| f == k).and_then(|(_, v)| v.as_deref())
}
fn has(&self, k: &str) -> bool {
self.flags.iter().any(|(f, _)| f == k)
}
fn num<T: std::str::FromStr>(&self, k: &str) -> Result<Option<T>, String> {
self.get(k).map(|v| v.parse().map_err(|_| format!("{k}: `{v}` is not a valid number"))).transpose()
}
fn pos(&self, n: usize, what: &str) -> Result<&str, String> {
self.pos.get(n).map(String::as_str).ok_or_else(|| format!("missing {what}"))
}
}
fn parse(values: &[&str], bare: &[&str], args: &[String]) -> Result<Args, String> {
let mut a = Args { pos: Vec::new(), flags: Vec::new() };
let mut it = args.iter();
while let Some(s) = it.next() {
let (k, inline) = match s.split_once('=') {
Some((k, v)) if k.starts_with("--") => (k, Some(v.to_string())),
_ => (s.as_str(), None),
};
if values.contains(&k) {
let v = match inline {
Some(v) => v,
None => it.next().ok_or_else(|| format!("{k} needs a value"))?.clone(),
};
a.flags.push((k.to_string(), Some(v)));
} else if bare.contains(&k) && inline.is_none() {
a.flags.push((k.to_string(), None));
} else if k.starts_with('-') && k.len() > 1 && k.parse::<f64>().is_err() {
return Err(format!("unknown option `{s}`"));
} else {
a.pos.push(s.clone());
}
}
Ok(a)
}
fn version() -> String {
let sha = env!("TEXTURECRAFT_BUILD_SHA");
let short = sha.get(..7).unwrap_or(sha);
let date = env!("TEXTURECRAFT_BUILD_DATE");
match (short.is_empty(), date.is_empty()) {
(true, true) => format!("TextureCraft {}", texturecraft_engine::VERSION),
(true, false) => format!("TextureCraft {} ({date})", texturecraft_engine::VERSION),
_ => format!("TextureCraft {} ({short} {date})", texturecraft_engine::VERSION),
}
}
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
let code = match args.first().map(String::as_str) {
None => {
eprint!("{USAGE}");
2
}
Some("--version" | "-V" | "version") => {
println!("{}", version());
0
}
Some("--help" | "-h" | "help") => {
print!("{USAGE}");
0
}
Some(cmd) => match SUBCOMMANDS.iter().find(|(n, _, _)| *n == cmd) {
None => {
eprintln!("texturecraft-cli: unknown command `{cmd}`\n\n{USAGE}");
2
}
Some(_) if args.iter().any(|a| a == "--help" || a == "-h") => {
print!("{USAGE}");
0
}
Some((name, values, bare)) => match parse(values, bare, args.get(1..).unwrap_or_default()) {
Err(e) => {
eprintln!("texturecraft-cli {name}: {e}\n\n{USAGE}");
2
}
Ok(a) => match dispatch(name, &a) {
Ok(()) => 0,
Err(e) => {
eprintln!("texturecraft-cli {name}: error: {e}");
1
}
},
},
},
};
std::process::exit(code);
}
type R = Result<(), String>;
fn dispatch(name: &str, a: &Args) -> R {
match name {
"info" => info(a),
"commands" => commands(a),
"run" => run(a),
"batch" => batch(a),
"bake" => bake(a),
"export" => export(a),
"render" => render(a),
"new" => new(a),
"mcp" => mcp(a),
"serve" => serve(a),
other => Err(format!("unknown command `{other}`")),
}
}
fn s(e: impl std::fmt::Display) -> String {
e.to_string()
}
fn print_json(v: &Value) -> R {
println!("{}", serde_json::to_string_pretty(v).map_err(s)?);
Ok(())
}
fn is_project(path: &str) -> bool {
Path::new(path).extension().is_some_and(|e| e.eq_ignore_ascii_case(PROJECT_EXT))
}
/// A trusted local session on `input`: a project, a mesh file or `builtin:<id>`.
fn open(input: &str, resolution: Option<u32>) -> Result<Headless, String> {
let mut h = Headless::new(Headless::default_session().map_err(s)?, Filesystem::TrustedLocal);
match input.strip_prefix("builtin:") {
Some(id) => h.command_run("project.new", json!({"mesh": id, "resolution": resolution.unwrap_or(1024), "name": id})).map(|_| ()),
None if is_project(input) => h.open(input).map(|_| ()),
None => h.import_mesh(input, resolution, None).map(|_| ()),
}
.map_err(s)?;
Ok(h)
}
fn save(h: &mut Headless, out: &str) -> R {
let r = h.save(Some(out)).map_err(s)?;
eprintln!("saved {}", r["path"].as_str().unwrap_or_default());
Ok(())
}
fn report_json(r: &MeshReport) -> Value {
json!({
"triangles": r.triangles, "vertices": r.vertices, "materials": r.materials, "uvsGenerated": r.uvs_generated,
"uvOutOfRange": r.uv_out_of_range, "overlapRatio": r.overlap_ratio, "zeroAreaUvTriangles": r.zero_area_uv_triangles, "warnings": r.warnings,
})
}
fn info(a: &Args) -> R {
let file = a.pos(0, "<file>")?;
if !is_project(file) {
let bytes = std::fs::read(file).map_err(|e| format!("cannot read {file}: {e}"))?;
let m = import_mesh_bytes(file, &bytes).map_err(s)?;
return print_json(&json!({
"file": file, "kind": "mesh", "triangles": m.mesh.triangle_count(), "vertices": m.mesh.vertex_count(),
"materials": m.mesh.materials, "textureSets": m.mesh.materials, "uv": report_json(&m.report),
}));
}
let h = open(file, None)?;
let mut v = h.inspect();
v["file"] = json!(file);
v["kind"] = json!("project");
// The embedded mesh is re-imported for its UV report (built-in meshes have none).
v["uv"] = match &h.session.mesh_source {
Some((ext, bytes)) => import_mesh_bytes(&format!("mesh.{ext}"), bytes).map(|m| report_json(&m.report)).map_err(s)?,
None => Value::Null,
};
print_json(&v)
}
fn commands(a: &Args) -> R {
let h = open("builtin:cube", Some(128))?;
for c in h.command_list(a.get("--filter")).as_array().into_iter().flatten() {
let f = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or_default().to_string();
println!("{:<28} {:<36} {}", f("id"), f("label"), f("params"));
}
Ok(())
}
fn run(a: &Args) -> R {
let (input, id) = (a.pos(0, "<input>")?, a.pos(1, "<command-id>")?);
let params: Value = match a.pos.get(2) {
Some(j) => serde_json::from_str(j).map_err(|e| format!("params are not JSON: {e}"))?,
None => json!({}),
};
let mut h = open(input, None)?;
print_json(&h.command_run(id, params).map_err(s)?)?;
match a.get("-o") {
Some(out) => save(&mut h, out),
None => Ok(()),
}
}
fn batch(a: &Args) -> R {
let path = a.pos(0, "<script.json>")?;
let text = std::fs::read_to_string(path).map_err(|e| format!("cannot read {path}: {e}"))?;
let script: Value = serde_json::from_str(&text).map_err(|e| format!("{path} is not JSON: {e}"))?;
let steps =
script.as_array().or_else(|| script.get("steps").and_then(Value::as_array)).ok_or("the script must be a list of steps or {\"steps\": [...]}")?;
let field = |k: &str| script.get(k).and_then(Value::as_str);
let mut h = open(field("open").unwrap_or("builtin:material_ball"), None)?;
let reply = h.batch(steps);
print_json(&reply)?;
if let Some(f) = reply.get("failed").filter(|f| !f.is_null()) {
return Err(format!("step {} (`{}`) failed: {}", f["index"], f["id"].as_str().unwrap_or_default(), f["error"].as_str().unwrap_or_default()));
}
match field("save") {
Some(out) => save(&mut h, out),
None => Ok(()),
}
}
fn bake(a: &Args) -> R {
let input = a.pos(0, "<input>")?;
let out = a.get("-o").or(is_project(input).then_some(input)).ok_or("give -o <out.tcraft> to save the baked project")?;
let mut p = json!({"ts": "all"});
if let Some(r) = a.num::<u32>("--resolution")? {
p["resolution"] = json!(r);
}
if let Some(m) = a.get("--maps") {
p["maps"] = json!(m.split(',').map(str::trim).filter(|m| !m.is_empty()).collect::<Vec<_>>());
}
let mut h = open(input, None)?;
h.command_run("bake.run", p).map_err(s)?;
save(&mut h, out)?;
print_json(&h.inspect()["textureSets"])
}
fn export(a: &Args) -> R {
let (input, dir) = (a.pos(0, "<input>")?, a.pos(1, "<dir>")?);
let mut p = json!({"dir": dir});
for k in ["preset", "format", "padding"] {
if let Some(v) = a.get(&format!("--{k}")) {
p[k] = json!(v);
}
}
if let Some(v) = a.num::<u32>("--size")? {
p["size"] = json!(v);
}
let mut h = open(input, None)?;
let r = h.export(&p).map_err(s)?;
for w in r["warnings"].as_array().into_iter().flatten() {
eprintln!("warning: {}", w.as_str().unwrap_or_default());
}
for f in r["files"].as_array().into_iter().flatten() {
println!("{}", f.as_str().unwrap_or_default());
}
Ok(())
}
fn render(a: &Args) -> R {
let (input, out) = (a.pos(0, "<input>")?, a.pos(1, "<out.png>")?);
let (width, height) = match a.get("--size") {
Some(sz) => {
let (w, h) = sz.split_once(['x', 'X']).ok_or("--size must be <W>x<H>, e.g. 1280x800")?;
(Some(w.parse().map_err(|_| "bad --size width")?), Some(h.parse().map_err(|_| "bad --size height")?))
}
None => (None, None),
};
let o = RenderOptions {
view: a.get("--view").map(str::to_string),
width,
height,
yaw: a.num("--yaw")?,
pitch: a.num("--pitch")?,
samples: a.num("--samples")?,
bounces: a.num("--bounces")?,
};
let mut h = open(input, None)?;
let (w, ht, png) = h.render_png(&o).map_err(s)?;
std::fs::write(out, png).map_err(|e| format!("cannot write {out}: {e}"))?;
let by = if o.samples.is_some() { "path traced" } else { h.adapter().unwrap_or("GPU") };
eprintln!("wrote {out} ({w}x{ht}, {by})");
Ok(())
}
fn new(a: &Args) -> R {
let (input, out) = (a.pos(0, "<mesh | builtin:id>")?, a.pos(1, "<out.tcraft>")?);
if is_project(input) {
return Err(format!("{input} is already a project"));
}
let res = a.num::<u32>("--resolution")?;
let mut h = open(input, res)?;
if a.has("--sample") {
let bake_res = h.session.doc.project.texture_sets.first().map_or(1024, |t| t.resolution.min(1024));
h.command_run("bake.run", json!({"ts": "all", "resolution": bake_res})).map_err(s)?;
for ts in 0..h.session.set_count() {
h.command_run("textureSet.select", json!({"ts": ts})).map_err(s)?;
h.command_run("material.apply", json!({"material": "steel_painted_worn"})).map_err(s)?;
}
h.command_run("textureSet.select", json!({"ts": 0})).map_err(s)?;
}
save(&mut h, out)
}
fn workspace(a: &Args) -> Result<Filesystem, String> {
let (r, w) = (a.get("--read-root").map(Path::new), a.get("--write-root").map(Path::new));
if r.is_none() && w.is_none() {
return Ok(Filesystem::Denied);
}
Ok(Filesystem::Workspace(AuthorizedWorkspace::new(r, w).map_err(s)?))
}
fn port_of(v: &str) -> Result<u16, String> {
let p = v.strip_prefix("127.0.0.1:").or_else(|| v.strip_prefix("localhost:")).unwrap_or(v);
p.parse::<u16>().ok().filter(|p| *p != 0).ok_or_else(|| format!("`{v}` is not a loopback port (1-65535)"))
}
fn mcp(a: &Args) -> R {
let server = match a.get("--bridge") {
Some(b) => {
let port = port_of(b)?;
TexturecraftMcp::bridge(BridgeClient::new(port, client_token(port, a.get("--token").map(str::to_string)).map_err(s)?))
}
None => TexturecraftMcp::headless(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?)),
};
let rt = tokio::runtime::Builder::new_multi_thread().enable_all().build().map_err(s)?;
rt.block_on(server.serve_stdio()).map_err(s)
}
fn serve(a: &Args) -> R {
let h = Arc::new(Mutex::new(Headless::new(Headless::default_session().map_err(s)?, workspace(a)?)));
match a.get("--port") {
None => rpc::serve_lines(&h, std::io::stdin().lock(), std::io::stdout().lock()).map_err(s),
Some(p) => {
let port = port_of(p)?;
let (token, file) = server_token(port).map_err(s)?;
rpc::serve_tcp(port, h, token, |addr| match file {
Some(f) => eprintln!("texturecraft-cli: serving on {addr}; token in {}", f.display()),
None => eprintln!("texturecraft-cli: serving on {addr}; token from TEXTURECRAFT_CONTROL_TOKEN"),
})
.map_err(s)
}
}
}
+129
View File
@@ -0,0 +1,129 @@
//! Drives the `texturecraft-cli` binary.
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use serde_json::Value;
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_texturecraft-cli")).args(args).output().unwrap()
}
fn ok(args: &[&str]) -> String {
let o = cli(args);
assert!(o.status.success(), "{args:?} failed: {}", String::from_utf8_lossy(&o.stderr));
String::from_utf8(o.stdout).unwrap()
}
fn json(args: &[&str]) -> Value {
serde_json::from_str(&ok(args)).unwrap()
}
fn tmp(name: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("tc-cli-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn p(path: &Path) -> &str {
path.to_str().unwrap()
}
#[test]
fn version_and_usage_errors() {
let v = ok(&["--version"]);
assert!(v.starts_with("TextureCraft "), "{v}");
assert_eq!(v.lines().count(), 1);
assert!(ok(&["--help"]).contains("texturecraft-cli mcp"));
assert_eq!(cli(&[]).status.code(), Some(2));
assert_eq!(cli(&["frobnicate"]).status.code(), Some(2));
assert_eq!(cli(&["info", "--bogus"]).status.code(), Some(2));
let o = cli(&["info", "does/not/exist.tcraft"]);
assert_eq!(o.status.code(), Some(1));
assert!(String::from_utf8_lossy(&o.stderr).contains("error"));
assert_eq!(cli(&["run", "builtin:nope", "layer.add.fill"]).status.code(), Some(1));
assert_eq!(cli(&["run", "builtin:cube", "layer.add.fill", "{not json"]).status.code(), Some(1));
assert_eq!(cli(&["render", "builtin:cube", "x.png", "--size", "big"]).status.code(), Some(1));
}
#[test]
fn new_info_run_bake_export_batch() {
let d = tmp("flow");
let a = d.join("a.tcraft");
ok(&["new", "builtin:cube", p(&a), "--resolution", "128"]);
let info = json(&["info", p(&a)]);
assert_eq!(info["kind"], "project");
assert_eq!(info["textureSets"][0]["resolution"], 128);
assert!(info["mesh"]["triangles"].as_u64().unwrap() >= 12);
let b = d.join("b.tcraft");
let r = json(&["run", p(&a), "layer.add.fill", r#"{"color":[1,0,0],"roughness":0.3}"#, "-o", p(&b)]);
assert!(r["layer"].is_u64(), "{r}");
assert_eq!(json(&["info", p(&b)])["layers"][0]["kind"], "fill");
ok(&["bake", p(&b), "--resolution", "128", "--maps", "ambientOcclusion,curvature"]);
let maps = json(&["info", p(&b)])["textureSets"][0]["baked"]["maps"].clone();
assert_eq!(maps.as_array().unwrap().len(), 2, "{maps}");
let tex = d.join("tex");
let files = ok(&["export", p(&b), p(&tex), "--preset", "glTF PBR Metal Roughness", "--size", "128"]);
assert!(files.lines().count() >= 3, "{files}");
for f in files.lines() {
assert!(Path::new(f).is_file(), "{f}");
}
let script = d.join("script.json");
let c = d.join("c.tcraft");
let body = serde_json::json!({"open": p(&b), "steps": [{"id": "layer.add.paint", "params": {"name": "Scripted"}}], "save": p(&c)});
std::fs::write(&script, body.to_string()).unwrap();
assert_eq!(json(&["batch", p(&script)])["completed"], 1);
assert_eq!(json(&["info", p(&c)])["layers"][0]["name"], "Scripted");
std::fs::write(&script, r#"[{"id":"layer.add.paint"},{"id":"no.such"}]"#).unwrap();
assert_eq!(cli(&["batch", p(&script)]).status.code(), Some(1));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn info_on_a_mesh_reports_uvs() {
let d = tmp("mesh");
let obj = d.join("quad.obj");
std::fs::write(&obj, "v 0 0 0\nv 1 0 0\nv 1 1 0\nv 0 1 0\nvt 0 0\nvt 1 0\nvt 1 1\nvt 0 1\nusemtl Paint\nf 1/1 2/2 3/3 4/4\n").unwrap();
let info = json(&["info", p(&obj)]);
assert_eq!(info["kind"], "mesh");
assert_eq!(info["triangles"], 2);
assert_eq!(info["materials"][0], "Paint");
assert_eq!(info["uv"]["uvsGenerated"], false);
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn render_writes_a_png() {
let d = tmp("render");
let out = d.join("ball.png");
let o = cli(&["render", "builtin:material_ball", p(&out), "--size", "160x120", "--yaw", "30"]);
if !o.status.success() {
let err = String::from_utf8_lossy(&o.stderr);
assert!(err.contains("cannot render"), "{err}");
eprintln!("skipping: {err}");
return;
}
let img = image::open(&out).unwrap();
assert_eq!((img.width(), img.height()), (160, 120));
let _ = std::fs::remove_dir_all(&d);
}
#[test]
fn path_traced_render_needs_no_gpu() {
let d = tmp("trace");
let out = d.join("ball.png");
ok(&["render", "builtin:material_ball", p(&out), "--size", "96x64", "--samples", "4"]);
let img = image::open(&out).unwrap().to_rgb8();
assert_eq!(img.dimensions(), (96, 64));
// The lit ball in the middle is brighter than the dark backdrop corner.
let lum = |x, y| img.get_pixel(x, y).0.iter().map(|v| *v as u32).sum::<u32>();
assert!(lum(48, 28) > lum(1, 1) + 60);
assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "0"]).status.code(), Some(1));
assert_eq!(cli(&["render", "builtin:cube", p(&out), "--samples", "4", "--view", "2d"]).status.code(), Some(1));
let _ = std::fs::remove_dir_all(&d);
}
+26
View File
@@ -0,0 +1,26 @@
[package]
name = "texturecraft-web"
description = "TextureCraft in the browser (eframe web runner, WebGPU with WebGL2 fallback)"
version.workspace = true
edition.workspace = true
license.workspace = true
publish = false
[lints]
workspace = true
[[bin]]
name = "texturecraft-web"
path = "src/main.rs"
[dependencies]
texturecraft-engine = { workspace = true }
texturecraft-ui-egui = { workspace = true }
log = { workspace = true }
[target.'cfg(target_arch = "wasm32")'.dependencies]
# `wgpu` pulls egui-wgpu's defaults: WebGPU plus the WebGL2 fallback.
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "persistence"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlCanvasElement", "Location"] }
+10
View File
@@ -0,0 +1,10 @@
# Build with: trunk build --release (from apps/texturecraft-web; packaging/web/package.sh)
[build]
target = "index.html"
dist = "../../dist/web"
public_url = "./"
filehash = true
[serve]
addresses = ["127.0.0.1"]
port = 8765
+30
View File
@@ -0,0 +1,30 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<title>TextureCraft</title>
<link data-trunk rel="rust" data-bin="texturecraft-web" data-cargo-profile="wasm-release" data-wasm-opt="z" data-weak-refs />
<style>
html, body { margin: 0; padding: 0; width: 100%; height: 100%; overflow: hidden; background: #1c1c1c; }
#texturecraft_canvas { position: absolute; inset: 0; width: 100%; height: 100%; display: block; }
#texturecraft_loading { position: absolute; inset: 0; display: flex; flex-direction: column; align-items: center; justify-content: center;
padding: 0 16px; text-align: center; color: #b8b8b8; font: 14px system-ui, sans-serif; pointer-events: none; }
#texturecraft_loading p { margin: 0 0 8px; max-width: 420px; line-height: 1.5; }
#texturecraft_loading a { color: #e0e0e0; pointer-events: auto; }
/* The app removes this element once it runs. If the WebAssembly never downloads or doesn't match
this page, no Rust runs to say so, so the page itself shows what to do after a while. */
#texturecraft_stalled { color: #8c8c8c; visibility: hidden; animation: texturecraft-stalled 0s 30s forwards; }
@keyframes texturecraft-stalled { to { visibility: visible; } }
</style>
</head>
<body>
<canvas id="texturecraft_canvas"></canvas>
<div id="texturecraft_loading">
<p>Loading TextureCraft&hellip;</p>
<p id="texturecraft_stalled">This is taking longer than usual. If TextureCraft doesn't start, its files may have failed to
download or come from a different version of this page. <a href="">Reload</a> to try again; the browser
console lists what failed.</p>
</div>
</body>
</html>
+41
View File
@@ -0,0 +1,41 @@
//! TextureCraft in the browser.
//!
//! Runs the same [`texturecraft_ui_egui::TextureCraftApp`] as the desktop app through eframe's web
//! runner (wgpu: WebGPU where available, WebGL2 otherwise). Build with `trunk build --release`
//! from this directory (`packaging/web/package.sh` zips the result).
//!
//! Differences from the desktop app: no control server (browsers can't listen on sockets), and
//! file I/O goes through `texturecraft_ui_egui::web_files` (file picker in, downloads out).
//!
//! URL query flag: `?webgl` forces the WebGL2 backend instead of WebGPU.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(target_arch = "wasm32")]
mod web;
#[cfg(target_arch = "wasm32")]
fn main() {
web::start();
}
#[cfg(not(target_arch = "wasm32"))]
fn main() {
eprintln!("texturecraft-web only runs in the browser: build it with `trunk build --release` in apps/texturecraft-web");
}
#[cfg(test)]
mod tests {
/// A WebAssembly module that never downloads runs no Rust, so the page itself replaces the
/// endless "Loading" with a way to retry, without a hand-written script.
#[test]
fn loading_page_offers_a_reload_when_startup_stalls() {
let html = include_str!("../index.html");
let (_, hint) = html.split_once("<p id=\"texturecraft_stalled\">").expect("stalled-startup hint in the loading element");
assert!(hint.contains("failed to") && hint.contains("<a href=\"\">Reload</a>"), "{hint}");
assert!(html.contains("animation: texturecraft-stalled"), "the hint appears after a delay");
assert!(html.contains("id=\"texturecraft_canvas\"") && html.contains("data-cargo-profile=\"wasm-release\""));
assert!(!html.contains("<script"), "trunk injects the generated loader; the page has no script of its own");
}
}
+69
View File
@@ -0,0 +1,69 @@
//! The eframe web runner: canvas lookup, backend selection and startup errors shown in the page.
use texturecraft_engine::Session;
use texturecraft_ui_egui::TextureCraftApp;
use wasm_bindgen::JsCast as _;
const CANVAS_ID: &str = "texturecraft_canvas";
const LOADING_ID: &str = "texturecraft_loading";
pub fn start() {
eframe::WebLogger::init(log::LevelFilter::Info).ok();
wasm_bindgen_futures::spawn_local(async {
let Some(document) = web_sys::window().and_then(|w| w.document()) else {
log::error!("no document");
return;
};
let result = match document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) {
Some(canvas) => run(canvas).await,
None => Err(format!("the page has no <canvas id=\"{CANVAS_ID}\">")),
};
if let Some(el) = document.get_element_by_id(LOADING_ID) {
match result {
Ok(()) => el.remove(),
Err(e) => {
log::error!("TextureCraft failed to start: {e}");
el.set_text_content(Some(&format!("TextureCraft failed to start: {e}. It needs a browser with WebGPU or WebGL2.")));
}
}
}
});
}
async fn run(canvas: web_sys::HtmlCanvasElement) -> Result<(), String> {
let mut options = eframe::WebOptions::default();
if query().contains("webgl")
&& let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
{
create.instance_descriptor.backends = eframe::wgpu::Backends::GL;
}
eframe::WebRunner::new()
.start(
canvas,
options,
Box::new(|cc| {
if let Some(rs) = &cc.wgpu_render_state {
log::info!("TextureCraft: wgpu backend {:?}", rs.adapter.get_info().backend);
}
Ok(Box::new(TextureCraftApp::new(cc, initial_session()?)))
}),
)
.await
.map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))
}
/// The baked sample project, or an empty material ball if that fails. Texture and bake sizes are
/// kept small: the web build composites and bakes on one thread (bake 256 took ~12 s to start on a
/// fast desktop CPU, 128 ~7.5 s).
fn initial_session() -> Result<Session, String> {
texturecraft_engine::sample_session(1024, 128)
.or_else(|e| {
log::warn!("sample project failed: {e}");
Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 1024)
})
.map_err(|e| e.to_string())
}
fn query() -> String {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
+23
View File
@@ -0,0 +1,23 @@
[package]
name = "texturecraft"
description = "TextureCraft: an open-source 3D texture painter (desktop app)"
version.workspace = true
edition.workspace = true
license.workspace = true
default-run = "texturecraft"
build = "build.rs"
[lints]
workspace = true
[dependencies]
texturecraft-engine = { workspace = true }
texturecraft-ui-egui = { workspace = true }
eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence"] }
egui = { workspace = true }
image = { workspace = true }
serde_json = { workspace = true }
log = { workspace = true }
[build-dependencies]
winresource = "0.1"
+80
View File
@@ -0,0 +1,80 @@
// Build provenance for every target, plus the Windows icon and VERSIONINFO.
//
// Shared by `texturecraft` and `texturecraft-cli` (whose build.rs `include!`s this file).
//
// - Always sets `TEXTURECRAFT_BUILD_SHA` (full git commit) and `TEXTURECRAFT_BUILD_DATE`
// (`YYYY-MM-DD`, UTC) for `env!`. They come from the same-named environment variables (CI and
// packaging/env.sh set them), else from `git` and the clock (`SOURCE_DATE_EPOCH` wins for
// reproducible builds); either is an empty string when unknown, so source tarballs, wasm and
// offline builds still compile. Without the env vars the commit is read when this script runs,
// so a local build can show a stale commit; release builds always set the variable.
// - Windows targets only: embeds assets/app-icon/texturecraft.ico and VERSIONINFO into the exe.
// A missing resource compiler is a warning, so a cross-compile still links, unless
// `TEXTURECRAFT_REQUIRE_WINRES=1` (set by packaging/windows/package.ps1) makes it an error.
use std::process::Command;
const ICON: &str = "../../assets/app-icon/texturecraft.ico";
fn main() {
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed={ICON}");
for var in ["TEXTURECRAFT_BUILD_SHA", "TEXTURECRAFT_BUILD_DATE", "TEXTURECRAFT_REQUIRE_WINRES", "SOURCE_DATE_EPOCH"] {
println!("cargo:rerun-if-env-changed={var}");
}
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_SHA={}", env_or("TEXTURECRAFT_BUILD_SHA", git_sha));
println!("cargo:rustc-env=TEXTURECRAFT_BUILD_DATE={}", env_or("TEXTURECRAFT_BUILD_DATE", today));
if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("windows") {
windows_resources();
}
}
fn env_or(var: &str, fallback: fn() -> Option<String>) -> String {
std::env::var(var).ok().map(|v| v.trim().to_owned()).filter(|v| !v.is_empty()).or_else(fallback).unwrap_or_default()
}
fn git_sha() -> Option<String> {
let out = Command::new("git").args(["rev-parse", "HEAD"]).output().ok().filter(|o| o.status.success())?;
let sha = String::from_utf8(out.stdout).ok()?.trim().to_owned();
(sha.len() >= 7 && sha.bytes().all(|b| b.is_ascii_hexdigit())).then_some(sha)
}
/// UTC date of `SOURCE_DATE_EPOCH`, or of now.
fn today() -> Option<String> {
let secs = match std::env::var("SOURCE_DATE_EPOCH") {
Ok(v) => v.trim().parse::<u64>().ok()?,
Err(_) => std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).ok()?.as_secs(),
};
// Days since 1970-01-01 to a civil date (Howard Hinnant's algorithm, proleptic Gregorian).
let z = i64::try_from(secs / 86_400).ok()? + 719_468;
let era = z.div_euclid(146_097);
let doe = z.rem_euclid(146_097);
let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let day = doy - (153 * mp + 2) / 5 + 1;
let month = if mp < 10 { mp + 3 } else { mp - 9 };
let year = yoe + era * 400 + i64::from(month <= 2);
Some(format!("{year:04}-{month:02}-{day:02}"))
}
fn windows_resources() {
let name = std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "texturecraft".into());
let description = if name.ends_with("-cli") { "TextureCraft command-line tool" } else { "TextureCraft 3D texture painter" };
let mut res = winresource::WindowsResource::new();
res.set_icon(ICON)
.set("ProductName", "TextureCraft")
.set("FileDescription", description)
.set("CompanyName", "Learning Machines LLC")
.set("LegalCopyright", "Copyright (c) the TextureCraft contributors. MIT OR Apache-2.0.")
.set("OriginalFilename", &format!("{name}.exe"))
.set("InternalName", &name);
if let Err(e) = res.compile() {
if std::env::var_os("TEXTURECRAFT_REQUIRE_WINRES").is_some() {
println!("cargo::error=embedding Windows resources into {name}.exe failed: {e}");
} else {
println!("cargo:warning={name}.exe built without icon/version resources: {e}");
}
}
}
+114
View File
@@ -0,0 +1,114 @@
//! Loopback JSON-lines control server (`--control <port>`): one request per line,
//! `{"id", "method", "params"}`, one reply per line. The first request must be
//! `{"method":"auth","params":{"token":"…"}}` with the token from `TEXTURECRAFT_CONTROL_TOKEN`
//! or, when that is unset, the token written to `<temp>/texturecraft-control-<port>.token`.
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc::{Receiver, Sender, channel};
use std::time::Duration;
use serde_json::{Value, json};
use texturecraft_ui_egui::ControlRequest;
/// Requests larger than this are rejected (screenshots go the other way).
const MAX_REQUEST: u64 = 8 << 20;
fn token(port: u16) -> String {
if let Ok(t) = std::env::var("TEXTURECRAFT_CONTROL_TOKEN")
&& t.len() >= 16
{
return t;
}
use std::hash::{BuildHasher, Hasher};
let mut out = String::new();
for i in 0..4u64 {
let mut h = std::collections::hash_map::RandomState::new().build_hasher();
h.write_u64(i ^ u64::from(std::process::id()));
h.write_u128(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map(|d| d.as_nanos()).unwrap_or(0));
out.push_str(&format!("{:016x}", h.finish()));
}
let path = std::env::temp_dir().join(format!("texturecraft-control-{port}.token"));
if let Err(e) = std::fs::write(&path, &out) {
eprintln!("texturecraft: could not write the control token to {}: {e}", path.display());
} else {
eprintln!("texturecraft: control token written to {}", path.display());
}
out
}
pub fn start(port: u16, ctx: egui::Context) -> Receiver<ControlRequest> {
let (tx, rx) = channel::<ControlRequest>();
let listener = match TcpListener::bind(("127.0.0.1", port)) {
Ok(l) => l,
Err(e) => {
eprintln!("texturecraft: control server failed to bind 127.0.0.1:{port}: {e}");
return rx;
}
};
let token = token(port);
eprintln!("texturecraft: control server listening on 127.0.0.1:{port}");
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let (tx, ctx, token) = (tx.clone(), ctx.clone(), token.clone());
std::thread::spawn(move || serve(stream, &token, tx, ctx));
}
});
rx
}
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context) {
let _ = stream.set_read_timeout(Some(Duration::from_secs(600)));
let Ok(read) = stream.try_clone() else { return };
let mut reader = BufReader::new(read.take(u64::MAX));
let mut out = stream;
let mut authed = false;
loop {
let mut line = String::new();
let n = match reader.by_ref().take(MAX_REQUEST).read_line(&mut line) {
Ok(n) => n,
Err(_) => break,
};
if n == 0 {
break;
}
if !line.ends_with('\n') && n as u64 >= MAX_REQUEST {
let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": "request too large"}));
break;
}
if line.trim().is_empty() {
continue;
}
let msg: Value = match serde_json::from_str(&line) {
Ok(v) => v,
Err(e) => {
let _ = writeln!(out, "{}", json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")}));
continue;
}
};
let id = msg.get("id").cloned().unwrap_or(Value::Null);
let method = msg.get("method").and_then(Value::as_str).unwrap_or("").to_string();
let params = msg.get("params").cloned().unwrap_or(json!({}));
let mut reply = if !authed {
let ok = method == "auth" && params.get("token").and_then(Value::as_str) == Some(token);
authed = ok;
if ok { json!({"ok": true}) } else { json!({"ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}) }
} else {
let (req, rrx) = ControlRequest::new(method, params);
if tx.send(req).is_err() {
break;
}
ctx.request_repaint();
rrx.recv_timeout(Duration::from_secs(120)).unwrap_or_else(|_| json!({"ok": false, "error": "timeout"}))
};
if let Some(o) = reply.as_object_mut() {
o.insert("id".into(), id);
}
if writeln!(out, "{reply}").is_err() || out.flush().is_err() || !authed {
if !authed {
continue;
}
break;
}
}
}
+120
View File
@@ -0,0 +1,120 @@
//! TextureCraft desktop app.
//!
//! Usage: `texturecraft [project.tcraft | mesh.glb] [--control <port>] [--empty] [--version]`
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod control_server;
use texturecraft_engine::Session;
use texturecraft_ui_egui::TextureCraftApp;
const ICON_PNG: &[u8] = include_bytes!("../../../assets/app-icon/hicolor/256x256/apps/ai.storyteller.texturecraft.png");
fn version() -> String {
let sha = env!("TEXTURECRAFT_BUILD_SHA");
let short = sha.get(..7).unwrap_or(sha);
let date = env!("TEXTURECRAFT_BUILD_DATE");
match (short.is_empty(), date.is_empty()) {
(true, true) => format!("TextureCraft {}", texturecraft_engine::VERSION),
(true, false) => format!("TextureCraft {} ({date})", texturecraft_engine::VERSION),
_ => format!("TextureCraft {} ({short} {date})", texturecraft_engine::VERSION),
}
}
struct Args {
file: Option<String>,
control: Option<u16>,
empty: bool,
}
fn parse_args() -> Result<Option<Args>, String> {
let mut args = Args { file: None, control: None, empty: false };
let mut it = std::env::args().skip(1);
while let Some(a) = it.next() {
match a.as_str() {
"--version" | "-V" => {
println!("{}", version());
return Ok(None);
}
"--help" | "-h" => {
println!("{}\n\nUsage: texturecraft [project.tcraft | mesh file] [--control <port>] [--empty]", version());
return Ok(None);
}
"--control" => {
let p = it.next().ok_or("--control needs a port")?;
args.control = Some(p.parse().map_err(|_| format!("invalid port `{p}`"))?);
}
"--empty" => args.empty = true,
f if !f.starts_with('-') => args.file = Some(f.to_string()),
other => return Err(format!("unknown option `{other}`")),
}
}
Ok(Some(args))
}
fn initial_session(args: &Args) -> Session {
if let Some(f) = &args.file {
match texturecraft_engine::file_cmds::open_path(f) {
Ok(s) => return s,
Err(e) => eprintln!("texturecraft: could not open {f}: {e}"),
}
}
if !args.empty
&& let Ok(s) = texturecraft_engine::sample_session(2048, 512)
{
return s;
}
match Session::new_project("Untitled", texturecraft_engine::geom::primitives::material_ball(), "builtin:material_ball", None, 2048) {
Ok(s) => s,
Err(e) => {
eprintln!("texturecraft: {e}");
std::process::exit(1);
}
}
}
fn icon() -> Option<egui::IconData> {
let img = image::load_from_memory(ICON_PNG).ok()?.into_rgba8();
let (w, h) = img.dimensions();
Some(egui::IconData { rgba: img.into_raw(), width: w, height: h })
}
fn main() {
let args = match parse_args() {
Ok(Some(a)) => a,
Ok(None) => return,
Err(e) => {
eprintln!("texturecraft: {e}");
std::process::exit(2);
}
};
let prev = std::panic::take_hook();
std::panic::set_hook(Box::new(move |info| {
eprintln!("texturecraft: internal error: {info}");
prev(info);
}));
let session = initial_session(&args);
let mut viewport = egui::ViewportBuilder::default().with_title("TextureCraft").with_inner_size([1600.0, 960.0]).with_min_inner_size([960.0, 600.0]);
if let Some(i) = icon() {
viewport = viewport.with_icon(i);
}
let options = eframe::NativeOptions { viewport, renderer: eframe::Renderer::Wgpu, ..Default::default() };
let control = args.control;
let r = eframe::run_native(
"TextureCraft",
options,
Box::new(move |cc| {
let mut app = TextureCraftApp::new(cc, session);
if let Some(port) = control {
app.control = Some(control_server::start(port, cc.egui_ctx.clone()));
}
Ok(Box::new(app))
}),
);
if let Err(e) = r {
eprintln!("texturecraft: {e}");
std::process::exit(1);
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 14 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 827 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 4.5 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 63 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.9 KiB

@@ -0,0 +1,169 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<title>TextureCraft</title>
<clipPath id="tile"><rect width="512" height="512" rx="112"/></clipPath>
<g clip-path="url(#tile)">
<rect width="512" height="512" fill="#c2672b"/>
<path d="M185.7 218.5 L184.0 219.6 L182.0 220.9 L180.0 222.3 L177.8 223.8 L175.7 225.4 L173.4 227.1 L171.0 228.8 L168.6 230.6 L166.1 232.5 L163.5 234.4 L160.9 236.3 L158.2 238.3 L155.5 240.2 L152.8 242.1 L150.2 244.0 L147.5 245.9 L144.9 247.7 L142.3 249.4 L139.9 251.1 L137.5 252.6 L135.3 254.1 L133.2 255.4 L131.4 256.5 L129.6 257.6 L127.6 258.6 L125.4 259.7 L123.2 260.8 L120.9 261.8 L118.7 262.8 L116.4 263.8 L114.2 264.7 L111.9 265.7 L109.7 266.5 L107.5 267.4 L105.3 268.2 L103.1 268.9 L101.0 269.6 L98.9 270.3 L96.9 270.9 L94.9 271.5 L92.9 272.0 L91.0 272.5 L89.2 272.9 L87.5 273.3 L85.9 273.6 L84.3 273.8 L82.9 274.1 L81.6 274.2 L80.3 274.4 L79.1 274.5 L77.8 274.5 L76.5 274.5 L75.1 274.4 L73.8 274.3 L72.4 274.1 L71.0 273.9 L69.7 273.6 L68.3 273.3 L66.9 272.9 L65.6 272.5 L64.3 272.1 L63.0 271.6 L61.7 271.1 L60.5 270.6 L59.4 270.1 L58.2 269.5 L57.2 268.9 L56.2 268.4 L55.2 267.8 L54.4 267.3 L53.6 266.7 L52.9 266.3 L52.4 266.0 L52.0 265.7 L51.5 265.3 L50.9 264.8 L50.3 264.1 L49.8 263.3 L49.2 262.5 L48.7 261.6 L48.2 260.6 L47.7 259.5 L47.2 258.5 L46.8 257.4 L46.4 256.2 L46.1 255.1 L45.8 254.0 L45.5 252.9 L45.3 251.9 L45.1 250.9 L45.0 249.9 L44.9 249.1 L44.8 248.3 L44.8 247.7 L44.7 247.2 L44.6 246.9 L44.5 246.9 L44.4 246.7 L44.4 246.4 L44.5 246.0 L44.7 245.4 L45.0 244.8 L45.5 244.2 L46.0 243.5 L46.6 242.7 L47.3 242.0 L48.1 241.3 L48.9 240.6 L49.7 239.9 L50.6 239.2 L51.5 238.6 L52.4 238.0 L53.3 237.5 L54.2 237.0 L55.0 236.6 L55.8 236.2 L56.5 235.9 L57.1 235.6 L57.6 235.4 L57.9 235.3 L58.1 235.1 L58.5 235.1 L58.9 235.0 L59.6 235.0 L60.3 235.1 L61.1 235.3 L61.9 235.6 L62.9 235.9 L63.8 236.2 L64.8 236.7 L65.8 237.1 L66.7 237.6 L67.7 238.2 L68.6 238.8 L69.5 239.4 L70.4 240.0 L71.2 240.6 L71.9 241.2 L72.6 241.8 L73.2 242.3 L73.6 242.8 L74.0 243.3 L74.3 243.6 L74.5 243.7 L74.6 243.7 L74.7 243.7 L74.7 243.9 L74.8 244.2 L74.8 244.7 L74.7 245.4 L74.5 246.1 L74.2 246.9 L73.9 247.8 L73.5 248.7 L73.1 249.6 L72.6 250.5 L72.1 251.5 L71.6 252.4 L71.1 253.3 L70.5 254.3 L70.0 255.1 L69.5 256.0 L69.0 256.8 L68.5 257.6 L68.0 258.3 L67.6 259.1 L67.2 259.7 L66.9 260.3 L73.1 263.7 L73.3 263.4 L73.6 263.0 L74.0 262.5 L74.4 262.0 L75.0 261.3 L75.6 260.6 L76.3 259.9 L77.0 259.1 L77.8 258.2 L78.5 257.3 L79.3 256.4 L80.1 255.5 L80.9 254.5 L81.7 253.5 L82.4 252.4 L83.1 251.3 L83.8 250.2 L84.4 249.0 L84.9 247.8 L85.4 246.4 L85.7 245.0 L85.9 243.5 L85.8 241.9 L85.5 240.3 L85.1 238.8 L84.6 237.6 L84.0 236.3 L83.3 235.1 L82.6 233.9 L81.8 232.7 L80.9 231.6 L80.0 230.4 L79.0 229.2 L78.0 228.1 L76.9 227.0 L75.8 225.9 L74.6 224.8 L73.3 223.7 L72.1 222.7 L70.8 221.8 L69.4 220.9 L68.0 220.0 L66.5 219.2 L65.0 218.5 L63.4 217.9 L61.7 217.3 L59.9 217.0 L58.1 216.7 L56.3 216.7 L54.6 216.7 L53.0 216.8 L51.3 217.0 L49.6 217.2 L47.9 217.6 L46.2 218.0 L44.5 218.4 L42.8 219.0 L41.0 219.5 L39.3 220.2 L37.6 220.9 L35.9 221.7 L34.2 222.6 L32.5 223.5 L30.9 224.5 L29.2 225.7 L27.6 226.9 L26.1 228.2 L24.6 229.6 L23.1 231.2 L21.8 233.0 L20.5 235.0 L19.4 237.1 L18.5 239.1 L17.8 241.0 L17.2 243.0 L16.6 244.9 L16.2 246.9 L15.8 249.0 L15.5 251.1 L15.2 253.2 L15.1 255.3 L15.0 257.5 L14.9 259.7 L15.0 261.9 L15.1 264.1 L15.3 266.4 L15.5 268.7 L15.9 271.0 L16.4 273.3 L16.9 275.7 L17.6 278.0 L18.4 280.4 L19.3 282.7 L20.4 285.1 L21.7 287.5 L23.1 289.7 L24.4 291.7 L25.8 293.6 L27.2 295.4 L28.7 297.3 L30.3 299.1 L31.9 300.9 L33.7 302.6 L35.5 304.3 L37.3 306.0 L39.3 307.7 L41.3 309.4 L43.4 311.0 L45.6 312.5 L47.8 314.0 L50.1 315.5 L52.5 316.9 L55.0 318.3 L57.5 319.6 L60.2 320.8 L62.9 322.0 L65.6 323.1 L68.5 324.1 L71.4 325.0 L74.4 325.8 L77.4 326.5 L80.5 327.1 L83.5 327.6 L86.5 328.1 L89.6 328.5 L92.7 328.8 L95.8 329.0 L98.9 329.3 L102.1 329.4 L105.2 329.5 L108.4 329.6 L111.6 329.6 L114.8 329.5 L118.0 329.5 L121.3 329.3 L124.5 329.2 L127.7 329.0 L131.0 328.7 L134.2 328.4 L137.4 328.1 L140.7 327.8 L143.9 327.4 L147.1 326.9 L150.4 326.4 L154.1 325.8 L157.9 325.0 L161.7 324.1 L165.5 323.2 L169.4 322.3 L173.2 321.2 L177.0 320.2 L180.8 319.1 L184.5 318.0 L188.3 316.9 L191.9 315.8 L195.5 314.7 L199.1 313.6 L202.5 312.6 L205.8 311.5 L208.9 310.6 L211.9 309.6 L214.7 308.7 L217.3 307.9 L219.7 307.2 L221.8 306.6 L223.6 306.1 L225.0 305.8 L226.3 305.5 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M200.3 286.6 L197.3 287.5 L194.2 288.5 L191.0 289.6 L187.7 290.7 L184.3 291.8 L180.9 292.9 L177.4 294.1 L173.9 295.2 L170.4 296.3 L166.9 297.4 L163.4 298.5 L160.0 299.5 L156.5 300.5 L153.2 301.4 L149.9 302.3 L146.6 303.0 L143.5 303.7 L140.6 304.2 L137.7 304.7 L134.8 305.2 L131.8 305.7 L128.9 306.1 L126.0 306.5 L123.1 306.9 L120.2 307.2 L117.3 307.5 L114.4 307.8 L111.5 308.0 L108.6 308.2 L105.8 308.4 L103.0 308.5 L100.2 308.6 L97.5 308.6 L94.8 308.6 L92.1 308.5 L89.5 308.4 L86.9 308.2 L84.3 308.0 L81.9 307.7 L79.4 307.4 L77.0 307.0 L74.7 306.5 L72.4 305.9 L70.1 305.2 L67.9 304.5 L65.7 303.8 L63.5 302.9 L61.4 302.0 L59.3 301.1 L57.3 300.1 L55.4 299.0 L53.4 297.9 L51.6 296.8 L49.8 295.6 L48.0 294.4 L46.3 293.2 L44.7 291.9 L43.1 290.7 L41.6 289.4 L40.1 288.0 L38.8 286.7 L37.5 285.3 L36.2 284.0 L35.0 282.6 L33.9 281.2 L32.8 279.7 L31.8 278.1 L30.9 276.5 L30.1 274.8 L29.4 273.0 L28.7 271.3 L28.1 269.5 L27.5 267.7 L27.1 265.8 L26.7 264.0 L26.3 262.2 L26.0 260.3 L25.8 258.5 L25.6 256.7 L25.5 254.9 L25.5 253.1 L25.5 251.3 L25.6 249.6 L25.7 247.9 L25.9 246.3 L26.2 244.7 L26.5 243.2 L26.9 241.7 L27.4 240.2 L28.0 238.7 L28.8 237.3 L29.7 235.9 L30.6 234.6 L31.6 233.3 L31.0 232.7 L29.7 233.8 L28.5 235.1 L27.4 236.4 L26.4 237.9 L25.5 239.5 L24.8 241.0 L24.2 242.6 L23.6 244.2 L23.2 245.9 L22.8 247.6 L22.4 249.4 L22.1 251.2 L21.9 253.1 L21.8 255.0 L21.7 257.0 L21.7 258.9 L21.7 260.9 L21.8 263.0 L22.0 265.0 L22.3 267.0 L22.6 269.1 L23.1 271.1 L23.6 273.2 L24.2 275.2 L24.9 277.3 L25.7 279.3 L26.7 281.3 L27.8 283.2 L28.9 285.1 L30.1 286.8 L31.4 288.4 L32.7 290.1 L34.0 291.7 L35.5 293.3 L37.0 294.8 L38.6 296.4 L40.3 297.9 L42.0 299.4 L43.8 300.8 L45.7 302.2 L47.6 303.6 L49.7 304.9 L51.7 306.2 L53.9 307.5 L56.1 308.7 L58.3 309.8 L60.7 310.9 L63.0 311.9 L65.5 312.8 L68.0 313.7 L70.6 314.4 L73.2 315.1 L75.8 315.7 L78.5 316.2 L81.2 316.6 L84.0 316.9 L86.7 317.2 L89.5 317.4 L92.4 317.5 L95.2 317.6 L98.1 317.6 L101.0 317.5 L103.9 317.4 L106.9 317.2 L109.9 317.0 L112.8 316.7 L115.8 316.4 L118.8 316.0 L121.8 315.5 L124.8 315.1 L127.8 314.6 L130.8 314.0 L133.8 313.4 L136.7 312.8 L139.7 312.1 L142.6 311.4 L145.6 310.6 L148.8 309.7 L152.1 308.7 L155.5 307.6 L158.9 306.4 L162.3 305.1 L165.7 303.8 L169.1 302.4 L172.5 300.9 L175.9 299.4 L179.3 297.9 L182.6 296.4 L185.8 294.9 L189.0 293.3 L192.1 291.8 L195.1 290.3 L198.0 288.8 L200.7 287.4 Z" fill="#0b0b0c"/>
<circle cx="85.5" cy="281.0" r="10.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.6"/>
<circle cx="85.5" cy="281.0" r="3.5" fill="#0b0b0c"/>
<circle cx="70.0" cy="280.3" r="9.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.0"/>
<circle cx="70.0" cy="280.3" r="3.0" fill="#0b0b0c"/>
<circle cx="55.8" cy="274.6" r="8.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.5"/>
<circle cx="55.8" cy="274.6" r="2.7" fill="#0b0b0c"/>
<circle cx="46.5" cy="266.9" r="7.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.1"/>
<circle cx="46.5" cy="266.9" r="2.3" fill="#0b0b0c"/>
<circle cx="42.1" cy="256.7" r="6.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.7"/>
<circle cx="42.1" cy="256.7" r="2.0" fill="#0b0b0c"/>
<circle cx="41.0" cy="247.6" r="5.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="41.0" cy="247.6" r="1.8" fill="#0b0b0c"/>
<circle cx="43.3" cy="241.7" r="5.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="49.3" cy="236.5" r="4.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="56.0" cy="233.3" r="3.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="60.3" cy="232.8" r="3.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="66.0" cy="234.9" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="70.8" cy="238.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="75.0" cy="242.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="76.2" cy="244.5" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="74.1" cy="250.2" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<path d="M285.7 305.5 L287.0 305.8 L288.4 306.1 L290.2 306.6 L292.3 307.2 L294.7 307.9 L297.3 308.7 L300.1 309.6 L303.1 310.6 L306.2 311.5 L309.5 312.6 L312.9 313.6 L316.5 314.7 L320.1 315.8 L323.7 316.9 L327.5 318.0 L331.2 319.1 L335.0 320.2 L338.8 321.2 L342.6 322.3 L346.5 323.2 L350.3 324.1 L354.1 325.0 L357.9 325.8 L361.6 326.4 L364.9 326.9 L368.1 327.4 L371.3 327.8 L374.6 328.1 L377.8 328.4 L381.0 328.7 L384.3 329.0 L387.5 329.2 L390.7 329.3 L394.0 329.5 L397.2 329.5 L400.4 329.6 L403.6 329.6 L406.8 329.5 L409.9 329.4 L413.1 329.3 L416.2 329.0 L419.3 328.8 L422.4 328.5 L425.5 328.1 L428.5 327.6 L431.5 327.1 L434.6 326.5 L437.6 325.8 L440.6 325.0 L443.5 324.1 L446.4 323.1 L449.1 322.0 L451.8 320.8 L454.5 319.6 L457.0 318.3 L459.5 316.9 L461.9 315.5 L464.2 314.0 L466.4 312.5 L468.6 311.0 L470.7 309.4 L472.7 307.7 L474.7 306.0 L476.5 304.3 L478.3 302.6 L480.1 300.9 L481.7 299.1 L483.3 297.3 L484.8 295.4 L486.2 293.6 L487.6 291.7 L488.9 289.7 L490.3 287.5 L491.6 285.1 L492.7 282.7 L493.6 280.4 L494.4 278.0 L495.1 275.7 L495.6 273.3 L496.1 271.0 L496.5 268.7 L496.7 266.4 L496.9 264.1 L497.0 261.9 L497.1 259.7 L497.0 257.5 L496.9 255.3 L496.8 253.2 L496.5 251.1 L496.2 249.0 L495.8 246.9 L495.4 244.9 L494.8 243.0 L494.2 241.0 L493.5 239.1 L492.6 237.1 L491.5 235.0 L490.2 233.0 L488.9 231.2 L487.4 229.6 L485.9 228.2 L484.4 226.9 L482.8 225.7 L481.1 224.5 L479.5 223.5 L477.8 222.6 L476.1 221.7 L474.4 220.9 L472.7 220.2 L471.0 219.5 L469.2 219.0 L467.5 218.4 L465.8 218.0 L464.1 217.6 L462.4 217.2 L460.7 217.0 L459.0 216.8 L457.4 216.7 L455.7 216.7 L453.9 216.7 L452.1 217.0 L450.3 217.3 L448.6 217.9 L447.0 218.5 L445.5 219.2 L444.0 220.0 L442.6 220.9 L441.2 221.8 L439.9 222.7 L438.7 223.7 L437.4 224.8 L436.2 225.9 L435.1 227.0 L434.0 228.1 L433.0 229.2 L432.0 230.4 L431.1 231.6 L430.2 232.7 L429.4 233.9 L428.7 235.1 L428.0 236.3 L427.4 237.6 L426.9 238.8 L426.5 240.3 L426.2 241.9 L426.1 243.5 L426.3 245.0 L426.6 246.4 L427.1 247.8 L427.6 249.0 L428.2 250.2 L428.9 251.3 L429.6 252.4 L430.3 253.5 L431.1 254.5 L431.9 255.5 L432.7 256.4 L433.5 257.3 L434.2 258.2 L435.0 259.1 L435.7 259.9 L436.4 260.6 L437.0 261.3 L437.6 262.0 L438.0 262.5 L438.4 263.0 L438.7 263.4 L438.9 263.7 L445.1 260.3 L444.8 259.7 L444.4 259.1 L444.0 258.3 L443.5 257.6 L443.0 256.8 L442.5 256.0 L442.0 255.1 L441.5 254.3 L440.9 253.3 L440.4 252.4 L439.9 251.5 L439.4 250.5 L438.9 249.6 L438.5 248.7 L438.1 247.8 L437.8 246.9 L437.5 246.1 L437.3 245.4 L437.2 244.7 L437.2 244.2 L437.3 243.9 L437.3 243.7 L437.4 243.7 L437.5 243.7 L437.7 243.6 L438.0 243.3 L438.4 242.8 L438.8 242.3 L439.4 241.8 L440.1 241.2 L440.8 240.6 L441.6 240.0 L442.5 239.4 L443.4 238.8 L444.3 238.2 L445.3 237.6 L446.2 237.1 L447.2 236.7 L448.2 236.2 L449.1 235.9 L450.1 235.6 L450.9 235.3 L451.7 235.1 L452.4 235.0 L453.1 235.0 L453.5 235.1 L453.9 235.1 L454.1 235.3 L454.4 235.4 L454.9 235.6 L455.5 235.9 L456.2 236.2 L457.0 236.6 L457.8 237.0 L458.7 237.5 L459.6 238.0 L460.5 238.6 L461.4 239.2 L462.3 239.9 L463.1 240.6 L463.9 241.3 L464.7 242.0 L465.4 242.7 L466.0 243.5 L466.5 244.2 L467.0 244.8 L467.3 245.4 L467.5 246.0 L467.6 246.4 L467.6 246.7 L467.5 246.9 L467.4 246.9 L467.3 247.2 L467.2 247.7 L467.2 248.3 L467.1 249.1 L467.0 249.9 L466.9 250.9 L466.7 251.9 L466.5 252.9 L466.2 254.0 L465.9 255.1 L465.6 256.2 L465.2 257.4 L464.8 258.5 L464.3 259.5 L463.8 260.6 L463.3 261.6 L462.8 262.5 L462.2 263.3 L461.7 264.1 L461.1 264.8 L460.5 265.3 L460.0 265.7 L459.6 266.0 L459.1 266.3 L458.4 266.7 L457.6 267.3 L456.8 267.8 L455.8 268.4 L454.8 268.9 L453.8 269.5 L452.6 270.1 L451.5 270.6 L450.3 271.1 L449.0 271.6 L447.7 272.1 L446.4 272.5 L445.1 272.9 L443.7 273.3 L442.3 273.6 L441.0 273.9 L439.6 274.1 L438.2 274.3 L436.9 274.4 L435.5 274.5 L434.2 274.5 L432.9 274.5 L431.7 274.4 L430.4 274.2 L429.1 274.1 L427.7 273.8 L426.1 273.6 L424.5 273.3 L422.8 272.9 L421.0 272.5 L419.1 272.0 L417.1 271.5 L415.1 270.9 L413.1 270.3 L411.0 269.6 L408.9 268.9 L406.7 268.2 L404.5 267.4 L402.3 266.5 L400.1 265.7 L397.8 264.7 L395.6 263.8 L393.3 262.8 L391.1 261.8 L388.8 260.8 L386.6 259.7 L384.4 258.6 L382.4 257.6 L380.6 256.5 L378.8 255.4 L376.7 254.1 L374.5 252.6 L372.1 251.1 L369.7 249.4 L367.1 247.7 L364.5 245.9 L361.8 244.0 L359.2 242.1 L356.5 240.2 L353.8 238.3 L351.1 236.3 L348.5 234.4 L345.9 232.5 L343.4 230.6 L341.0 228.8 L338.6 227.1 L336.3 225.4 L334.2 223.8 L332.0 222.3 L330.0 220.9 L328.0 219.6 L326.3 218.5 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M311.3 287.4 L314.0 288.8 L316.9 290.3 L319.9 291.8 L323.0 293.3 L326.2 294.9 L329.4 296.4 L332.7 297.9 L336.1 299.4 L339.5 300.9 L342.9 302.4 L346.3 303.8 L349.7 305.1 L353.1 306.4 L356.5 307.6 L359.9 308.7 L363.2 309.7 L366.4 310.6 L369.4 311.4 L372.3 312.1 L375.3 312.8 L378.2 313.4 L381.2 314.0 L384.2 314.6 L387.2 315.1 L390.2 315.5 L393.2 316.0 L396.2 316.4 L399.2 316.7 L402.1 317.0 L405.1 317.2 L408.1 317.4 L411.0 317.5 L413.9 317.6 L416.8 317.6 L419.6 317.5 L422.5 317.4 L425.3 317.2 L428.0 316.9 L430.8 316.6 L433.5 316.2 L436.2 315.7 L438.8 315.1 L441.4 314.4 L444.0 313.7 L446.5 312.8 L449.0 311.9 L451.3 310.9 L453.7 309.8 L455.9 308.7 L458.1 307.5 L460.3 306.2 L462.3 304.9 L464.4 303.6 L466.3 302.2 L468.2 300.8 L470.0 299.4 L471.7 297.9 L473.4 296.4 L475.0 294.8 L476.5 293.3 L478.0 291.7 L479.3 290.1 L480.6 288.4 L481.9 286.8 L483.1 285.1 L484.2 283.2 L485.3 281.3 L486.3 279.3 L487.1 277.3 L487.8 275.2 L488.4 273.2 L488.9 271.1 L489.4 269.1 L489.7 267.0 L490.0 265.0 L490.2 263.0 L490.3 260.9 L490.3 258.9 L490.3 257.0 L490.2 255.0 L490.1 253.1 L489.9 251.2 L489.6 249.4 L489.2 247.6 L488.8 245.9 L488.4 244.2 L487.8 242.6 L487.2 241.0 L486.5 239.5 L485.6 237.9 L484.6 236.4 L483.5 235.1 L482.3 233.8 L481.0 232.7 L480.4 233.3 L481.4 234.6 L482.3 235.9 L483.2 237.3 L484.0 238.7 L484.6 240.2 L485.1 241.7 L485.5 243.2 L485.8 244.7 L486.1 246.3 L486.3 247.9 L486.4 249.6 L486.5 251.3 L486.5 253.1 L486.5 254.9 L486.4 256.7 L486.2 258.5 L486.0 260.3 L485.7 262.2 L485.3 264.0 L484.9 265.8 L484.5 267.7 L483.9 269.5 L483.3 271.3 L482.6 273.0 L481.9 274.8 L481.1 276.5 L480.2 278.1 L479.2 279.7 L478.1 281.2 L477.0 282.6 L475.8 284.0 L474.5 285.3 L473.2 286.7 L471.9 288.0 L470.4 289.4 L468.9 290.7 L467.3 291.9 L465.7 293.2 L464.0 294.4 L462.2 295.6 L460.4 296.8 L458.6 297.9 L456.6 299.0 L454.7 300.1 L452.7 301.1 L450.6 302.0 L448.5 302.9 L446.3 303.8 L444.1 304.5 L441.9 305.2 L439.6 305.9 L437.3 306.5 L435.0 307.0 L432.6 307.4 L430.1 307.7 L427.7 308.0 L425.1 308.2 L422.5 308.4 L419.9 308.5 L417.2 308.6 L414.5 308.6 L411.8 308.6 L409.0 308.5 L406.2 308.4 L403.4 308.2 L400.5 308.0 L397.6 307.8 L394.7 307.5 L391.8 307.2 L388.9 306.9 L386.0 306.5 L383.1 306.1 L380.2 305.7 L377.2 305.2 L374.3 304.7 L371.4 304.2 L368.5 303.7 L365.4 303.0 L362.1 302.3 L358.8 301.4 L355.5 300.5 L352.0 299.5 L348.6 298.5 L345.1 297.4 L341.6 296.3 L338.1 295.2 L334.6 294.1 L331.1 292.9 L327.7 291.8 L324.3 290.7 L321.0 289.6 L317.8 288.5 L314.7 287.5 L311.7 286.6 Z" fill="#0b0b0c"/>
<circle cx="426.5" cy="281.0" r="10.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.6"/>
<circle cx="426.5" cy="281.0" r="3.5" fill="#0b0b0c"/>
<circle cx="442.0" cy="280.3" r="9.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.0"/>
<circle cx="442.0" cy="280.3" r="3.0" fill="#0b0b0c"/>
<circle cx="456.2" cy="274.6" r="8.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.5"/>
<circle cx="456.2" cy="274.6" r="2.7" fill="#0b0b0c"/>
<circle cx="465.5" cy="266.9" r="7.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.1"/>
<circle cx="465.5" cy="266.9" r="2.3" fill="#0b0b0c"/>
<circle cx="469.9" cy="256.7" r="6.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.7"/>
<circle cx="469.9" cy="256.7" r="2.0" fill="#0b0b0c"/>
<circle cx="471.0" cy="247.6" r="5.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="471.0" cy="247.6" r="1.8" fill="#0b0b0c"/>
<circle cx="468.7" cy="241.7" r="5.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="462.7" cy="236.5" r="4.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="456.0" cy="233.3" r="3.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="451.7" cy="232.8" r="3.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="446.0" cy="234.9" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="441.2" cy="238.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="437.0" cy="242.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="435.8" cy="244.5" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="437.9" cy="250.2" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<path d="M181.4 234.6 L180.7 235.8 L180.0 237.1 L179.3 238.5 L178.6 239.9 L177.9 241.3 L177.2 242.7 L176.4 244.2 L175.7 245.7 L175.0 247.3 L174.2 248.9 L173.4 250.5 L172.6 252.1 L171.8 253.8 L171.0 255.5 L170.1 257.2 L169.2 259.0 L168.4 260.7 L167.4 262.5 L166.5 264.2 L165.6 265.9 L164.7 267.6 L163.7 269.3 L162.8 271.0 L161.9 272.6 L161.0 274.1 L160.0 275.7 L158.9 277.4 L157.7 279.1 L156.5 281.0 L155.1 282.9 L153.6 285.0 L152.0 287.1 L150.4 289.3 L148.7 291.5 L146.9 293.9 L145.1 296.3 L143.2 298.7 L141.2 301.3 L139.3 303.9 L137.3 306.5 L135.3 309.3 L133.2 312.1 L131.2 315.0 L129.1 317.9 L127.1 321.0 L125.0 324.1 L123.0 327.2 L121.1 330.3 L119.5 333.0 L117.9 335.6 L116.3 338.3 L114.6 341.1 L112.9 343.9 L111.1 346.8 L109.3 349.7 L107.4 352.8 L105.5 355.9 L103.6 359.1 L101.7 362.3 L99.7 365.7 L97.8 369.2 L95.8 372.7 L93.9 376.4 L92.0 380.1 L90.2 384.0 L88.3 388.0 L86.6 392.0 L84.8 396.2 L83.2 400.5 L81.6 404.9 L80.1 409.4 L78.6 414.1 L77.2 419.0 L75.9 424.2 L74.7 429.5 L73.6 435.0 L72.5 440.7 L71.5 446.4 L70.6 452.3 L69.7 458.2 L68.8 464.2 L68.0 470.2 L67.2 476.1 L66.4 482.0 L65.7 487.9 L65.0 493.6 L64.3 499.1 L63.7 504.5 L63.1 509.6 L62.5 514.5 L61.9 519.0 L61.4 523.3 L60.9 527.2 L60.4 530.6 L59.9 533.6 L59.4 536.2 L92.6 543.8 L93.3 541.1 L94.2 537.9 L95.2 534.3 L96.3 530.4 L97.5 526.3 L98.7 521.8 L100.1 517.1 L101.5 512.1 L103.0 507.0 L104.5 501.8 L106.2 496.4 L107.8 491.0 L109.6 485.5 L111.3 480.0 L113.1 474.5 L114.9 469.2 L116.8 463.9 L118.6 458.8 L120.5 453.9 L122.4 449.2 L124.2 444.8 L126.0 440.8 L127.7 437.2 L129.4 433.9 L131.1 430.9 L132.8 427.9 L134.6 425.0 L136.4 422.2 L138.3 419.5 L140.1 416.9 L142.0 414.4 L144.0 411.9 L145.9 409.4 L147.9 407.0 L150.0 404.6 L152.0 402.3 L154.1 400.0 L156.2 397.6 L158.4 395.3 L160.6 393.0 L162.8 390.7 L165.0 388.4 L167.3 386.0 L169.6 383.6 L171.9 381.2 L174.3 378.7 L176.7 376.1 L178.9 373.7 L180.9 371.7 L182.8 369.8 L184.7 367.9 L186.7 366.1 L188.7 364.3 L190.7 362.4 L192.8 360.6 L194.9 358.8 L197.0 357.0 L199.1 355.1 L201.3 353.3 L203.4 351.5 L205.6 349.6 L207.8 347.8 L210.1 345.9 L212.3 344.0 L214.5 342.1 L216.7 340.1 L219.0 338.2 L221.2 336.1 L223.5 334.0 L225.7 331.9 L228.0 329.6 L230.1 327.4 L232.2 325.2 L234.2 323.1 L236.1 321.0 L238.0 318.9 L239.8 316.8 L241.6 314.8 L243.3 312.8 L245.0 310.8 L246.6 308.9 L248.2 307.0 L249.7 305.1 L251.1 303.4 L252.5 301.6 L253.8 300.0 L255.1 298.4 L256.3 296.9 L257.4 295.5 L258.4 294.3 L259.4 293.1 L260.2 292.0 L261.0 291.2 L261.6 290.4 L262.1 289.9 L262.6 289.4 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M195.2 264.6 L194.1 266.2 L193.0 267.8 L191.8 269.4 L190.6 271.1 L189.4 272.8 L188.2 274.5 L186.9 276.2 L185.7 277.9 L184.4 279.7 L183.1 281.4 L181.8 283.1 L180.5 284.8 L179.1 286.5 L177.8 288.1 L176.4 289.7 L175.0 291.4 L173.4 293.2 L171.8 295.0 L170.1 296.9 L168.3 298.8 L166.5 300.8 L164.6 302.8 L162.7 304.9 L160.7 307.0 L158.7 309.2 L156.7 311.4 L154.6 313.7 L152.5 316.1 L150.4 318.5 L148.3 320.9 L146.2 323.4 L144.1 326.0 L142.0 328.7 L139.8 331.4 L137.8 334.1 L135.7 337.0 L133.7 339.8 L131.9 342.4 L130.1 345.0 L128.3 347.6 L126.5 350.2 L124.6 352.9 L122.7 355.7 L120.7 358.5 L118.8 361.3 L116.8 364.3 L114.8 367.3 L112.8 370.4 L110.9 373.5 L108.9 376.8 L107.0 380.1 L105.1 383.5 L103.2 387.0 L101.4 390.6 L99.6 394.3 L97.9 398.0 L96.2 401.9 L94.6 405.9 L93.0 410.0 L91.6 414.3 L90.2 418.6 L88.9 423.2 L87.7 428.1 L86.6 433.2 L85.5 438.5 L84.5 444.0 L83.6 449.6 L82.8 455.4 L84.2 455.7 L85.8 450.2 L87.4 444.8 L89.0 439.5 L90.6 434.4 L92.2 429.6 L93.8 425.0 L95.4 420.6 L97.1 416.6 L98.8 412.6 L100.6 408.8 L102.4 405.1 L104.2 401.4 L106.1 397.9 L108.0 394.4 L109.9 391.1 L111.9 387.8 L113.9 384.6 L115.9 381.5 L117.9 378.4 L119.9 375.4 L121.9 372.4 L123.9 369.6 L125.8 366.7 L127.8 363.9 L129.8 361.1 L131.7 358.4 L133.6 355.7 L135.5 353.1 L137.3 350.4 L139.1 347.8 L140.8 345.1 L142.7 342.4 L144.6 339.6 L146.6 336.9 L148.5 334.2 L150.5 331.5 L152.5 328.9 L154.4 326.4 L156.4 323.9 L158.3 321.4 L160.3 319.0 L162.2 316.6 L164.1 314.3 L165.9 312.0 L167.8 309.7 L169.5 307.5 L171.3 305.3 L173.0 303.1 L174.6 301.0 L176.1 299.0 L177.6 297.0 L179.0 295.0 L180.4 293.1 L181.6 291.2 L182.8 289.4 L184.0 287.6 L185.1 285.7 L186.2 283.8 L187.3 281.8 L188.4 279.9 L189.5 278.0 L190.5 276.1 L191.5 274.2 L192.4 272.3 L193.4 270.5 L194.3 268.6 L195.1 266.8 L195.9 265.0 Z" fill="#0b0b0c"/>
<circle cx="182.7" cy="355.4" r="15.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="6.4"/>
<circle cx="182.7" cy="355.4" r="4.9" fill="#0b0b0c"/>
<circle cx="159.8" cy="380.2" r="13.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.8"/>
<circle cx="159.8" cy="380.2" r="4.4" fill="#0b0b0c"/>
<circle cx="140.8" cy="402.3" r="12.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.3"/>
<circle cx="140.8" cy="402.3" r="4.0" fill="#0b0b0c"/>
<circle cx="127.4" cy="421.6" r="11.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.8"/>
<circle cx="127.4" cy="421.6" r="3.7" fill="#0b0b0c"/>
<circle cx="117.4" cy="442.7" r="10.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.4"/>
<circle cx="117.4" cy="442.7" r="3.3" fill="#0b0b0c"/>
<circle cx="110.3" cy="462.3" r="9.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.0"/>
<circle cx="110.3" cy="462.3" r="3.1" fill="#0b0b0c"/>
<circle cx="103.8" cy="484.2" r="8.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.7"/>
<circle cx="103.8" cy="484.2" r="2.8" fill="#0b0b0c"/>
<circle cx="99.0" cy="500.6" r="8.1" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.4"/>
<circle cx="99.0" cy="500.6" r="2.6" fill="#0b0b0c"/>
<circle cx="93.8" cy="520.8" r="7.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.1"/>
<circle cx="93.8" cy="520.8" r="2.4" fill="#0b0b0c"/>
<circle cx="89.6" cy="536.9" r="7.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.9"/>
<circle cx="89.6" cy="536.9" r="2.2" fill="#0b0b0c"/>
<path d="M249.4 289.4 L250.0 290.0 L250.5 290.6 L251.2 291.3 L252.0 292.3 L252.9 293.3 L253.9 294.5 L255.0 295.7 L256.1 297.1 L257.4 298.5 L258.6 300.1 L260.0 301.7 L261.4 303.3 L262.9 305.1 L264.4 306.8 L266.0 308.7 L267.6 310.5 L269.3 312.4 L271.0 314.3 L272.7 316.3 L274.5 318.3 L276.4 320.3 L278.2 322.3 L280.2 324.3 L282.0 326.3 L283.8 328.0 L285.5 329.7 L287.4 331.5 L289.2 333.4 L291.1 335.3 L293.1 337.3 L295.1 339.3 L297.2 341.3 L299.3 343.4 L301.4 345.5 L303.7 347.7 L305.9 349.8 L308.2 352.0 L310.5 354.2 L312.9 356.4 L315.3 358.7 L317.8 360.9 L320.3 363.1 L322.8 365.4 L325.4 367.6 L328.0 369.8 L330.7 372.0 L333.4 374.2 L336.1 376.4 L339.1 378.7 L342.0 380.9 L345.1 383.1 L348.1 385.2 L351.1 387.2 L354.2 389.2 L357.2 391.1 L360.2 393.0 L363.3 394.9 L366.3 396.7 L369.3 398.5 L372.2 400.2 L375.1 402.0 L378.0 403.7 L380.8 405.4 L383.6 407.0 L386.3 408.7 L388.9 410.3 L391.5 411.9 L394.0 413.5 L396.3 415.0 L398.6 416.5 L400.8 418.0 L402.9 419.6 L405.3 421.4 L407.7 423.2 L410.1 425.1 L412.5 426.9 L414.9 428.8 L417.3 430.6 L419.6 432.4 L421.9 434.1 L424.1 435.9 L426.3 437.7 L428.4 439.4 L430.4 441.1 L432.3 442.8 L434.2 444.4 L435.9 446.0 L437.6 447.6 L439.1 449.1 L440.5 450.6 L441.8 451.9 L442.9 453.3 L443.9 454.5 L444.8 455.6 L445.5 456.6 L446.1 457.5 L446.6 458.3 L447.1 459.2 L447.5 460.2 L447.8 461.3 L448.1 462.5 L448.3 463.8 L448.5 465.1 L448.6 466.5 L448.6 468.0 L448.6 469.4 L448.5 470.9 L448.4 472.4 L448.1 473.9 L447.9 475.3 L447.5 476.7 L447.2 478.0 L446.8 479.3 L446.4 480.5 L445.9 481.6 L445.5 482.6 L445.1 483.4 L444.7 484.1 L444.4 484.7 L444.4 485.0 L444.5 485.1 L444.5 485.2 L444.3 485.4 L443.9 485.8 L443.2 486.1 L442.4 486.4 L441.4 486.7 L440.2 487.0 L438.9 487.2 L437.6 487.4 L436.2 487.5 L434.7 487.6 L433.2 487.6 L431.7 487.6 L430.2 487.5 L428.8 487.3 L427.4 487.2 L426.0 487.0 L424.8 486.7 L423.6 486.5 L422.6 486.2 L421.8 485.9 L421.1 485.7 L420.7 485.6 L420.4 485.5 L420.1 485.4 L419.8 485.1 L419.4 484.7 L418.9 484.1 L418.5 483.5 L418.0 482.7 L417.6 481.8 L417.1 480.9 L416.7 479.8 L416.4 478.7 L416.0 477.6 L415.7 476.5 L415.5 475.3 L415.3 474.1 L415.1 472.9 L415.0 471.8 L414.9 470.7 L414.8 469.6 L414.8 468.6 L414.8 467.7 L414.8 466.8 L414.9 466.1 L414.9 465.6 L415.0 465.3 L415.0 465.0 L415.2 464.6 L415.4 464.2 L415.8 463.7 L416.2 463.2 L416.8 462.7 L417.4 462.1 L418.1 461.6 L418.9 461.1 L419.7 460.5 L420.5 460.0 L421.3 459.5 L422.2 459.0 L423.1 458.5 L424.0 458.1 L424.8 457.7 L425.6 457.2 L426.5 456.8 L427.2 456.5 L427.9 456.1 L428.6 455.7 L429.3 455.3 L429.8 455.0 L426.2 449.0 L425.9 449.2 L425.5 449.3 L425.0 449.6 L424.3 449.8 L423.6 450.0 L422.8 450.3 L421.9 450.6 L420.9 450.9 L419.9 451.3 L418.9 451.7 L417.8 452.1 L416.8 452.5 L415.7 453.0 L414.6 453.5 L413.5 454.0 L412.4 454.6 L411.3 455.3 L410.2 456.0 L409.2 456.8 L408.2 457.7 L407.3 458.7 L406.4 459.8 L405.7 461.1 L405.1 462.4 L404.7 463.7 L404.3 464.9 L404.0 466.2 L403.8 467.5 L403.5 468.9 L403.4 470.3 L403.2 471.8 L403.1 473.3 L403.1 474.8 L403.1 476.4 L403.1 478.0 L403.2 479.6 L403.4 481.3 L403.6 482.9 L403.9 484.5 L404.2 486.2 L404.7 487.8 L405.2 489.4 L405.8 491.0 L406.6 492.6 L407.5 494.2 L408.6 495.7 L409.9 497.1 L411.3 498.4 L412.8 499.5 L414.3 500.5 L415.9 501.4 L417.5 502.2 L419.2 503.0 L421.0 503.8 L422.8 504.4 L424.7 505.1 L426.6 505.7 L428.6 506.2 L430.7 506.7 L432.8 507.2 L434.9 507.5 L437.1 507.8 L439.2 508.0 L441.4 508.1 L443.6 508.1 L445.9 508.0 L448.1 507.7 L450.4 507.3 L452.8 506.6 L455.1 505.7 L457.5 504.5 L459.6 503.0 L461.5 501.5 L463.1 500.0 L464.6 498.4 L466.0 496.7 L467.4 494.9 L468.7 493.1 L470.0 491.1 L471.2 489.1 L472.3 486.9 L473.4 484.7 L474.4 482.5 L475.4 480.1 L476.3 477.7 L477.1 475.2 L477.8 472.6 L478.3 469.9 L478.8 467.2 L479.2 464.4 L479.4 461.6 L479.5 458.6 L479.4 455.7 L479.1 452.6 L478.6 449.6 L477.9 446.5 L477.0 443.5 L475.9 440.6 L474.8 437.8 L473.5 435.0 L472.1 432.3 L470.6 429.6 L469.1 426.9 L467.5 424.3 L465.8 421.7 L464.0 419.1 L462.2 416.5 L460.4 413.9 L458.5 411.4 L456.6 408.8 L454.6 406.3 L452.7 403.8 L450.7 401.3 L448.7 398.8 L446.7 396.4 L444.8 393.9 L442.8 391.5 L440.9 389.1 L439.0 386.8 L437.1 384.4 L434.9 381.8 L432.5 379.1 L430.2 376.5 L427.7 373.9 L425.3 371.4 L422.8 368.8 L420.4 366.3 L417.9 363.8 L415.4 361.3 L412.9 358.8 L410.5 356.4 L408.0 354.0 L405.6 351.6 L403.3 349.2 L401.0 346.9 L398.7 344.6 L396.5 342.3 L394.4 340.1 L392.4 337.9 L390.5 335.7 L388.6 333.6 L386.9 331.5 L385.4 329.5 L383.9 327.6 L382.3 325.5 L380.8 323.4 L379.2 321.2 L377.7 319.0 L376.1 316.7 L374.6 314.5 L373.1 312.2 L371.6 309.9 L370.2 307.6 L368.7 305.3 L367.3 303.0 L365.9 300.7 L364.4 298.4 L363.0 296.0 L361.7 293.7 L360.3 291.4 L359.0 289.1 L357.6 286.9 L356.3 284.6 L355.0 282.4 L353.7 280.2 L352.4 278.0 L351.1 275.8 L350.0 273.7 L348.9 271.9 L348.0 270.1 L347.1 268.4 L346.1 266.5 L345.2 264.7 L344.3 262.9 L343.4 261.1 L342.5 259.3 L341.6 257.5 L340.7 255.7 L339.9 253.9 L339.1 252.2 L338.3 250.5 L337.5 248.8 L336.7 247.2 L336.0 245.6 L335.3 244.0 L334.6 242.5 L333.9 241.1 L333.2 239.7 L332.6 238.3 L331.9 23Line truncated
<path d="M318.0 268.5 L318.9 270.3 L319.8 272.2 L320.8 274.1 L321.8 276.0 L322.8 278.0 L323.8 279.9 L324.9 281.9 L326.0 283.8 L327.1 285.7 L328.3 287.7 L329.4 289.6 L330.7 291.6 L332.0 293.7 L333.4 295.9 L334.7 298.1 L336.1 300.3 L337.5 302.5 L339.0 304.8 L340.5 307.1 L342.0 309.4 L343.5 311.8 L345.0 314.1 L346.6 316.4 L348.2 318.8 L349.9 321.2 L351.5 323.5 L353.2 325.9 L354.9 328.2 L356.7 330.6 L358.4 332.9 L360.2 335.2 L362.0 337.5 L363.9 339.8 L365.8 342.0 L367.6 344.2 L369.6 346.3 L371.5 348.5 L373.6 350.6 L375.8 352.8 L378.1 355.0 L380.4 357.2 L382.8 359.4 L385.2 361.6 L387.7 363.8 L390.2 366.1 L392.7 368.3 L395.3 370.5 L397.8 372.7 L400.4 375.0 L402.9 377.2 L405.5 379.4 L408.0 381.6 L410.5 383.9 L413.0 386.1 L415.4 388.3 L417.8 390.6 L420.1 392.8 L422.4 395.1 L424.6 397.3 L426.6 399.5 L428.7 401.7 L430.8 403.8 L432.9 406.0 L435.0 408.2 L437.2 410.5 L439.3 412.7 L441.4 414.9 L443.4 417.1 L445.5 419.4 L447.5 421.6 L449.4 423.8 L451.3 426.0 L453.2 428.3 L455.0 430.5 L456.7 432.7 L458.3 434.9 L459.8 437.1 L461.3 439.3 L462.6 441.5 L463.9 443.7 L465.0 445.9 L465.9 448.1 L466.8 450.3 L467.5 452.6 L468.0 454.9 L468.4 457.2 L468.6 459.6 L468.8 461.9 L468.8 464.2 L468.6 466.5 L468.4 468.8 L468.1 471.1 L467.7 473.3 L467.3 475.5 L466.7 477.6 L466.1 479.7 L465.4 481.8 L464.7 483.8 L463.9 485.7 L463.0 487.6 L462.1 489.4 L462.8 489.7 L464.0 488.0 L465.1 486.3 L466.1 484.4 L467.1 482.4 L468.1 480.4 L468.9 478.3 L469.7 476.1 L470.4 473.8 L471.1 471.5 L471.6 469.2 L472.0 466.7 L472.3 464.3 L472.5 461.8 L472.6 459.2 L472.5 456.6 L472.2 454.0 L471.8 451.4 L471.2 448.8 L470.4 446.2 L469.5 443.7 L468.4 441.2 L467.3 438.7 L466.0 436.3 L464.6 433.8 L463.1 431.4 L461.5 428.9 L459.9 426.5 L458.1 424.1 L456.3 421.6 L454.5 419.2 L452.6 416.8 L450.7 414.4 L448.7 412.0 L446.7 409.7 L444.7 407.3 L442.6 404.9 L440.6 402.6 L438.5 400.3 L436.5 398.0 L434.5 395.7 L432.5 393.5 L430.4 391.2 L428.3 388.8 L425.9 386.4 L423.6 384.0 L421.1 381.7 L418.7 379.3 L416.2 377.0 L413.6 374.7 L411.1 372.4 L408.5 370.1 L405.9 367.9 L403.3 365.6 L400.8 363.4 L398.2 361.2 L395.7 359.0 L393.2 356.8 L390.7 354.7 L388.3 352.6 L385.9 350.4 L383.6 348.4 L381.4 346.3 L379.3 344.3 L377.2 342.3 L375.2 340.3 L373.4 338.3 L371.5 336.3 L369.6 334.2 L367.7 332.1 L365.8 330.0 L364.0 327.8 L362.2 325.6 L360.3 323.5 L358.5 321.3 L356.8 319.1 L355.0 316.9 L353.2 314.6 L351.5 312.4 L349.8 310.2 L348.1 308.0 L346.4 305.9 L344.8 303.7 L343.2 301.5 L341.6 299.4 L340.0 297.3 L338.4 295.2 L336.9 293.2 L335.4 291.2 L333.9 289.2 L332.4 287.3 L331.1 285.5 L329.8 283.8 L328.5 282.0 L327.2 280.2 L326.0 278.4 L324.7 276.6 L323.5 274.9 L322.3 273.1 L321.1 271.4 L319.9 269.7 L318.7 268.0 Z" fill="#0b0b0c"/>
<circle cx="382.7" cy="397.6" r="11.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.8"/>
<circle cx="382.7" cy="397.6" r="3.7" fill="#0b0b0c"/>
<circle cx="405.5" cy="413.0" r="10.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.2"/>
<circle cx="405.5" cy="413.0" r="3.2" fill="#0b0b0c"/>
<circle cx="426.1" cy="430.0" r="8.7" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.7"/>
<circle cx="426.1" cy="430.0" r="2.8" fill="#0b0b0c"/>
<circle cx="441.7" cy="444.3" r="7.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.2"/>
<circle cx="441.7" cy="444.3" r="2.4" fill="#0b0b0c"/>
<circle cx="451.1" cy="457.1" r="6.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.8"/>
<circle cx="451.1" cy="457.1" r="2.1" fill="#0b0b0c"/>
<circle cx="452.5" cy="470.2" r="5.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="452.5" cy="470.2" r="1.9" fill="#0b0b0c"/>
<circle cx="449.5" cy="482.2" r="5.1" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="449.5" cy="482.2" r="1.6" fill="#0b0b0c"/>
<circle cx="444.8" cy="488.7" r="4.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="436.0" cy="490.3" r="4.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="426.7" cy="489.6" r="3.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="419.4" cy="487.3" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="415.8" cy="482.4" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="413.8" cy="475.4" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="413.2" cy="468.4" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="414.9" cy="462.8" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<path d="M188.1 246.3 L188.2 247.7 L188.2 249.4 L188.3 251.0 L188.4 252.7 L188.5 254.4 L188.6 256.2 L188.8 258.1 L188.9 260.0 L189.1 261.9 L189.2 263.9 L189.4 266.0 L189.5 268.1 L189.7 270.2 L189.9 272.4 L190.0 274.7 L190.1 277.0 L190.3 279.3 L190.4 281.6 L190.5 284.0 L190.6 286.3 L190.7 288.7 L190.7 291.1 L190.8 293.5 L190.8 295.9 L190.7 298.7 L190.7 301.7 L190.6 304.8 L190.6 307.9 L190.5 311.1 L190.5 314.4 L190.4 317.7 L190.4 321.1 L190.3 324.5 L190.2 327.9 L190.1 331.3 L190.0 334.7 L189.8 338.2 L189.7 341.6 L189.5 345.0 L189.3 348.3 L189.1 351.6 L188.9 354.9 L188.7 358.0 L188.4 361.1 L188.1 364.1 L187.8 367.0 L187.5 369.7 L187.2 372.2 L186.9 374.4 L186.6 376.4 L186.3 378.4 L185.8 380.4 L185.4 382.5 L184.8 384.5 L184.1 386.7 L183.4 388.9 L182.7 391.2 L181.8 393.6 L180.9 396.0 L179.9 398.6 L178.9 401.3 L177.9 404.1 L176.8 407.0 L175.7 410.1 L174.6 413.3 L173.5 416.6 L172.5 420.1 L171.5 423.7 L170.6 427.4 L169.7 431.2 L168.9 435.2 L168.2 439.3 L167.6 443.5 L167.1 447.7 L166.7 452.1 L166.4 456.6 L166.1 461.2 L165.9 465.9 L165.6 470.6 L165.5 475.4 L165.3 480.2 L165.2 485.0 L165.1 489.8 L165.0 494.5 L165.0 499.1 L164.9 503.7 L164.8 508.1 L164.8 512.4 L164.7 516.5 L164.7 520.4 L164.6 524.0 L164.6 527.4 L164.5 530.5 L164.4 533.2 L164.3 535.6 L164.1 537.6 L203.9 542.4 L204.2 540.2 L204.7 537.5 L205.2 534.6 L205.7 531.5 L206.3 528.1 L207.0 524.5 L207.7 520.6 L208.4 516.7 L209.2 512.5 L210.0 508.3 L210.8 503.9 L211.7 499.5 L212.6 495.1 L213.6 490.6 L214.6 486.2 L215.6 481.8 L216.6 477.5 L217.6 473.3 L218.7 469.3 L219.7 465.4 L220.8 461.8 L221.8 458.4 L222.8 455.4 L223.8 452.7 L224.8 450.3 L225.7 448.1 L226.8 446.0 L227.8 443.9 L228.9 441.9 L230.1 439.9 L231.2 437.9 L232.4 436.0 L233.7 434.0 L235.0 431.9 L236.4 429.8 L237.8 427.6 L239.3 425.4 L240.8 423.0 L242.4 420.5 L244.0 417.9 L245.6 415.2 L247.2 412.3 L248.9 409.3 L250.6 406.1 L252.2 402.7 L253.8 399.2 L255.3 395.5 L256.8 391.8 L258.1 388.2 L259.4 384.6 L260.7 381.0 L261.9 377.4 L263.1 373.7 L264.3 370.1 L265.4 366.3 L266.5 362.6 L267.6 358.9 L268.7 355.2 L269.8 351.5 L270.8 347.8 L271.8 344.1 L272.8 340.4 L273.7 336.8 L274.7 333.3 L275.6 329.8 L276.5 326.4 L277.3 323.1 L278.2 319.9 L279.0 316.8 L279.8 313.8 L280.5 310.9 L281.2 308.1 L282.0 305.0 L282.7 302.0 L283.4 298.9 L284.0 295.9 L284.6 292.9 L285.2 290.0 L285.8 287.2 L286.3 284.4 L286.8 281.6 L287.3 279.0 L287.8 276.4 L288.2 273.9 L288.6 271.5 L289.0 269.2 L289.4 267.0 L289.7 264.9 L290.1 263.0 L290.4 261.1 L290.7 259.5 L291.0 258.0 L291.2 256.6 L291.4 255.5 L291.7 254.6 L291.9 253.7 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M260.5 267.7 L260.1 269.9 L259.7 272.2 L259.2 274.6 L258.7 277.1 L258.3 279.6 L257.8 282.2 L257.2 284.8 L256.7 287.5 L256.2 290.2 L255.6 293.0 L255.0 295.8 L254.4 298.6 L253.7 301.5 L253.1 304.3 L252.4 307.1 L251.7 310.0 L251.0 313.0 L250.3 316.1 L249.6 319.3 L248.8 322.6 L248.0 325.9 L247.3 329.3 L246.5 332.8 L245.6 336.3 L244.8 339.9 L244.0 343.4 L243.1 347.0 L242.3 350.6 L241.4 354.2 L240.5 357.8 L239.7 361.4 L238.8 364.9 L237.8 368.4 L236.9 371.9 L236.0 375.3 L235.0 378.6 L234.1 381.9 L233.1 385.1 L232.0 388.3 L230.9 391.4 L229.7 394.4 L228.5 397.3 L227.3 400.1 L226.0 402.9 L224.7 405.5 L223.4 408.1 L222.2 410.6 L220.9 413.1 L219.6 415.5 L218.4 417.9 L217.1 420.3 L215.9 422.6 L214.8 425.0 L213.7 427.4 L212.6 429.8 L211.5 432.3 L210.5 434.8 L209.6 437.3 L208.7 440.0 L207.8 442.7 L207.1 445.5 L206.4 448.5 L205.7 451.7 L205.1 455.2 L204.5 458.9 L203.9 462.8 L203.5 466.9 L204.4 467.1 L205.6 463.1 L206.8 459.3 L207.9 455.7 L209.0 452.4 L210.1 449.4 L211.2 446.7 L212.3 444.0 L213.4 441.5 L214.5 439.1 L215.7 436.8 L216.9 434.5 L218.2 432.3 L219.5 430.0 L220.8 427.8 L222.1 425.6 L223.5 423.4 L224.8 421.1 L226.3 418.8 L227.7 416.5 L229.1 414.0 L230.6 411.5 L232.1 408.9 L233.5 406.2 L235.0 403.4 L236.4 400.5 L237.8 397.4 L239.1 394.2 L240.4 390.9 L241.6 387.5 L242.7 384.1 L243.7 380.8 L244.7 377.3 L245.7 373.8 L246.6 370.3 L247.6 366.7 L248.4 363.1 L249.3 359.4 L250.1 355.8 L250.9 352.1 L251.6 348.4 L252.3 344.8 L253.0 341.1 L253.7 337.5 L254.3 334.0 L254.9 330.4 L255.5 327.0 L256.0 323.6 L256.5 320.2 L257.0 317.0 L257.5 313.8 L257.9 310.8 L258.3 307.9 L258.7 305.0 L259.1 302.1 L259.5 299.2 L259.8 296.3 L260.1 293.4 L260.4 290.6 L260.6 287.8 L260.8 285.1 L261.0 282.4 L261.2 279.8 L261.3 277.2 L261.4 274.8 L261.5 272.3 L261.6 270.0 L261.6 267.8 Z" fill="#0b0b0c"/>
<circle cx="200.3" cy="346.9" r="15.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="6.7"/>
<circle cx="200.3" cy="346.9" r="5.1" fill="#0b0b0c"/>
<circle cx="196.3" cy="377.3" r="14.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="6.1"/>
<circle cx="196.3" cy="377.3" r="4.6" fill="#0b0b0c"/>
<circle cx="189.0" cy="400.1" r="13.1" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.5"/>
<circle cx="189.0" cy="400.1" r="4.2" fill="#0b0b0c"/>
<circle cx="178.2" cy="429.9" r="11.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.0"/>
<circle cx="178.2" cy="429.9" r="3.8" fill="#0b0b0c"/>
<circle cx="173.6" cy="457.8" r="10.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.6"/>
<circle cx="173.6" cy="457.8" r="3.5" fill="#0b0b0c"/>
<circle cx="172.0" cy="481.0" r="10.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.2"/>
<circle cx="172.0" cy="481.0" r="3.2" fill="#0b0b0c"/>
<circle cx="171.3" cy="499.8" r="9.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.9"/>
<circle cx="171.3" cy="499.8" r="3.0" fill="#0b0b0c"/>
<circle cx="170.4" cy="520.9" r="8.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.6"/>
<circle cx="170.4" cy="520.9" r="2.7" fill="#0b0b0c"/>
<circle cx="169.8" cy="536.2" r="8.1" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.4"/>
<circle cx="169.8" cy="536.2" r="2.6" fill="#0b0b0c"/>
<path d="M222.3 255.4 L222.6 256.2 L222.8 256.8 L223.2 257.8 L223.5 259.1 L223.9 260.6 L224.4 262.3 L224.8 264.2 L225.3 266.2 L225.8 268.4 L226.3 270.7 L226.9 273.2 L227.5 275.7 L228.2 278.3 L228.8 281.1 L229.6 283.9 L230.3 286.8 L231.1 289.7 L231.9 292.7 L232.8 295.8 L233.8 298.9 L234.7 302.0 L235.8 305.2 L236.9 308.4 L238.1 311.7 L239.4 315.2 L240.8 318.6 L242.2 321.9 L243.7 325.2 L245.3 328.4 L246.9 331.5 L248.5 334.5 L250.1 337.6 L251.7 340.5 L253.4 343.4 L255.0 346.3 L256.6 349.1 L258.2 351.9 L259.7 354.6 L261.2 357.3 L262.7 359.9 L264.0 362.4 L265.4 364.9 L266.6 367.2 L267.8 369.5 L268.8 371.6 L269.8 373.6 L270.7 375.5 L271.5 377.3 L272.3 379.4 L273.1 381.7 L273.8 384.0 L274.5 386.2 L275.2 388.4 L275.8 390.7 L276.5 392.9 L277.0 395.1 L277.6 397.3 L278.1 399.4 L278.5 401.6 L278.9 403.7 L279.3 405.8 L279.7 407.9 L280.0 410.0 L280.3 412.0 L280.5 414.0 L280.7 416.0 L280.8 418.0 L280.9 419.9 L281.0 421.7 L281.1 423.6 L281.1 425.4 L281.0 427.1 L280.9 428.9 L280.8 430.7 L280.6 432.6 L280.4 434.5 L280.1 436.4 L279.8 438.3 L279.4 440.3 L278.9 442.2 L278.5 444.2 L277.9 446.1 L277.4 448.0 L276.8 449.8 L276.2 451.6 L275.6 453.3 L275.0 454.9 L274.3 456.5 L273.7 457.9 L273.0 459.2 L272.4 460.5 L271.8 461.6 L271.2 462.5 L270.7 463.3 L270.3 464.0 L270.1 464.4 L270.1 464.7 L270.0 464.9 L269.8 465.2 L269.4 465.6 L268.9 465.9 L268.2 466.2 L267.4 466.5 L266.5 466.7 L265.5 466.9 L264.5 467.0 L263.3 467.1 L262.1 467.1 L260.9 467.1 L259.6 467.0 L258.4 466.9 L257.1 466.7 L255.9 466.5 L254.8 466.3 L253.6 466.0 L252.6 465.7 L251.6 465.4 L250.7 465.1 L249.9 464.8 L249.4 464.6 L249.1 464.6 L248.7 464.4 L248.3 464.2 L247.8 463.8 L247.3 463.3 L246.8 462.7 L246.2 462.0 L245.7 461.2 L245.2 460.4 L244.7 459.5 L244.2 458.5 L243.8 457.6 L243.3 456.5 L243.0 455.5 L242.6 454.5 L242.3 453.5 L242.1 452.5 L241.9 451.6 L241.7 450.7 L241.6 449.8 L241.5 449.1 L241.4 448.4 L241.4 447.9 L241.4 447.6 L241.3 447.6 L241.2 447.5 L241.3 447.3 L241.4 447.0 L241.6 446.7 L242.0 446.3 L242.5 445.8 L243.1 445.3 L243.8 444.9 L244.5 444.4 L245.3 443.9 L246.1 443.5 L247.0 443.0 L247.9 442.6 L248.7 442.2 L249.6 441.8 L250.5 441.4 L251.3 441.1 L252.1 440.7 L252.9 440.4 L253.7 440.1 L254.4 439.7 L255.0 439.4 L255.6 439.1 L252.4 432.9 L252.1 433.0 L251.7 433.1 L251.2 433.3 L250.6 433.4 L249.8 433.6 L249.0 433.8 L248.1 434.0 L247.1 434.2 L246.1 434.4 L245.1 434.7 L244.0 435.0 L242.9 435.3 L241.8 435.6 L240.6 436.0 L239.5 436.4 L238.4 436.9 L237.3 437.4 L236.2 438.0 L235.1 438.7 L234.0 439.6 L233.0 440.5 L232.1 441.7 L231.2 443.0 L230.6 444.4 L230.2 445.7 L229.9 446.9 L229.7 448.2 L229.5 449.5 L229.3 450.8 L229.3 452.2 L229.2 453.7 L229.2 455.1 L229.3 456.6 L229.4 458.1 L229.5 459.6 L229.7 461.2 L230.0 462.8 L230.3 464.3 L230.7 465.9 L231.2 467.5 L231.7 469.1 L232.4 470.6 L233.1 472.2 L233.9 473.7 L234.9 475.2 L236.0 476.7 L237.2 478.1 L238.6 479.4 L239.9 480.4 L241.2 481.4 L242.6 482.3 L244.0 483.3 L245.5 484.2 L247.1 485.1 L248.7 485.9 L250.4 486.8 L252.2 487.5 L254.0 488.3 L255.9 489.0 L257.9 489.6 L259.9 490.2 L262.0 490.7 L264.1 491.1 L266.3 491.4 L268.6 491.5 L270.9 491.6 L273.3 491.5 L275.8 491.2 L278.3 490.7 L280.9 489.9 L283.4 488.9 L285.9 487.6 L288.1 486.2 L290.1 484.8 L292.1 483.3 L293.9 481.7 L295.7 480.0 L297.5 478.3 L299.2 476.4 L300.9 474.5 L302.6 472.5 L304.2 470.5 L305.9 468.4 L307.4 466.2 L309.0 464.0 L310.5 461.7 L311.9 459.4 L313.4 457.0 L314.7 454.6 L316.1 452.2 L317.4 449.7 L318.6 447.2 L319.8 444.6 L320.9 442.1 L322.0 439.5 L323.0 436.9 L323.9 434.2 L324.8 431.6 L325.6 428.9 L326.3 426.2 L327.1 423.5 L327.7 420.7 L328.4 417.9 L328.9 415.1 L329.5 412.2 L330.0 409.4 L330.4 406.4 L330.8 403.5 L331.2 400.6 L331.5 397.6 L331.8 394.6 L332.0 391.6 L332.2 388.5 L332.4 385.5 L332.5 382.4 L332.6 379.3 L332.6 376.2 L332.6 373.1 L332.6 370.0 L332.5 366.7 L332.3 363.1 L332.0 359.3 L331.5 355.6 L331.1 352.0 L330.5 348.3 L330.0 344.7 L329.4 341.1 L328.7 337.6 L328.1 334.1 L327.5 330.6 L326.8 327.2 L326.2 323.9 L325.5 320.6 L324.9 317.3 L324.3 314.2 L323.8 311.2 L323.3 308.3 L322.9 305.5 L322.5 302.8 L322.3 300.3 L322.1 298.0 L321.9 295.9 L321.9 294.0 L321.9 292.3 L322.0 290.5 L322.1 288.6 L322.2 286.6 L322.3 284.5 L322.4 282.4 L322.5 280.3 L322.7 278.2 L322.9 276.1 L323.1 273.9 L323.3 271.8 L323.5 269.7 L323.7 267.6 L324.0 265.5 L324.2 263.4 L324.4 261.4 L324.6 259.4 L324.8 257.5 L325.0 255.6 L325.2 253.7 L325.4 251.8 L325.5 250.0 L325.6 248.1 L325.7 246.1 L325.7 244.6 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M296.4 265.5 L296.1 267.7 L296.0 269.9 L295.8 272.2 L295.7 274.5 L295.5 276.8 L295.5 279.2 L295.4 281.6 L295.4 284.0 L295.4 286.5 L295.4 288.9 L295.5 291.3 L295.6 293.7 L295.7 296.0 L295.9 298.3 L296.1 300.6 L296.4 303.0 L296.8 305.6 L297.3 308.2 L297.8 311.0 L298.4 313.8 L299.1 316.8 L299.8 319.8 L300.5 322.8 L301.3 326.0 L302.1 329.1 L302.9 332.3 L303.8 335.5 L304.6 338.7 L305.4 342.0 L306.2 345.2 L307.0 348.4 L307.7 351.6 L308.4 354.9 L309.1 358.0 L309.7 361.2 L310.2 364.3 L310.6 367.4 L311.0 370.4 L311.3 373.3 L311.5 376.2 L311.7 379.0 L311.9 381.8 L312.0 384.6 L312.1 387.3 L312.2 390.1 L312.2 392.8 L312.2 395.6 L312.2 398.3 L312.1 400.9 L312.0 403.6 L311.9 406.2 L311.7 408.8 L311.5 411.4 L311.3 414.0 L311.0 416.5 L310.7 419.0 L310.3 421.5 L309.9 423.9 L309.5 426.3 L309.0 428.7 L308.4 431.0 L307.9 433.4 L307.2 435.7 L306.5 438.0 L305.8 440.3 L305.0 442.6 L304.1 445.0 L303.2 447.3 L302.2 449.6 L301.2 451.8 L300.2 454.1 L299.1 456.3 L298.0 458.4 L296.9 460.6 L295.7 462.6 L294.5 464.6 L293.3 466.6 L292.0 468.5 L290.8 470.3 L289.5 472.0 L288.1 473.7 L286.8 475.2 L285.4 476.7 L284.0 478.0 L282.6 479.3 L281.0 480.5 L279.4 481.5 L277.6 482.4 L275.8 483.2 L276.0 483.9 L278.0 483.4 L280.0 482.7 L281.9 481.8 L283.7 480.7 L285.4 479.6 L287.0 478.3 L288.7 476.9 L290.3 475.4 L291.8 473.9 L293.4 472.2 L294.9 470.4 L296.4 468.6 L297.9 466.7 L299.4 464.7 L300.8 462.7 L302.2 460.6 L303.6 458.4 L304.9 456.2 L306.2 453.9 L307.4 451.7 L308.6 449.3 L309.8 447.0 L310.9 444.6 L311.9 442.2 L312.9 439.8 L313.8 437.3 L314.6 434.9 L315.4 432.5 L316.1 430.0 L316.7 427.5 L317.4 425.0 L317.9 422.4 L318.4 419.8 L318.9 417.1 L319.3 414.5 L319.7 411.8 L320.0 409.1 L320.3 406.3 L320.5 403.6 L320.7 400.8 L320.9 398.0 L320.9 395.1 L321.0 392.3 L321.0 389.4 L321.0 386.5 L320.9 383.6 L320.8 380.7 L320.6 377.8 L320.4 374.9 L320.2 371.9 L319.9 368.9 L319.4 365.6 L318.9 362.3 L318.3 359.0 L317.6 355.7 L316.9 352.4 L316.0 349.1 L315.2 345.8 L314.3 342.5 L313.3 339.2 L312.4 336.0 L311.4 332.8 L310.4 329.6 L309.4 326.4 L308.5 323.4 L307.5 320.3 L306.6 317.4 L305.7 314.5 L304.8 311.7 L304.0 308.9 L303.3 306.3 L302.6 303.8 L302.0 301.5 L301.5 299.2 L301.0 297.1 L300.6 295.0 L300.3 292.8 L299.9 290.5 L299.6 288.2 L299.3 285.9 L299.0 283.5 L298.7 281.2 L298.5 278.9 L298.2 276.6 L298.0 274.3 L297.8 272.0 L297.6 269.8 L297.4 267.6 L297.2 265.4 Z" fill="#0b0b0c"/>
<circle cx="281.1" cy="380.5" r="12.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.1"/>
<circle cx="281.1" cy="380.5" r="3.9" fill="#0b0b0c"/>
<circle cx="286.0" cy="403.7" r="10.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.4"/>
<circle cx="286.0" cy="403.7" r="3.3" fill="#0b0b0c"/>
<circle cx="286.9" cy="424.7" r="9.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.8"/>
<circle cx="286.9" cy="424.7" r="2.9" fill="#0b0b0c"/>
<circle cx="284.8" cy="440.3" r="7.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.3"/>
<circle cx="284.8" cy="440.3" r="2.5" fill="#0b0b0c"/>
<circle cx="279.5" cy="455.6" r="6.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.8"/>
<circle cx="279.5" cy="455.6" r="2.2" fill="#0b0b0c"/>
<circle cx="274.1" cy="465.4" r="5.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="274.1" cy="465.4" r="1.9" fill="#0b0b0c"/>
<circle cx="268.6" cy="469.7" r="5.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="268.6" cy="469.7" r="1.7" fill="#0b0b0c"/>
<circle cx="260.2" cy="470.1" r="4.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="251.4" cy="468.1" r="4.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="246.5" cy="465.7" r="3.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="243.2" cy="461.2" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="240.9" cy="454.8" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="239.9" cy="449.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="240.8" cy="445.6" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="245.7" cy="442.4" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<clipPath id="head"><path d="M262.0 62.0 L265.2 62.1 L268.4 62.1 L271.7 62.2 L274.9 62.4 L278.2 62.5 L281.6 62.8 L284.9 63.0 L288.2 63.3 L291.6 63.6 L294.9 63.9 L298.2 64.3 L301.5 64.8 L304.8 65.2 L308.0 65.8 L311.3 66.3 L314.4 67.0 L317.6 67.6 L320.7 68.4 L323.7 69.2 L326.7 70.0 L329.6 70.9 L332.5 71.9 L335.3 72.9 L338.0 74.0 L340.7 75.2 L343.3 76.4 L345.9 77.7 L348.5 79.1 L351.0 80.5 L353.5 82.0 L356.0 83.5 L358.4 85.1 L360.8 86.8 L363.2 88.5 L365.5 90.2 L367.8 92.0 L370.0 93.8 L372.1 95.7 L374.2 97.6 L376.2 99.6 L378.2 101.5 L380.1 103.5 L381.9 105.6 L383.7 107.6 L385.4 109.7 L387.0 111.8 L388.5 113.9 L390.0 116.0 L391.4 118.2 L392.7 120.4 L394.0 122.7 L395.3 125.1 L396.4 127.5 L397.6 130.0 L398.6 132.5 L399.6 135.0 L400.6 137.6 L401.4 140.2 L402.3 142.9 L403.0 145.5 L403.7 148.1 L404.3 150.8 L404.8 153.4 L405.3 156.1 L405.6 158.7 L405.9 161.3 L406.2 163.8 L406.3 166.4 L406.4 168.9 L406.3 171.3 L406.2 173.7 L406.0 176.0 L405.7 178.3 L405.2 180.6 L404.5 182.9 L403.7 185.2 L402.8 187.4 L401.8 189.7 L400.6 192.0 L399.4 194.2 L398.1 196.4 L396.7 198.7 L395.3 200.8 L393.9 203.0 L392.4 205.1 L390.9 207.2 L389.4 209.3 L387.9 211.3 L386.5 213.3 L385.0 215.3 L383.7 217.2 L382.4 219.1 L381.1 220.9 L380.0 222.6 L378.9 224.3 L378.0 226.0 L377.2 227.6 L376.4 229.1 L375.7 230.5 L375.1 231.9 L374.5 233.2 L373.9 234.5 L373.4 235.7 L373.0 236.8 L372.5 237.9 L372.1 239.0 L371.7 240.1 L371.2 241.1 L370.8 242.1 L370.4 243.2 L370.0 244.2 L369.5 245.2 L369.0 246.2 L368.4 247.2 L367.9 248.3 L367.2 249.4 L366.5 250.5 L365.8 251.6 L364.9 252.8 L364.0 254.0 L363.0 255.3 L362.1 256.6 L361.2 257.9 L360.2 259.3 L359.3 260.7 L358.3 262.1 L357.3 263.5 L356.3 265.0 L355.3 266.4 L354.2 267.9 L353.0 269.3 L351.9 270.8 L350.6 272.2 L349.4 273.6 L348.0 275.0 L346.6 276.4 L345.1 277.7 L343.5 279.0 L341.8 280.3 L340.1 281.5 L338.2 282.7 L336.3 283.9 L334.2 285.0 L332.0 286.0 L329.7 287.0 L327.2 288.0 L324.6 289.0 L321.9 290.0 L319.0 290.9 L316.1 291.9 L313.1 292.8 L309.9 293.7 L306.7 294.6 L303.5 295.4 L300.1 296.2 L296.8 297.0 L293.3 297.7 L289.9 298.4 L286.4 299.0 L283.0 299.6 L279.5 300.2 L276.0 300.6 L272.6 301.0 L269.2 301.4 L265.8 301.6 L262.5 301.8 L259.2 302.0 L256.0 302.0 L252.8 302.0 L249.5 301.8 L246.2 301.6 L242.8 301.4 L239.4 301.0 L236.0 300.6 L232.5 300.2 L229.0 299.6 L225.6 299.0 L222.1 298.4 L218.7 297.7 L215.2 297.0 L211.9 296.2 L208.5 295.4 L205.3 294.6 L202.1 293.7 L198.9 292.8 L195.9 291.9 L193.0 290.9 L190.1 290.0 L187.4 289.0 L184.8 288.0 L182.3 287.0 L180.0 286.0 L177.8 285.0 L175.7 283.9 L173.8 282.7 L171.9 281.5 L170.2 280.3 L168.5 279.0 L166.9 277.7 L165.4 276.4 L164.0 275.0 L162.6 273.6 L161.4 272.2 L160.1 270.8 L159.0 269.3 L157.8 267.9 L156.7 266.4 L155.7 265.0 L154.7 263.5 L153.7 262.1 L152.7 260.7 L151.8 259.3 L150.8 257.9 L149.9 256.6 L149.0 255.3 L148.0 254.0 L147.1 252.8 L146.2 251.6 L145.5 250.5 L144.8 249.4 L144.1 248.3 L143.5 247.2 L143.0 246.2 L142.4 245.2 L142.0 244.2 L141.5 243.2 L141.1 242.1 L140.6 241.1 L140.2 240.1 L139.8 239.0 L139.3 237.9 L138.9 236.8 L138.4 235.7 L137.9 234.5 L137.4 233.2 L136.8 231.9 L136.2 230.5 L135.5 229.1 L134.8 227.6 L134.0 226.0 L133.1 224.3 L132.1 222.6 L131.0 220.9 L129.8 219.1 L128.6 217.3 L127.3 215.4 L125.9 213.4 L124.5 211.5 L123.1 209.5 L121.7 207.4 L120.3 205.4 L118.9 203.2 L117.5 201.1 L116.2 198.9 L114.9 196.7 L113.7 194.5 L112.6 192.3 L111.5 190.0 L110.6 187.7 L109.8 185.4 L109.1 183.1 L108.6 180.7 L108.2 178.4 L108.0 176.0 L107.9 173.6 L107.9 171.1 L108.0 168.5 L108.2 165.9 L108.5 163.2 L108.9 160.4 L109.3 157.6 L109.9 154.8 L110.5 152.0 L111.1 149.1 L111.9 146.2 L112.8 143.4 L113.7 140.5 L114.6 137.7 L115.7 134.9 L116.8 132.1 L118.0 129.3 L119.2 126.6 L120.6 124.0 L121.9 121.4 L123.4 118.9 L124.9 116.5 L126.4 114.2 L128.0 112.0 L129.7 109.8 L131.4 107.7 L133.3 105.6 L135.3 103.6 L137.3 101.6 L139.4 99.6 L141.6 97.7 L143.9 95.8 L146.2 93.9 L148.6 92.1 L151.0 90.3 L153.5 88.6 L156.0 87.0 L158.6 85.3 L161.3 83.7 L163.9 82.2 L166.6 80.7 L169.3 79.3 L172.1 78.0 L174.9 76.7 L177.6 75.4 L180.4 74.2 L183.2 73.1 L186.0 72.0 L188.8 71.0 L191.7 70.0 L194.6 69.2 L197.6 68.3 L200.7 67.6 L203.7 66.9 L206.8 66.2 L210.0 65.6 L213.2 65.1 L216.4 64.6 L219.6 64.1 L222.9 63.8 L226.1 63.4 L229.4 63.1 L232.7 62.8 L236.0 62.6 L239.3 62.4 L242.6 62.2 L245.9 62.1 L249.1 62.0 L252.4 62.0 L255.6 62.0 L258.8 62.0 Z"/></clipPath>
<path d="M262.0 62.0 L265.2 62.1 L268.4 62.1 L271.7 62.2 L274.9 62.4 L278.2 62.5 L281.6 62.8 L284.9 63.0 L288.2 63.3 L291.6 63.6 L294.9 63.9 L298.2 64.3 L301.5 64.8 L304.8 65.2 L308.0 65.8 L311.3 66.3 L314.4 67.0 L317.6 67.6 L320.7 68.4 L323.7 69.2 L326.7 70.0 L329.6 70.9 L332.5 71.9 L335.3 72.9 L338.0 74.0 L340.7 75.2 L343.3 76.4 L345.9 77.7 L348.5 79.1 L351.0 80.5 L353.5 82.0 L356.0 83.5 L358.4 85.1 L360.8 86.8 L363.2 88.5 L365.5 90.2 L367.8 92.0 L370.0 93.8 L372.1 95.7 L374.2 97.6 L376.2 99.6 L378.2 101.5 L380.1 103.5 L381.9 105.6 L383.7 107.6 L385.4 109.7 L387.0 111.8 L388.5 113.9 L390.0 116.0 L391.4 118.2 L392.7 120.4 L394.0 122.7 L395.3 125.1 L396.4 127.5 L397.6 130.0 L398.6 132.5 L399.6 135.0 L400.6 137.6 L401.4 140.2 L402.3 142.9 L403.0 145.5 L403.7 148.1 L404.3 150.8 L404.8 153.4 L405.3 156.1 L405.6 158.7 L405.9 161.3 L406.2 163.8 L406.3 166.4 L406.4 168.9 L406.3 171.3 L406.2 173.7 L406.0 176.0 L405.7 178.3 L405.2 180.6 L404.5 182.9 L403.7 185.2 L402.8 187.4 L401.8 189.7 L400.6 192.0 L399.4 194.2 L398.1 196.4 L396.7 198.7 L395.3 200.8 L393.9 203.0 L392.4 205.1 L390.9 207.2 L389.4 209.3 L387.9 211.3 L386.5 213.3 L385.0 215.3 L383.7 217.2 L382.4 219.1 L381.1 220.9 L380.0 222.6 L378.9 224.3 L378.0 226.0 L377.2 227.6 L376.4 229.1 L375.7 230.5 L375.1 231.9 L374.5 233.2 L373.9 234.5 L373.4 235.7 L373.0 236.8 L372.5 237.9 L372.1 239.0 L371.7 240.1 L371.2 241.1 L370.8 242.1 L370.4 243.2 L370.0 244.2 L369.5 245.2 L369.0 246.2 L368.4 247.2 L367.9 248.3 L367.2 249.4 L366.5 250.5 L365.8 251.6 L364.9 252.8 L364.0 254.0 L363.0 255.3 L362.1 256.6 L361.2 257.9 L360.2 259.3 L359.3 260.7 L358.3 262.1 L357.3 263.5 L356.3 265.0 L355.3 266.4 L354.2 267.9 L353.0 269.3 L351.9 270.8 L350.6 272.2 L349.4 273.6 L348.0 275.0 L346.6 276.4 L345.1 277.7 L343.5 279.0 L341.8 280.3 L340.1 281.5 L338.2 282.7 L336.3 283.9 L334.2 285.0 L332.0 286.0 L329.7 287.0 L327.2 288.0 L324.6 289.0 L321.9 290.0 L319.0 290.9 L316.1 291.9 L313.1 292.8 L309.9 293.7 L306.7 294.6 L303.5 295.4 L300.1 296.2 L296.8 297.0 L293.3 297.7 L289.9 298.4 L286.4 299.0 L283.0 299.6 L279.5 300.2 L276.0 300.6 L272.6 301.0 L269.2 301.4 L265.8 301.6 L262.5 301.8 L259.2 302.0 L256.0 302.0 L252.8 302.0 L249.5 301.8 L246.2 301.6 L242.8 301.4 L239.4 301.0 L236.0 300.6 L232.5 300.2 L229.0 299.6 L225.6 299.0 L222.1 298.4 L218.7 297.7 L215.2 297.0 L211.9 296.2 L208.5 295.4 L205.3 294.6 L202.1 293.7 L198.9 292.8 L195.9 291.9 L193.0 290.9 L190.1 290.0 L187.4 289.0 L184.8 288.0 L182.3 287.0 L180.0 286.0 L177.8 285.0 L175.7 283.9 L173.8 282.7 L171.9 281.5 L170.2 280.3 L168.5 279.0 L166.9 277.7 L165.4 276.4 L164.0 275.0 L162.6 273.6 L161.4 272.2 L160.1 270.8 L159.0 269.3 L157.8 267.9 L156.7 266.4 L155.7 265.0 L154.7 263.5 L153.7 262.1 L152.7 260.7 L151.8 259.3 L150.8 257.9 L149.9 256.6 L149.0 255.3 L148.0 254.0 L147.1 252.8 L146.2 251.6 L145.5 250.5 L144.8 249.4 L144.1 248.3 L143.5 247.2 L143.0 246.2 L142.4 245.2 L142.0 244.2 L141.5 243.2 L141.1 242.1 L140.6 241.1 L140.2 240.1 L139.8 239.0 L139.3 237.9 L138.9 236.8 L138.4 235.7 L137.9 234.5 L137.4 233.2 L136.8 231.9 L136.2 230.5 L135.5 229.1 L134.8 227.6 L134.0 226.0 L133.1 224.3 L132.1 222.6 L131.0 220.9 L129.8 219.1 L128.6 217.3 L127.3 215.4 L125.9 213.4 L124.5 211.5 L123.1 209.5 L121.7 207.4 L120.3 205.4 L118.9 203.2 L117.5 201.1 L116.2 198.9 L114.9 196.7 L113.7 194.5 L112.6 192.3 L111.5 190.0 L110.6 187.7 L109.8 185.4 L109.1 183.1 L108.6 180.7 L108.2 178.4 L108.0 176.0 L107.9 173.6 L107.9 171.1 L108.0 168.5 L108.2 165.9 L108.5 163.2 L108.9 160.4 L109.3 157.6 L109.9 154.8 L110.5 152.0 L111.1 149.1 L111.9 146.2 L112.8 143.4 L113.7 140.5 L114.6 137.7 L115.7 134.9 L116.8 132.1 L118.0 129.3 L119.2 126.6 L120.6 124.0 L121.9 121.4 L123.4 118.9 L124.9 116.5 L126.4 114.2 L128.0 112.0 L129.7 109.8 L131.4 107.7 L133.3 105.6 L135.3 103.6 L137.3 101.6 L139.4 99.6 L141.6 97.7 L143.9 95.8 L146.2 93.9 L148.6 92.1 L151.0 90.3 L153.5 88.6 L156.0 87.0 L158.6 85.3 L161.3 83.7 L163.9 82.2 L166.6 80.7 L169.3 79.3 L172.1 78.0 L174.9 76.7 L177.6 75.4 L180.4 74.2 L183.2 73.1 L186.0 72.0 L188.8 71.0 L191.7 70.0 L194.6 69.2 L197.6 68.3 L200.7 67.6 L203.7 66.9 L206.8 66.2 L210.0 65.6 L213.2 65.1 L216.4 64.6 L219.6 64.1 L222.9 63.8 L226.1 63.4 L229.4 63.1 L232.7 62.8 L236.0 62.6 L239.3 62.4 L242.6 62.2 L245.9 62.1 L249.1 62.0 L252.4 62.0 L255.6 62.0 L258.8 62.0 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="8" stroke-linejoin="round"/>
<path d="M291.9 68.8 L295.0 69.4 L298.1 70.1 L301.2 70.7 L304.2 71.4 L307.3 72.1 L310.2 72.8 L313.2 73.6 L316.0 74.4 L318.9 75.3 L321.6 76.2 L324.3 77.2 L326.9 78.2 L329.5 79.2 L332.0 80.3 L334.4 81.5 L336.8 82.7 L339.2 84.0 L341.5 85.4 L343.8 86.8 L346.1 88.2 L348.4 89.7 L350.6 91.2 L352.8 92.8 L354.9 94.5 L357.0 96.1 L359.0 97.8 L361.0 99.5 L363.0 101.3 L364.9 103.1 L366.7 104.9 L368.5 106.8 L370.2 108.6 L371.9 110.5 L373.5 112.4 L375.0 114.3 L376.5 116.2 L377.9 118.1 L379.2 120.1 L380.4 122.0 L381.7 124.1 L382.8 126.2 L384.0 128.3 L385.0 130.5 L386.1 132.8 L387.1 135.1 L388.0 137.4 L388.9 139.8 L389.7 142.1 L390.5 144.5 L391.2 147.0 L391.8 149.4 L392.4 151.8 L392.9 154.2 L393.4 156.6 L393.8 159.0 L394.1 161.4 L394.4 163.7 L394.6 166.0 L394.7 168.2 L394.7 170.4 L394.6 172.6 L394.5 174.7 L394.3 176.7 L393.9 178.7 L393.4 180.7 L392.8 182.8 L392.0 184.8 L391.2 186.9 L390.2 189.0 L389.2 191.1 L388.0 193.2 L386.8 195.3 L385.6 197.4 L384.3 199.5 L383.0 201.6 L381.7 203.6 L380.4 205.6 L379.1 207.6 L377.8 209.6 L376.5 211.5 L375.3 213.4 L374.1 215.3 L373.0 217.1 L372.0 218.8 L371.1 220.5 L370.3 222.2 L369.6 223.8 L369.0 225.3 L368.5 226.7 L368.9 226.9 L369.7 225.6 L370.6 224.3 L371.5 222.8 L372.5 221.3 L373.5 219.8 L374.7 218.2 L376.0 216.5 L377.3 214.8 L378.7 213.1 L380.1 211.3 L381.6 209.5 L383.1 207.6 L384.6 205.7 L386.1 203.8 L387.6 201.8 L389.1 199.8 L390.6 197.7 L392.0 195.6 L393.3 193.5 L394.6 191.3 L395.8 189.1 L396.9 186.9 L397.9 184.7 L398.8 182.4 L399.5 180.1 L400.1 177.7 L400.5 175.3 L400.7 173.0 L400.9 170.6 L401.0 168.2 L401.0 165.7 L400.9 163.2 L400.8 160.7 L400.5 158.1 L400.2 155.5 L399.8 152.9 L399.3 150.3 L398.7 147.7 L398.1 145.1 L397.4 142.5 L396.7 139.9 L395.8 137.3 L394.9 134.8 L393.9 132.3 L392.9 129.8 L391.8 127.3 L390.6 124.9 L389.4 122.6 L388.1 120.3 L386.8 118.1 L385.4 115.9 L384.0 113.8 L382.4 111.8 L380.8 109.7 L379.1 107.7 L377.4 105.7 L375.5 103.7 L373.7 101.7 L371.7 99.8 L369.7 98.0 L367.6 96.1 L365.5 94.3 L363.3 92.6 L361.1 90.9 L358.8 89.2 L356.4 87.6 L354.1 86.1 L351.6 84.6 L349.2 83.1 L346.7 81.8 L344.2 80.4 L341.6 79.2 L339.1 78.0 L336.5 76.9 L333.8 75.9 L331.2 74.9 L328.4 74.0 L325.6 73.2 L322.7 72.4 L319.8 71.7 L316.9 71.1 L313.9 70.5 L310.8 70.0 L307.7 69.6 L304.6 69.2 L301.5 68.8 L298.3 68.6 L295.2 68.4 L292.0 68.3 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M299.3 76.8 L302.1 77.6 L304.9 78.3 L307.6 79.1 L310.3 79.9 L312.9 80.7 L315.5 81.6 L318.0 82.5 L320.4 83.4 L322.8 84.4 L325.1 85.5 L327.3 86.6 L329.5 87.7 L331.8 88.9 L333.9 90.2 L336.1 91.5 L338.2 92.9 L340.3 94.3 L342.3 95.7 L344.4 97.2 L346.3 98.7 L348.3 100.3 L350.2 101.8 L352.0 103.5 L353.8 105.1 L355.6 106.8 L357.3 108.5 L358.9 110.2 L360.5 111.9 L362.1 113.7 L363.6 115.4 L365.0 117.2 L366.3 119.0 L367.6 120.8 L368.8 122.6 L370.0 124.4 L371.1 126.3 L372.2 128.2 L373.2 130.2 L374.2 132.3 L375.2 134.4 L376.1 136.5 L377.0 138.7 L377.8 140.9 L378.6 143.1 L379.3 145.3 L379.9 147.6 L380.5 149.8 L381.1 152.1 L381.6 154.3 L382.0 156.5 L382.4 158.7 L382.7 160.9 L382.9 163.1 L383.1 165.2 L383.2 167.3 L383.2 169.4 L383.2 171.4 L383.1 173.3 L382.8 175.2 L382.5 177.0 L382.0 178.9 L381.4 180.9 L380.7 182.8 L379.9 184.7 L379.0 186.7 L378.1 188.7 L377.0 190.6 L375.9 192.6 L374.8 194.5 L373.6 196.5 L372.4 198.4 L371.2 200.3 L370.0 202.2 L368.8 204.0 L367.6 205.8 L366.4 207.6 L365.3 209.4 L364.2 211.1 L363.2 212.8 L362.3 214.4 L361.6 216.0 L362.0 216.3 L363.1 214.9 L364.2 213.4 L365.4 211.9 L366.6 210.3 L367.9 208.7 L369.3 207.1 L370.6 205.4 L372.0 203.7 L373.4 201.9 L374.8 200.1 L376.2 198.3 L377.6 196.4 L379.0 194.5 L380.3 192.6 L381.5 190.6 L382.7 188.6 L383.8 186.6 L384.8 184.6 L385.7 182.5 L386.5 180.4 L387.2 178.2 L387.8 176.1 L388.1 173.9 L388.4 171.7 L388.6 169.5 L388.6 167.3 L388.6 165.0 L388.6 162.7 L388.4 160.4 L388.2 158.0 L387.9 155.6 L387.5 153.2 L387.1 150.8 L386.6 148.4 L386.0 146.0 L385.3 143.5 L384.6 141.1 L383.8 138.8 L383.0 136.4 L382.1 134.1 L381.1 131.8 L380.1 129.5 L379.0 127.3 L377.9 125.2 L376.7 123.0 L375.5 121.0 L374.2 119.0 L372.9 117.1 L371.4 115.2 L369.9 113.3 L368.4 111.4 L366.8 109.6 L365.1 107.7 L363.3 105.9 L361.5 104.2 L359.6 102.5 L357.7 100.8 L355.7 99.1 L353.7 97.5 L351.6 95.9 L349.5 94.4 L347.4 92.9 L345.2 91.5 L342.9 90.2 L340.7 88.8 L338.4 87.6 L336.0 86.4 L333.7 85.2 L331.3 84.1 L328.9 83.1 L326.5 82.2 L324.0 81.3 L321.4 80.5 L318.9 79.8 L316.2 79.1 L313.5 78.5 L310.8 77.9 L308.0 77.4 L305.2 77.0 L302.3 76.6 L299.4 76.3 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M304.5 85.3 L306.9 86.1 L309.3 87.0 L311.6 87.8 L313.9 88.7 L316.0 89.7 L318.2 90.7 L320.2 91.7 L322.3 92.8 L324.3 93.9 L326.3 95.1 L328.3 96.3 L330.3 97.6 L332.2 98.9 L334.1 100.2 L336.0 101.6 L337.8 103.0 L339.6 104.4 L341.3 105.9 L343.0 107.4 L344.7 108.9 L346.3 110.5 L347.9 112.0 L349.4 113.6 L350.8 115.2 L352.3 116.9 L353.6 118.5 L354.9 120.1 L356.2 121.8 L357.4 123.4 L358.5 125.1 L359.6 126.8 L360.6 128.5 L361.6 130.3 L362.5 132.2 L363.5 134.1 L364.4 136.0 L365.2 138.0 L366.0 140.0 L366.7 142.0 L367.4 144.1 L368.1 146.1 L368.7 148.2 L369.3 150.3 L369.8 152.3 L370.2 154.4 L370.6 156.5 L371.0 158.5 L371.2 160.5 L371.5 162.5 L371.6 164.5 L371.7 166.4 L371.7 168.3 L371.7 170.2 L371.6 172.0 L371.4 173.7 L371.1 175.4 L370.7 177.2 L370.1 179.0 L369.5 180.8 L368.7 182.6 L367.9 184.4 L367.0 186.2 L366.1 188.0 L365.1 189.8 L364.0 191.6 L362.9 193.4 L361.8 195.2 L360.7 197.0 L359.6 198.7 L358.5 200.4 L357.4 202.1 L356.4 203.8 L355.4 205.4 L355.8 205.7 L357.1 204.3 L358.3 202.8 L359.6 201.2 L360.9 199.7 L362.2 198.0 L363.5 196.4 L364.8 194.7 L366.1 193.0 L367.3 191.3 L368.5 189.5 L369.7 187.7 L370.8 185.9 L371.8 184.0 L372.7 182.2 L373.6 180.3 L374.3 178.3 L374.9 176.4 L375.4 174.4 L375.8 172.4 L376.0 170.5 L376.2 168.5 L376.3 166.4 L376.3 164.3 L376.2 162.2 L376.1 160.0 L375.9 157.9 L375.6 155.7 L375.2 153.5 L374.8 151.2 L374.4 149.0 L373.8 146.8 L373.2 144.6 L372.6 142.4 L371.9 140.2 L371.1 138.1 L370.3 135.9 L369.4 133.8 L368.4 131.7 L367.5 129.7 L366.4 127.7 L365.3 125.8 L364.2 123.9 L363.0 122.1 L361.8 120.3 L360.4 118.6 L359.1 116.8 L357.6 115.1 L356.1 113.4 L354.6 111.8 L353.0 110.1 L351.3 108.5 L349.6 106.9 L347.8 105.4 L346.0 103.9 L344.1 102.4 L342.2 101.0 L340.3 99.6 L338.3 98.3 L336.3 97.0 L334.2 95.7 L332.1 94.5 L330.0 93.4 L327.9 92.3 L325.7 91.2 L323.5 90.3 L321.3 89.4 L319.1 88.5 L316.8 87.7 L314.5 87.0 L312.1 86.3 L309.7 85.7 L307.2 85.2 L304.7 84.8 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M307.3 94.0 L309.3 94.9 L311.3 95.9 L313.2 96.8 L315.0 97.8 L316.9 98.9 L318.7 100.0 L320.5 101.1 L322.3 102.3 L324.1 103.5 L325.8 104.7 L327.5 106.0 L329.2 107.3 L330.8 108.6 L332.4 110.0 L334.0 111.3 L335.5 112.7 L337.0 114.2 L338.4 115.6 L339.8 117.1 L341.1 118.6 L342.4 120.0 L343.7 121.5 L344.9 123.1 L346.0 124.6 L347.1 126.1 L348.1 127.6 L349.1 129.2 L350.1 130.8 L351.0 132.4 L351.8 134.1 L352.7 135.9 L353.5 137.6 L354.3 139.4 L355.0 141.3 L355.7 143.1 L356.3 145.0 L356.9 146.9 L357.5 148.8 L358.0 150.7 L358.5 152.6 L358.9 154.5 L359.3 156.4 L359.6 158.2 L359.8 160.1 L360.0 161.9 L360.2 163.7 L360.3 165.5 L360.3 167.3 L360.3 169.0 L360.2 170.6 L360.0 172.2 L359.7 173.8 L359.3 175.5 L358.8 177.1 L358.2 178.8 L357.6 180.4 L356.8 182.1 L356.0 183.8 L355.1 185.4 L354.2 187.1 L353.3 188.8 L352.3 190.4 L351.3 192.0 L350.3 193.7 L349.3 195.3 L349.7 195.6 L351.0 194.2 L352.2 192.7 L353.4 191.2 L354.5 189.6 L355.7 188.0 L356.8 186.4 L357.8 184.8 L358.8 183.2 L359.8 181.5 L360.6 179.8 L361.4 178.1 L362.1 176.3 L362.6 174.6 L363.1 172.8 L363.4 171.0 L363.6 169.2 L363.8 167.4 L363.9 165.5 L363.9 163.6 L363.8 161.7 L363.7 159.7 L363.5 157.7 L363.3 155.7 L362.9 153.7 L362.6 151.7 L362.1 149.7 L361.7 147.7 L361.1 145.7 L360.5 143.7 L359.9 141.7 L359.2 139.7 L358.4 137.8 L357.6 135.8 L356.8 133.9 L355.9 132.1 L354.9 130.3 L353.9 128.5 L352.9 126.8 L351.8 125.2 L350.7 123.6 L349.5 122.0 L348.2 120.4 L346.9 118.8 L345.5 117.3 L344.1 115.8 L342.6 114.3 L341.1 112.8 L339.5 111.4 L337.9 110.0 L336.3 108.7 L334.6 107.3 L332.8 106.0 L331.0 104.8 L329.2 103.6 L327.4 102.4 L325.5 101.3 L323.6 100.2 L321.7 99.1 L319.7 98.2 L317.7 97.2 L315.8 96.4 L313.7 95.5 L311.7 94.8 L309.6 94.1 L307.5 93.5 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M307.8 102.9 L309.4 103.9 L311.1 104.9 L312.7 105.9 L314.4 107.0 L316.0 108.1 L317.5 109.3 L319.1 110.4 L320.6 111.6 L322.1 112.8 L323.5 114.1 L324.9 115.3 L326.3 116.6 L327.6 117.9 L328.9 119.2 L330.2 120.5 L331.4 121.9 L332.6 123.2 L333.7 124.6 L334.8 126.0 L335.9 127.4 L336.8 128.8 L337.8 130.1 L338.7 131.6 L339.5 133.0 L340.3 134.5 L341.1 136.1 L341.9 137.6 L342.6 139.3 L343.3 140.9 L344.0 142.6 L344.6 144.3 L345.2 146.0 L345.8 147.7 L346.3 149.4 L346.7 151.1 L347.2 152.9 L347.5 154.6 L347.9 156.3 L348.2 158.0 L348.4 159.7 L348.6 161.4 L348.7 163.0 L348.8 164.6 L348.9 166.2 L348.8 167.8 L348.8 169.3 L348.6 170.7 L348.3 172.2 L348.0 173.7 L347.5 175.2 L347.0 176.7 L346.4 178.3 L345.7 179.8 L345.0 181.3 L344.2 182.8 L343.4 184.4 L342.5 185.9 L343.0 186.2 L344.0 184.8 L345.0 183.4 L346.0 181.9 L346.9 180.4 L347.8 178.9 L348.5 177.4 L349.2 175.9 L349.8 174.3 L350.3 172.7 L350.8 171.1 L351.0 169.5 L351.2 167.9 L351.4 166.3 L351.5 164.6 L351.5 162.9 L351.4 161.2 L351.3 159.4 L351.1 157.6 L350.9 155.8 L350.6 154.0 L350.3 152.2 L349.9 150.4 L349.5 148.5 L349.0 146.7 L348.5 144.9 L347.9 143.1 L347.3 141.3 L346.6 139.6 L345.8 137.9 L345.1 136.2 L344.3 134.5 L343.4 132.9 L342.5 131.3 L341.6 129.7 L340.6 128.3 L339.6 126.8 L338.5 125.4 L337.4 124.0 L336.2 122.6 L334.9 121.2 L333.7 119.8 L332.3 118.5 L330.9 117.2 L329.5 115.9 L328.1 114.6 L326.6 113.4 L325.0 112.2 L323.5 111.0 L321.8 109.9 L320.2 108.8 L318.5 107.8 L316.8 106.7 L315.1 105.8 L313.4 104.9 L311.6 104.0 L309.8 103.2 L308.0 102.4 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M343.5 267.5 L342.1 268.7 L340.7 269.9 L339.2 271.1 L337.7 272.3 L336.0 273.4 L334.3 274.4 L332.5 275.5 L330.7 276.4 L328.7 277.4 L326.6 278.2 L324.4 279.1 L322.1 279.9 L319.6 280.7 L317.0 281.5 L314.3 282.4 L311.5 283.1 L308.6 283.9 L305.6 284.7 L302.6 285.4 L299.5 286.1 L296.3 286.8 L293.2 287.4 L289.9 288.1 L286.7 288.6 L283.4 289.2 L280.2 289.7 L276.9 290.1 L273.7 290.5 L270.4 290.9 L267.3 291.1 L264.1 291.4 L261.0 291.6 L258.0 291.7 L255.0 291.7 L252.0 291.7 L249.0 291.6 L245.9 291.4 L242.7 291.2 L239.6 290.9 L236.3 290.6 L233.1 290.2 L229.8 289.7 L226.6 289.2 L223.3 288.7 L220.0 288.1 L216.8 287.5 L213.6 286.9 L210.5 286.2 L207.4 285.5 L204.3 284.8 L201.4 284.0 L198.5 283.3 L195.7 282.5 L193.0 281.7 L190.4 280.9 L187.9 280.0 L185.5 279.2 L183.3 278.4 L181.2 277.5 L179.2 276.6 L177.4 275.6 L175.6 274.6 L173.8 273.5 L172.2 272.4 L170.6 271.3 L169.1 270.2 L168.8 270.5 L170.1 272.0 L171.5 273.3 L173.0 274.6 L174.7 275.9 L176.4 277.2 L178.3 278.4 L180.2 279.5 L182.3 280.6 L184.5 281.7 L186.8 282.8 L189.3 283.8 L191.9 284.9 L194.6 285.9 L197.3 286.9 L200.2 287.9 L203.2 288.8 L206.2 289.8 L209.4 290.7 L212.5 291.5 L215.8 292.4 L219.0 293.1 L222.3 293.9 L225.6 294.6 L228.9 295.2 L232.3 295.7 L235.6 296.2 L238.9 296.7 L242.2 297.0 L245.5 297.3 L248.7 297.5 L251.9 297.7 L255.0 297.7 L258.1 297.7 L261.3 297.5 L264.5 297.3 L267.8 297.1 L271.1 296.7 L274.4 296.3 L277.7 295.8 L281.1 295.2 L284.4 294.6 L287.7 294.0 L291.0 293.2 L294.3 292.5 L297.5 291.6 L300.7 290.8 L303.8 289.9 L306.8 289.0 L309.8 288.0 L312.7 287.0 L315.5 286.0 L318.2 285.0 L320.8 283.9 L323.2 282.9 L325.6 281.8 L327.8 280.8 L329.9 279.7 L331.8 278.5 L333.7 277.3 L335.4 276.1 L337.1 274.8 L338.6 273.5 L340.1 272.1 L341.4 270.8 L342.7 269.3 L343.9 267.9 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M327.9 269.8 L326.1 270.8 L324.2 271.7 L322.2 272.5 L320.1 273.3 L317.8 274.1 L315.5 274.9 L313.0 275.7 L310.4 276.5 L307.8 277.3 L305.0 278.1 L302.2 278.8 L299.3 279.5 L296.4 280.2 L293.4 280.9 L290.4 281.5 L287.3 282.1 L284.2 282.7 L281.1 283.2 L278.0 283.7 L274.9 284.1 L271.8 284.5 L268.7 284.8 L265.7 285.1 L262.7 285.3 L259.7 285.5 L256.8 285.6 L254.0 285.7 L251.2 285.6 L248.3 285.5 L245.3 285.4 L242.3 285.1 L239.3 284.9 L236.2 284.5 L233.1 284.2 L230.0 283.7 L226.9 283.2 L223.8 282.7 L220.7 282.2 L217.6 281.6 L214.6 281.0 L211.6 280.3 L208.6 279.6 L205.8 278.9 L202.9 278.2 L200.2 277.4 L197.5 276.6 L195.0 275.9 L192.5 275.1 L190.1 274.3 L187.9 273.5 L185.8 272.7 L183.7 271.8 L183.5 272.3 L185.4 273.3 L187.5 274.3 L189.7 275.3 L192.0 276.3 L194.5 277.3 L197.0 278.2 L199.6 279.2 L202.4 280.1 L205.2 281.0 L208.1 281.8 L211.0 282.7 L214.0 283.5 L217.0 284.2 L220.1 284.9 L223.2 285.6 L226.3 286.2 L229.5 286.8 L232.6 287.3 L235.8 287.8 L238.9 288.2 L242.0 288.5 L245.1 288.8 L248.1 289.0 L251.1 289.1 L254.0 289.1 L256.9 289.1 L259.9 289.0 L262.9 288.8 L266.0 288.6 L269.1 288.2 L272.2 287.8 L275.4 287.4 L278.5 286.9 L281.7 286.3 L284.8 285.7 L287.9 285.0 L291.0 284.3 L294.0 283.5 L297.0 282.7 L300.0 281.9 L302.9 281.1 L305.7 280.2 L308.4 279.3 L311.0 278.3 L313.6 277.4 L316.0 276.4 L318.3 275.5 L320.6 274.5 L322.6 273.5 L324.6 272.5 L326.4 271.4 L328.1 270.3 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M195.9 103.9 L195.3 104.2 L194.7 104.6 L193.9 105.0 L193.1 105.5 L192.3 106.0 L191.4 106.6 L190.4 107.2 L189.4 107.8 L188.4 108.5 L187.3 109.2 L186.3 110.0 L185.2 110.8 L184.1 111.6 L183.0 112.5 L181.9 113.4 L180.8 114.3 L179.7 115.2 L178.7 116.2 L177.7 117.2 L176.8 118.2 L175.9 119.2 L175.0 120.2 L174.2 121.3 L173.5 122.4 L172.8 123.5 L172.2 124.6 L171.6 125.8 L171.0 127.0 L170.5 128.3 L170.0 129.6 L169.5 130.9 L169.1 132.2 L168.7 133.6 L168.4 134.9 L168.0 136.3 L167.7 137.6 L167.5 138.9 L167.2 140.2 L167.0 141.4 L166.8 142.6 L166.6 143.7 L166.4 144.8 L166.3 145.9 L166.2 146.9 L166.1 147.7 L166.0 148.6 L165.9 149.3 L165.9 149.9 L166.1 150.1 L166.5 149.5 L166.9 148.9 L167.3 148.2 L167.8 147.4 L168.2 146.5 L168.7 145.5 L169.2 144.5 L169.7 143.5 L170.2 142.4 L170.7 141.3 L171.2 140.1 L171.8 138.9 L172.3 137.7 L172.9 136.5 L173.4 135.3 L174.0 134.1 L174.6 132.9 L175.1 131.8 L175.7 130.6 L176.3 129.5 L176.8 128.5 L177.4 127.5 L178.0 126.5 L178.5 125.6 L179.1 124.8 L179.7 123.9 L180.5 122.9 L181.2 122.0 L182.0 121.0 L182.8 120.0 L183.7 119.0 L184.5 118.0 L185.4 117.0 L186.3 116.0 L187.2 115.0 L188.1 114.0 L189.0 113.0 L189.8 112.0 L190.6 111.0 L191.5 110.1 L192.2 109.2 L193.0 108.3 L193.6 107.5 L194.3 106.7 L194.8 106.0 L195.4 105.3 L195.8 104.7 L196.1 104.1 Z" fill="#0b0b0c"/>
<path d="M221.9 95.9 L221.5 96.0 L221.0 96.2 L220.5 96.5 L220.0 96.7 L219.4 97.1 L218.8 97.5 L218.2 97.9 L217.6 98.3 L217.0 98.8 L216.4 99.4 L215.8 99.9 L215.3 100.6 L214.8 101.2 L214.3 101.9 L213.9 102.5 L213.5 103.2 L213.2 103.9 L212.9 104.6 L212.6 105.2 L212.4 105.9 L212.2 106.4 L212.0 107.0 L211.9 107.5 L211.9 107.9 L212.1 108.1 L212.5 108.0 L213.0 107.8 L213.5 107.5 L214.0 107.3 L214.6 106.9 L215.2 106.5 L215.8 106.1 L216.4 105.7 L217.0 105.2 L217.6 104.6 L218.2 104.1 L218.7 103.4 L219.2 102.8 L219.7 102.1 L220.1 101.5 L220.5 100.8 L220.8 100.1 L221.1 99.4 L221.4 98.8 L221.6 98.1 L221.8 97.6 L222.0 97.0 L222.1 96.5 L222.1 96.1 Z" fill="#0b0b0c"/>
<path d="M287.9 98.1 L288.4 98.6 L288.9 99.1 L289.6 99.6 L290.3 100.2 L291.1 100.8 L291.9 101.4 L292.8 102.0 L293.8 102.7 L294.7 103.4 L295.8 104.1 L296.8 104.8 L297.9 105.5 L299.0 106.2 L300.1 107.0 L301.1 107.7 L302.2 108.5 L303.3 109.2 L304.4 110.0 L305.4 110.7 L306.4 111.4 L307.4 112.2 L308.3 112.9 L309.2 113.6 L310.0 114.3 L310.9 115.0 L311.7 115.8 L312.5 116.6 L313.4 117.5 L314.3 118.4 L315.2 119.3 L316.1 120.3 L317.1 121.2 L318.0 122.2 L318.9 123.2 L319.9 124.2 L320.8 125.2 L321.7 126.1 L322.6 127.1 L323.5 128.0 L324.3 128.9 L325.1 129.8 L325.9 130.6 L326.7 131.3 L327.4 132.0 L328.1 132.7 L328.7 133.2 L329.3 133.7 L329.9 134.1 L330.1 133.9 L329.9 133.3 L329.6 132.6 L329.2 131.8 L328.8 131.0 L328.4 130.1 L327.9 129.2 L327.4 128.2 L326.8 127.1 L326.2 126.0 L325.6 124.9 L324.9 123.7 L324.2 122.6 L323.5 121.4 L322.7 120.2 L322.0 119.0 L321.2 117.9 L320.3 116.7 L319.5 115.6 L318.6 114.5 L317.7 113.5 L316.8 112.5 L315.9 111.5 L314.9 110.6 L314.0 109.7 L313.0 108.9 L311.9 108.1 L310.8 107.4 L309.7 106.6 L308.5 105.9 L307.3 105.2 L306.1 104.6 L304.9 104.0 L303.6 103.4 L302.4 102.8 L301.1 102.3 L299.9 101.8 L298.6 101.3 L297.4 100.8 L296.3 100.4 L295.1 100.0 L294.0 99.6 L293.0 99.3 L292.0 99.0 L291.1 98.7 L290.2 98.4 L289.4 98.2 L288.7 98.0 L288.1 97.9 Z" fill="#0b0b0c"/>
<circle cx="172" cy="214" r="52" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7"/>
<circle cx="176" cy="217" r="37" fill="#c2672b" stroke="#0b0b0c" stroke-width="5"/>
<ellipse cx="178.0" cy="218" rx="26" ry="18" fill="#0b0b0c"/>
<circle cx="169.0" cy="210" r="7.5" fill="#efe9dc"/>
<circle cx="188.0" cy="224" r="3.5" fill="#efe9dc"/>
<path d="M122.7 196.7 L123.6 196.1 L124.5 195.3 L125.5 194.3 L126.6 193.3 L127.7 192.2 L128.9 190.9 L130.2 189.6 L131.5 188.2 L132.9 186.8 L134.2 185.3 L135.7 183.9 L137.1 182.4 L138.6 180.9 L140.1 179.4 L141.6 178.0 L143.1 176.5 L144.6 175.2 L146.1 173.9 L147.6 172.8 L149.0 171.7 L150.4 170.7 L151.7 169.9 L153.0 169.2 L154.2 168.6 L155.5 168.1 L156.9 167.7 L158.4 167.2 L159.9 166.8 L161.5 166.4 L163.1 166.1 L164.8 165.8 L166.5 165.6 L168.2 165.4 L169.9 165.2 L171.7 165.1 L173.4 165.0 L175.2 164.9 L176.9 164.9 L178.7 164.9 L180.4 164.9 L182.1 165.0 L183.7 165.1 L185.3 165.3 L186.9 165.5 L188.4 165.7 L189.9 165.9 L191.2 166.2 L192.5 166.5 L193.6 166.8 L194.8 167.2 L196.0 167.8 L197.2 168.4 L198.4 169.1 L199.7 169.9 L201.0 170.8 L202.2 171.8 L203.5 172.8 L204.8 173.8 L206.0 174.9 L207.3 176.0 L208.5 177.1 L209.7 178.2 L210.9 179.3 L212.0 180.4 L213.1 181.4 L214.1 182.4 L215.1 183.3 L216.0 184.2 L216.9 185.0 L217.8 185.7 L218.6 186.3 L219.3 186.7 L220.7 185.3 L220.3 184.6 L219.8 183.8 L219.3 183.0 L218.7 182.0 L218.0 180.9 L217.3 179.8 L216.5 178.5 L215.7 177.3 L214.9 175.9 L213.9 174.6 L213.0 173.2 L212.0 171.8 L210.9 170.4 L209.8 168.9 L208.6 167.5 L207.4 166.2 L206.1 164.8 L204.8 163.6 L203.4 162.3 L201.9 161.2 L200.4 160.1 L198.9 159.1 L197.2 158.2 L195.5 157.5 L193.9 156.9 L192.2 156.4 L190.5 155.9 L188.7 155.5 L186.8 155.1 L185.0 154.8 L183.1 154.5 L181.1 154.3 L179.1 154.2 L177.1 154.1 L175.1 154.0 L173.1 154.0 L171.0 154.1 L169.0 154.2 L167.0 154.4 L164.9 154.7 L162.9 155.0 L160.9 155.4 L159.0 155.9 L157.1 156.5 L155.2 157.1 L153.3 157.7 L151.5 158.5 L149.8 159.4 L148.0 160.4 L146.2 161.5 L144.5 162.8 L142.9 164.3 L141.3 165.8 L139.8 167.3 L138.3 169.0 L136.9 170.7 L135.5 172.5 L134.2 174.3 L132.9 176.1 L131.6 177.9 L130.4 179.7 L129.3 181.5 L128.2 183.2 L127.2 185.0 L126.2 186.6 L125.3 188.2 L124.4 189.7 L123.6 191.0 L122.9 192.3 L122.3 193.4 L121.7 194.4 L121.3 195.3 Z" fill="#0b0b0c"/>
<path d="M137.9 258.2 L138.6 258.7 L139.4 259.3 L140.3 259.9 L141.2 260.6 L142.3 261.4 L143.5 262.2 L144.7 263.1 L146.0 264.0 L147.4 264.9 L148.8 265.8 L150.3 266.8 L151.8 267.7 L153.3 268.6 L155.0 269.5 L156.6 270.4 L158.3 271.2 L159.9 271.9 L161.6 272.6 L163.4 273.3 L165.1 273.8 L166.8 274.3 L168.5 274.6 L170.2 274.9 L171.9 275.0 L173.6 275.0 L175.4 274.8 L177.1 274.6 L178.9 274.2 L180.7 273.8 L182.5 273.3 L184.2 272.7 L186.0 272.0 L187.8 271.3 L189.6 270.6 L191.3 269.8 L193.0 268.9 L194.6 268.1 L196.2 267.2 L197.8 266.4 L199.3 265.5 L200.7 264.7 L202.0 263.9 L203.3 263.2 L204.4 262.5 L205.5 261.8 L206.5 261.2 L207.3 260.7 L208.1 260.2 L207.9 259.8 L207.0 259.9 L206.0 260.1 L204.9 260.4 L203.7 260.7 L202.4 261.2 L201.0 261.6 L199.5 262.1 L197.9 262.6 L196.3 263.1 L194.7 263.7 L193.0 264.3 L191.3 264.8 L189.5 265.4 L187.8 265.9 L186.1 266.4 L184.3 266.9 L182.6 267.4 L180.9 267.8 L179.3 268.2 L177.7 268.5 L176.2 268.7 L174.7 268.9 L173.4 269.0 L172.1 269.0 L170.8 268.9 L169.5 268.8 L168.0 268.5 L166.6 268.2 L165.0 267.8 L163.5 267.4 L161.9 266.9 L160.3 266.3 L158.6 265.7 L157.0 265.1 L155.3 264.5 L153.7 263.8 L152.1 263.1 L150.5 262.5 L149.0 261.8 L147.5 261.2 L146.0 260.6 L144.7 260.0 L143.3 259.5 L142.1 259.0 L141.0 258.6 L139.9 258.2 L138.9 257.9 L138.1 257.8 Z" fill="#0b0b0c"/>
<circle cx="340" cy="214" r="52" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7"/>
<circle cx="336" cy="217" r="37" fill="#c2672b" stroke="#0b0b0c" stroke-width="5"/>
<ellipse cx="334.0" cy="218" rx="26" ry="18" fill="#0b0b0c"/>
<circle cx="325.0" cy="210" r="7.5" fill="#efe9dc"/>
<circle cx="344.0" cy="224" r="3.5" fill="#efe9dc"/>
<path d="M390.7 195.3 L390.3 194.4 L389.7 193.4 L389.1 192.3 L388.4 191.0 L387.6 189.7 L386.7 188.2 L385.8 186.6 L384.8 185.0 L383.8 183.2 L382.7 181.5 L381.6 179.7 L380.4 177.9 L379.1 176.1 L377.8 174.3 L376.5 172.5 L375.1 170.7 L373.7 169.0 L372.2 167.3 L370.7 165.8 L369.1 164.3 L367.5 162.8 L365.8 161.5 L364.0 160.4 L362.2 159.4 L360.5 158.5 L358.7 157.7 L356.8 157.1 L354.9 156.5 L353.0 155.9 L351.1 155.4 L349.1 155.0 L347.1 154.7 L345.0 154.4 L343.0 154.2 L341.0 154.1 L338.9 154.0 L336.9 154.0 L334.9 154.1 L332.9 154.2 L330.9 154.3 L328.9 154.5 L327.0 154.8 L325.2 155.1 L323.3 155.5 L321.5 155.9 L319.8 156.4 L318.1 156.9 L316.5 157.5 L314.8 158.2 L313.1 159.1 L311.6 160.1 L310.1 161.2 L308.6 162.3 L307.2 163.6 L305.9 164.8 L304.6 166.2 L303.4 167.5 L302.2 168.9 L301.1 170.4 L300.0 171.8 L299.0 173.2 L298.1 174.6 L297.1 175.9 L296.3 177.3 L295.5 178.5 L294.7 179.8 L294.0 180.9 L293.3 182.0 L292.7 183.0 L292.2 183.8 L291.7 184.6 L291.3 185.3 L292.7 186.7 L293.4 186.3 L294.2 185.7 L295.1 185.0 L296.0 184.2 L296.9 183.3 L297.9 182.4 L298.9 181.4 L300.0 180.4 L301.1 179.3 L302.3 178.2 L303.5 177.1 L304.7 176.0 L306.0 174.9 L307.2 173.8 L308.5 172.8 L309.8 171.8 L311.0 170.8 L312.3 169.9 L313.6 169.1 L314.8 168.4 L316.0 167.8 L317.2 167.2 L318.4 166.8 L319.5 166.5 L320.8 166.2 L322.1 165.9 L323.6 165.7 L325.1 165.5 L326.7 165.3 L328.3 165.1 L329.9 165.0 L331.6 164.9 L333.3 164.9 L335.1 164.9 L336.8 164.9 L338.6 165.0 L340.3 165.1 L342.1 165.2 L343.8 165.4 L345.5 165.6 L347.2 165.8 L348.9 166.1 L350.5 166.4 L352.1 166.8 L353.6 167.2 L355.1 167.7 L356.5 168.1 L357.8 168.6 L359.0 169.2 L360.3 169.9 L361.6 170.7 L363.0 171.7 L364.4 172.8 L365.9 173.9 L367.4 175.2 L368.9 176.5 L370.4 178.0 L371.9 179.4 L373.4 180.9 L374.9 182.4 L376.3 183.9 L377.8 185.3 L379.1 186.8 L380.5 188.2 L381.8 189.6 L383.1 190.9 L384.3 192.2 L385.4 193.3 L386.5 194.3 L387.5 195.3 L388.4 196.1 L389.3 196.7 Z" fill="#0b0b0c"/>
<path d="M373.9 257.8 L373.1 257.9 L372.1 258.2 L371.0 258.6 L369.9 259.0 L368.7 259.5 L367.3 260.0 L366.0 260.6 L364.5 261.2 L363.0 261.8 L361.5 262.5 L359.9 263.1 L358.3 263.8 L356.7 264.5 L355.0 265.1 L353.4 265.7 L351.7 266.3 L350.1 266.9 L348.5 267.4 L347.0 267.8 L345.4 268.2 L344.0 268.5 L342.5 268.8 L341.2 268.9 L339.9 269.0 L338.6 269.0 L337.3 268.9 L335.8 268.7 L334.3 268.5 L332.7 268.2 L331.1 267.8 L329.4 267.4 L327.7 266.9 L325.9 266.4 L324.2 265.9 L322.5 265.4 L320.7 264.8 L319.0 264.3 L317.3 263.7 L315.7 263.1 L314.1 262.6 L312.5 262.1 L311.0 261.6 L309.6 261.2 L308.3 260.7 L307.1 260.4 L306.0 260.1 L305.0 259.9 L304.1 259.8 L303.9 260.2 L304.7 260.7 L305.5 261.2 L306.5 261.8 L307.6 262.5 L308.7 263.2 L310.0 263.9 L311.3 264.7 L312.7 265.5 L314.2 266.4 L315.8 267.2 L317.4 268.1 L319.0 268.9 L320.7 269.8 L322.4 270.6 L324.2 271.3 L326.0 272.0 L327.8 272.7 L329.5 273.3 L331.3 273.8 L333.1 274.2 L334.9 274.6 L336.6 274.8 L338.4 275.0 L340.1 275.0 L341.8 274.9 L343.5 274.6 L345.2 274.3 L346.9 273.8 L348.6 273.3 L350.4 272.6 L352.1 271.9 L353.7 271.2 L355.4 270.4 L357.0 269.5 L358.7 268.6 L360.2 267.7 L361.7 266.8 L363.2 265.8 L364.6 264.9 L366.0 264.0 L367.3 263.1 L368.5 262.2 L369.7 261.4 L370.8 260.6 L371.7 259.9 L372.6 259.3 L373.4 258.7 L374.1 258.2 Z" fill="#0b0b0c"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

+164
View File
@@ -0,0 +1,164 @@
"""TextureCraft app icon: an octopus drawn in code, written to icon.svg beside this file.
Original artwork (no traced or third-party source), MIT OR Apache-2.0 like the rest of the repo.
Follows craftrules standards/icon-design.md: 512 tile with rx=112, three colours only (ink, paper,
TextureCraft copper), a tight head-and-shoulders portrait with big eyes, carved lines that swell
and taper. Edit the shapes here, run `python3 assets/app-icon/icon.py`, then `packaging/icons.sh`
to render every PNG, the .ico and the .icns. Plain Python 3, no dependencies.
"""
import math
from pathlib import Path
INK, PAPER, APP = "#0b0b0c", "#efe9dc", "#c2672b"
def catmull(pts, n=24, closed=False):
out = []
m = len(pts)
segs = m if closed else m - 1
for i in range(segs):
g = (lambda k: pts[k % m]) if closed else (lambda k: pts[min(max(k, 0), m - 1)])
p0, p1, p2, p3 = g(i - 1), g(i), g(i + 1), g(i + 2)
for s in range(n):
t = s / n
t2, t3 = t * t, t * t * t
out.append(tuple(0.5 * ((2 * p1[j]) + (-p0[j] + p2[j]) * t + (2 * p0[j] - 5 * p1[j] + 4 * p2[j] - p3[j]) * t2
+ (-p0[j] + 3 * p1[j] - 3 * p2[j] + p3[j]) * t3) for j in range(2)))
if not closed:
out.append(pts[-1])
return out
def arclen(pts):
acc = [0.0]
for a, b in zip(pts, pts[1:]):
acc.append(acc[-1] + math.dist(a, b))
total = acc[-1] or 1.0
return [a / total for a in acc]
def normals(pts):
out = []
for i in range(len(pts)):
a = pts[max(i - 1, 0)]
b = pts[min(i + 1, len(pts) - 1)]
dx, dy = b[0] - a[0], b[1] - a[1]
d = math.hypot(dx, dy) or 1.0
out.append((-dy / d, dx / d))
return out
def path(pts, close=True):
s = "M" + " L".join(f"{x:.1f} {y:.1f}" for x, y in pts)
return s + (" Z" if close else "")
def ribbon(center, width, offset=lambda u: 0.0, u0=0.0, u1=1.0):
"""Closed outline of a stroke along `center` whose width (and sideways offset) vary with u."""
us = arclen(center)
ns = normals(center)
left, right = [], []
for p, n, u in zip(center, ns, us):
if u < u0 or u > u1:
continue
v = (u - u0) / ((u1 - u0) or 1)
w, o = width(v) / 2, offset(u)
left.append((p[0] + n[0] * (o + w), p[1] + n[1] * (o + w)))
right.append((p[0] + n[0] * (o - w), p[1] + n[1] * (o - w)))
return left + right[::-1]
def swell(peak, lo=0.0):
"""Carved line: thin at both ends, `peak` wide in the middle."""
return lambda v: lo + (peak - lo) * math.sin(math.pi * min(max(v, 0), 1)) ** 0.8
def at(center, u):
us = arclen(center)
ns = normals(center)
for i in range(1, len(us)):
if us[i] >= u:
return center[i], ns[i]
return center[-1], ns[-1]
out = []
el = out.append
def arm(points, base, tip, side, suckers=(0.45, 0.97), shade=(0.05, 0.75)):
"""An arm: paper body with ink contour, a carved shading line, suckers along `side`."""
c = catmull(points)
w = lambda v: tip + (base - tip) * (1 - v) ** 1.15
el(f'<path d="{path(ribbon(c, w))}" fill="{PAPER}" stroke="{INK}" stroke-width="7" stroke-linejoin="round"/>')
# Shading line on the side away from the suckers.
el(f'<path d="{path(ribbon(c, swell(9, 0.6), offset=lambda u: -side * w(u) * 0.22, u0=shade[0], u1=shade[1]))}" fill="{INK}"/>')
# Suckers: paper discs with an ink ring and a dark centre, shrinking toward the tip.
u = suckers[0]
while u < suckers[1]:
p, n = at(c, u)
r = max(w(u) * 0.2, 3.2)
cx, cy = p[0] + n[0] * side * w(u) * 0.36, p[1] + n[1] * side * w(u) * 0.36
el(f'<circle cx="{cx:.1f}" cy="{cy:.1f}" r="{r:.1f}" fill="{PAPER}" stroke="{INK}" stroke-width="{max(2.6, r * 0.42):.1f}"/>')
if r > 5:
el(f'<circle cx="{cx:.1f}" cy="{cy:.1f}" r="{r * 0.32:.1f}" fill="{INK}"/>')
u += max(r * 2.9, 8) / 420
# Arms, back to front.
arm([(206, 262), (140, 292), (78, 300), (38, 278), (32, 242), (58, 226), (80, 242), (70, 262)], 96, 7, 1, suckers=(0.42, 0.97)) # left curl
arm([(306, 262), (372, 292), (434, 300), (474, 278), (480, 242), (454, 226), (432, 242), (442, 262)], 96, 7, -1, suckers=(0.42, 0.97)) # right curl
arm([(222, 262), (196, 300), (150, 352), (104, 424), (76, 540)], 98, 34, -1, suckers=(0.3, 1.0)) # left, off the bottom
arm([(290, 262), (316, 300), (360, 352), (420, 402), (462, 452), (452, 494), (416, 492), (410, 464), (428, 452)], 98, 7, 1, suckers=(0.4, 0.97)) # right, curl
arm([(240, 250), (236, 302), (222, 382), (196, 446), (184, 540)], 104, 40, 1, suckers=(0.34, 1.0)) # front left
arm([(274, 250), (280, 302), (302, 372), (302, 432), (278, 476), (244, 472), (236, 446), (254, 436)], 104, 7, 1, suckers=(0.4, 0.97)) # front right curl
# Head: mantle + eye region, one silhouette.
head = catmull([(262, 62), (338, 74), (390, 116), (406, 176), (378, 226), (364, 254), (332, 286), (256, 302), (180, 286),
(148, 254), (134, 226), (108, 176), (128, 112), (186, 72)], closed=True)
el(f'<clipPath id="head"><path d="{path(head)}"/></clipPath>')
el(f'<path d="{path(head)}" fill="{PAPER}" stroke="{INK}" stroke-width="8" stroke-linejoin="round"/>')
# Engraved shading: contour-following lines that thicken toward the shadow side (right and below).
cx0, cy0 = 236, 156
for k, f in enumerate([0.95, 0.88, 0.81, 0.74, 0.67]):
ring = [(cx0 + (x - cx0) * f, cy0 + (y - cy0) * f) for x, y in head]
n = len(ring)
# Right flank of the mantle, in shadow.
arc = ring[int(n * (0.03 + k * 0.012)):int(n * (0.30 - k * 0.012))]
el(f'<path d="{path(ribbon(arc, swell(7.5 - k * 1.0, 0.5)))}" fill="{INK}" clip-path="url(#head)"/>')
for k, f in enumerate([0.95, 0.9]):
ring = [(cx0 + (x - cx0) * f, cy0 + (y - cy0) * f) for x, y in head]
n = len(ring)
# Under the head, where the arms join.
arc = ring[int(n * (0.40 + k * 0.02)):int(n * (0.60 - k * 0.02))]
el(f'<path d="{path(ribbon(arc, swell(6 - k * 2.5, 0.5)))}" fill="{INK}" clip-path="url(#head)"/>')
# A few carved strokes over the dome (texture), left side lighter.
for pts, wd in [([(196, 104), (176, 124), (166, 150)], 6), ([(222, 96), (212, 108)], 4.5), ([(288, 98), (312, 112), (330, 134)], 6)]:
el(f'<path d="{path(ribbon(catmull(pts), swell(wd, 0.3)))}" fill="{INK}"/>')
# Eyes.
for ex, ey, look in [(172, 214, 4), (340, 214, -4)]:
el(f'<circle cx="{ex}" cy="{ey}" r="52" fill="{PAPER}" stroke="{INK}" stroke-width="7"/>')
el(f'<circle cx="{ex + look}" cy="{ey + 3}" r="37" fill="{APP}" stroke="{INK}" stroke-width="5"/>')
el(f'<ellipse cx="{ex + look * 1.5}" cy="{ey + 4}" rx="26" ry="18" fill="{INK}"/>')
el(f'<circle cx="{ex + look * 1.5 - 9}" cy="{ey - 4}" r="7.5" fill="{PAPER}"/>')
el(f'<circle cx="{ex + look * 1.5 + 10}" cy="{ey + 10}" r="3.5" fill="{PAPER}"/>')
s = 1 if ex < 256 else -1
# Upper lid: a heavy carved arc.
lid = catmull([(ex - 50 * s, ey - 18), (ex - 20 * s, ey - 50), (ex + 22 * s, ey - 52), (ex + 48 * s, ey - 28)])
el(f'<path d="{path(ribbon(lid, swell(11, 2)))}" fill="{INK}"/>')
# Lower lid crease.
low = catmull([(ex - 34 * s, ey + 44), (ex, ey + 58), (ex + 36 * s, ey + 46)])
el(f'<path d="{path(ribbon(low, swell(6, 0.5)))}" fill="{INK}"/>')
body = "\n ".join(out)
svg = f'''<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<title>TextureCraft</title>
<clipPath id="tile"><rect width="512" height="512" rx="112"/></clipPath>
<g clip-path="url(#tile)">
<rect width="512" height="512" fill="{APP}"/>
{body}
</g>
</svg>
'''
Path(__file__).with_name("icon.svg").write_text(svg, encoding="utf-8", newline="\n")
+169
View File
@@ -0,0 +1,169 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">
<title>TextureCraft</title>
<clipPath id="tile"><rect width="512" height="512" rx="112"/></clipPath>
<g clip-path="url(#tile)">
<rect width="512" height="512" fill="#c2672b"/>
<path d="M185.7 218.5 L184.0 219.6 L182.0 220.9 L180.0 222.3 L177.8 223.8 L175.7 225.4 L173.4 227.1 L171.0 228.8 L168.6 230.6 L166.1 232.5 L163.5 234.4 L160.9 236.3 L158.2 238.3 L155.5 240.2 L152.8 242.1 L150.2 244.0 L147.5 245.9 L144.9 247.7 L142.3 249.4 L139.9 251.1 L137.5 252.6 L135.3 254.1 L133.2 255.4 L131.4 256.5 L129.6 257.6 L127.6 258.6 L125.4 259.7 L123.2 260.8 L120.9 261.8 L118.7 262.8 L116.4 263.8 L114.2 264.7 L111.9 265.7 L109.7 266.5 L107.5 267.4 L105.3 268.2 L103.1 268.9 L101.0 269.6 L98.9 270.3 L96.9 270.9 L94.9 271.5 L92.9 272.0 L91.0 272.5 L89.2 272.9 L87.5 273.3 L85.9 273.6 L84.3 273.8 L82.9 274.1 L81.6 274.2 L80.3 274.4 L79.1 274.5 L77.8 274.5 L76.5 274.5 L75.1 274.4 L73.8 274.3 L72.4 274.1 L71.0 273.9 L69.7 273.6 L68.3 273.3 L66.9 272.9 L65.6 272.5 L64.3 272.1 L63.0 271.6 L61.7 271.1 L60.5 270.6 L59.4 270.1 L58.2 269.5 L57.2 268.9 L56.2 268.4 L55.2 267.8 L54.4 267.3 L53.6 266.7 L52.9 266.3 L52.4 266.0 L52.0 265.7 L51.5 265.3 L50.9 264.8 L50.3 264.1 L49.8 263.3 L49.2 262.5 L48.7 261.6 L48.2 260.6 L47.7 259.5 L47.2 258.5 L46.8 257.4 L46.4 256.2 L46.1 255.1 L45.8 254.0 L45.5 252.9 L45.3 251.9 L45.1 250.9 L45.0 249.9 L44.9 249.1 L44.8 248.3 L44.8 247.7 L44.7 247.2 L44.6 246.9 L44.5 246.9 L44.4 246.7 L44.4 246.4 L44.5 246.0 L44.7 245.4 L45.0 244.8 L45.5 244.2 L46.0 243.5 L46.6 242.7 L47.3 242.0 L48.1 241.3 L48.9 240.6 L49.7 239.9 L50.6 239.2 L51.5 238.6 L52.4 238.0 L53.3 237.5 L54.2 237.0 L55.0 236.6 L55.8 236.2 L56.5 235.9 L57.1 235.6 L57.6 235.4 L57.9 235.3 L58.1 235.1 L58.5 235.1 L58.9 235.0 L59.6 235.0 L60.3 235.1 L61.1 235.3 L61.9 235.6 L62.9 235.9 L63.8 236.2 L64.8 236.7 L65.8 237.1 L66.7 237.6 L67.7 238.2 L68.6 238.8 L69.5 239.4 L70.4 240.0 L71.2 240.6 L71.9 241.2 L72.6 241.8 L73.2 242.3 L73.6 242.8 L74.0 243.3 L74.3 243.6 L74.5 243.7 L74.6 243.7 L74.7 243.7 L74.7 243.9 L74.8 244.2 L74.8 244.7 L74.7 245.4 L74.5 246.1 L74.2 246.9 L73.9 247.8 L73.5 248.7 L73.1 249.6 L72.6 250.5 L72.1 251.5 L71.6 252.4 L71.1 253.3 L70.5 254.3 L70.0 255.1 L69.5 256.0 L69.0 256.8 L68.5 257.6 L68.0 258.3 L67.6 259.1 L67.2 259.7 L66.9 260.3 L73.1 263.7 L73.3 263.4 L73.6 263.0 L74.0 262.5 L74.4 262.0 L75.0 261.3 L75.6 260.6 L76.3 259.9 L77.0 259.1 L77.8 258.2 L78.5 257.3 L79.3 256.4 L80.1 255.5 L80.9 254.5 L81.7 253.5 L82.4 252.4 L83.1 251.3 L83.8 250.2 L84.4 249.0 L84.9 247.8 L85.4 246.4 L85.7 245.0 L85.9 243.5 L85.8 241.9 L85.5 240.3 L85.1 238.8 L84.6 237.6 L84.0 236.3 L83.3 235.1 L82.6 233.9 L81.8 232.7 L80.9 231.6 L80.0 230.4 L79.0 229.2 L78.0 228.1 L76.9 227.0 L75.8 225.9 L74.6 224.8 L73.3 223.7 L72.1 222.7 L70.8 221.8 L69.4 220.9 L68.0 220.0 L66.5 219.2 L65.0 218.5 L63.4 217.9 L61.7 217.3 L59.9 217.0 L58.1 216.7 L56.3 216.7 L54.6 216.7 L53.0 216.8 L51.3 217.0 L49.6 217.2 L47.9 217.6 L46.2 218.0 L44.5 218.4 L42.8 219.0 L41.0 219.5 L39.3 220.2 L37.6 220.9 L35.9 221.7 L34.2 222.6 L32.5 223.5 L30.9 224.5 L29.2 225.7 L27.6 226.9 L26.1 228.2 L24.6 229.6 L23.1 231.2 L21.8 233.0 L20.5 235.0 L19.4 237.1 L18.5 239.1 L17.8 241.0 L17.2 243.0 L16.6 244.9 L16.2 246.9 L15.8 249.0 L15.5 251.1 L15.2 253.2 L15.1 255.3 L15.0 257.5 L14.9 259.7 L15.0 261.9 L15.1 264.1 L15.3 266.4 L15.5 268.7 L15.9 271.0 L16.4 273.3 L16.9 275.7 L17.6 278.0 L18.4 280.4 L19.3 282.7 L20.4 285.1 L21.7 287.5 L23.1 289.7 L24.4 291.7 L25.8 293.6 L27.2 295.4 L28.7 297.3 L30.3 299.1 L31.9 300.9 L33.7 302.6 L35.5 304.3 L37.3 306.0 L39.3 307.7 L41.3 309.4 L43.4 311.0 L45.6 312.5 L47.8 314.0 L50.1 315.5 L52.5 316.9 L55.0 318.3 L57.5 319.6 L60.2 320.8 L62.9 322.0 L65.6 323.1 L68.5 324.1 L71.4 325.0 L74.4 325.8 L77.4 326.5 L80.5 327.1 L83.5 327.6 L86.5 328.1 L89.6 328.5 L92.7 328.8 L95.8 329.0 L98.9 329.3 L102.1 329.4 L105.2 329.5 L108.4 329.6 L111.6 329.6 L114.8 329.5 L118.0 329.5 L121.3 329.3 L124.5 329.2 L127.7 329.0 L131.0 328.7 L134.2 328.4 L137.4 328.1 L140.7 327.8 L143.9 327.4 L147.1 326.9 L150.4 326.4 L154.1 325.8 L157.9 325.0 L161.7 324.1 L165.5 323.2 L169.4 322.3 L173.2 321.2 L177.0 320.2 L180.8 319.1 L184.5 318.0 L188.3 316.9 L191.9 315.8 L195.5 314.7 L199.1 313.6 L202.5 312.6 L205.8 311.5 L208.9 310.6 L211.9 309.6 L214.7 308.7 L217.3 307.9 L219.7 307.2 L221.8 306.6 L223.6 306.1 L225.0 305.8 L226.3 305.5 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M200.3 286.6 L197.3 287.5 L194.2 288.5 L191.0 289.6 L187.7 290.7 L184.3 291.8 L180.9 292.9 L177.4 294.1 L173.9 295.2 L170.4 296.3 L166.9 297.4 L163.4 298.5 L160.0 299.5 L156.5 300.5 L153.2 301.4 L149.9 302.3 L146.6 303.0 L143.5 303.7 L140.6 304.2 L137.7 304.7 L134.8 305.2 L131.8 305.7 L128.9 306.1 L126.0 306.5 L123.1 306.9 L120.2 307.2 L117.3 307.5 L114.4 307.8 L111.5 308.0 L108.6 308.2 L105.8 308.4 L103.0 308.5 L100.2 308.6 L97.5 308.6 L94.8 308.6 L92.1 308.5 L89.5 308.4 L86.9 308.2 L84.3 308.0 L81.9 307.7 L79.4 307.4 L77.0 307.0 L74.7 306.5 L72.4 305.9 L70.1 305.2 L67.9 304.5 L65.7 303.8 L63.5 302.9 L61.4 302.0 L59.3 301.1 L57.3 300.1 L55.4 299.0 L53.4 297.9 L51.6 296.8 L49.8 295.6 L48.0 294.4 L46.3 293.2 L44.7 291.9 L43.1 290.7 L41.6 289.4 L40.1 288.0 L38.8 286.7 L37.5 285.3 L36.2 284.0 L35.0 282.6 L33.9 281.2 L32.8 279.7 L31.8 278.1 L30.9 276.5 L30.1 274.8 L29.4 273.0 L28.7 271.3 L28.1 269.5 L27.5 267.7 L27.1 265.8 L26.7 264.0 L26.3 262.2 L26.0 260.3 L25.8 258.5 L25.6 256.7 L25.5 254.9 L25.5 253.1 L25.5 251.3 L25.6 249.6 L25.7 247.9 L25.9 246.3 L26.2 244.7 L26.5 243.2 L26.9 241.7 L27.4 240.2 L28.0 238.7 L28.8 237.3 L29.7 235.9 L30.6 234.6 L31.6 233.3 L31.0 232.7 L29.7 233.8 L28.5 235.1 L27.4 236.4 L26.4 237.9 L25.5 239.5 L24.8 241.0 L24.2 242.6 L23.6 244.2 L23.2 245.9 L22.8 247.6 L22.4 249.4 L22.1 251.2 L21.9 253.1 L21.8 255.0 L21.7 257.0 L21.7 258.9 L21.7 260.9 L21.8 263.0 L22.0 265.0 L22.3 267.0 L22.6 269.1 L23.1 271.1 L23.6 273.2 L24.2 275.2 L24.9 277.3 L25.7 279.3 L26.7 281.3 L27.8 283.2 L28.9 285.1 L30.1 286.8 L31.4 288.4 L32.7 290.1 L34.0 291.7 L35.5 293.3 L37.0 294.8 L38.6 296.4 L40.3 297.9 L42.0 299.4 L43.8 300.8 L45.7 302.2 L47.6 303.6 L49.7 304.9 L51.7 306.2 L53.9 307.5 L56.1 308.7 L58.3 309.8 L60.7 310.9 L63.0 311.9 L65.5 312.8 L68.0 313.7 L70.6 314.4 L73.2 315.1 L75.8 315.7 L78.5 316.2 L81.2 316.6 L84.0 316.9 L86.7 317.2 L89.5 317.4 L92.4 317.5 L95.2 317.6 L98.1 317.6 L101.0 317.5 L103.9 317.4 L106.9 317.2 L109.9 317.0 L112.8 316.7 L115.8 316.4 L118.8 316.0 L121.8 315.5 L124.8 315.1 L127.8 314.6 L130.8 314.0 L133.8 313.4 L136.7 312.8 L139.7 312.1 L142.6 311.4 L145.6 310.6 L148.8 309.7 L152.1 308.7 L155.5 307.6 L158.9 306.4 L162.3 305.1 L165.7 303.8 L169.1 302.4 L172.5 300.9 L175.9 299.4 L179.3 297.9 L182.6 296.4 L185.8 294.9 L189.0 293.3 L192.1 291.8 L195.1 290.3 L198.0 288.8 L200.7 287.4 Z" fill="#0b0b0c"/>
<circle cx="85.5" cy="281.0" r="10.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.6"/>
<circle cx="85.5" cy="281.0" r="3.5" fill="#0b0b0c"/>
<circle cx="70.0" cy="280.3" r="9.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.0"/>
<circle cx="70.0" cy="280.3" r="3.0" fill="#0b0b0c"/>
<circle cx="55.8" cy="274.6" r="8.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.5"/>
<circle cx="55.8" cy="274.6" r="2.7" fill="#0b0b0c"/>
<circle cx="46.5" cy="266.9" r="7.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.1"/>
<circle cx="46.5" cy="266.9" r="2.3" fill="#0b0b0c"/>
<circle cx="42.1" cy="256.7" r="6.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.7"/>
<circle cx="42.1" cy="256.7" r="2.0" fill="#0b0b0c"/>
<circle cx="41.0" cy="247.6" r="5.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="41.0" cy="247.6" r="1.8" fill="#0b0b0c"/>
<circle cx="43.3" cy="241.7" r="5.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="49.3" cy="236.5" r="4.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="56.0" cy="233.3" r="3.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="60.3" cy="232.8" r="3.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="66.0" cy="234.9" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="70.8" cy="238.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="75.0" cy="242.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="76.2" cy="244.5" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="74.1" cy="250.2" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<path d="M285.7 305.5 L287.0 305.8 L288.4 306.1 L290.2 306.6 L292.3 307.2 L294.7 307.9 L297.3 308.7 L300.1 309.6 L303.1 310.6 L306.2 311.5 L309.5 312.6 L312.9 313.6 L316.5 314.7 L320.1 315.8 L323.7 316.9 L327.5 318.0 L331.2 319.1 L335.0 320.2 L338.8 321.2 L342.6 322.3 L346.5 323.2 L350.3 324.1 L354.1 325.0 L357.9 325.8 L361.6 326.4 L364.9 326.9 L368.1 327.4 L371.3 327.8 L374.6 328.1 L377.8 328.4 L381.0 328.7 L384.3 329.0 L387.5 329.2 L390.7 329.3 L394.0 329.5 L397.2 329.5 L400.4 329.6 L403.6 329.6 L406.8 329.5 L409.9 329.4 L413.1 329.3 L416.2 329.0 L419.3 328.8 L422.4 328.5 L425.5 328.1 L428.5 327.6 L431.5 327.1 L434.6 326.5 L437.6 325.8 L440.6 325.0 L443.5 324.1 L446.4 323.1 L449.1 322.0 L451.8 320.8 L454.5 319.6 L457.0 318.3 L459.5 316.9 L461.9 315.5 L464.2 314.0 L466.4 312.5 L468.6 311.0 L470.7 309.4 L472.7 307.7 L474.7 306.0 L476.5 304.3 L478.3 302.6 L480.1 300.9 L481.7 299.1 L483.3 297.3 L484.8 295.4 L486.2 293.6 L487.6 291.7 L488.9 289.7 L490.3 287.5 L491.6 285.1 L492.7 282.7 L493.6 280.4 L494.4 278.0 L495.1 275.7 L495.6 273.3 L496.1 271.0 L496.5 268.7 L496.7 266.4 L496.9 264.1 L497.0 261.9 L497.1 259.7 L497.0 257.5 L496.9 255.3 L496.8 253.2 L496.5 251.1 L496.2 249.0 L495.8 246.9 L495.4 244.9 L494.8 243.0 L494.2 241.0 L493.5 239.1 L492.6 237.1 L491.5 235.0 L490.2 233.0 L488.9 231.2 L487.4 229.6 L485.9 228.2 L484.4 226.9 L482.8 225.7 L481.1 224.5 L479.5 223.5 L477.8 222.6 L476.1 221.7 L474.4 220.9 L472.7 220.2 L471.0 219.5 L469.2 219.0 L467.5 218.4 L465.8 218.0 L464.1 217.6 L462.4 217.2 L460.7 217.0 L459.0 216.8 L457.4 216.7 L455.7 216.7 L453.9 216.7 L452.1 217.0 L450.3 217.3 L448.6 217.9 L447.0 218.5 L445.5 219.2 L444.0 220.0 L442.6 220.9 L441.2 221.8 L439.9 222.7 L438.7 223.7 L437.4 224.8 L436.2 225.9 L435.1 227.0 L434.0 228.1 L433.0 229.2 L432.0 230.4 L431.1 231.6 L430.2 232.7 L429.4 233.9 L428.7 235.1 L428.0 236.3 L427.4 237.6 L426.9 238.8 L426.5 240.3 L426.2 241.9 L426.1 243.5 L426.3 245.0 L426.6 246.4 L427.1 247.8 L427.6 249.0 L428.2 250.2 L428.9 251.3 L429.6 252.4 L430.3 253.5 L431.1 254.5 L431.9 255.5 L432.7 256.4 L433.5 257.3 L434.2 258.2 L435.0 259.1 L435.7 259.9 L436.4 260.6 L437.0 261.3 L437.6 262.0 L438.0 262.5 L438.4 263.0 L438.7 263.4 L438.9 263.7 L445.1 260.3 L444.8 259.7 L444.4 259.1 L444.0 258.3 L443.5 257.6 L443.0 256.8 L442.5 256.0 L442.0 255.1 L441.5 254.3 L440.9 253.3 L440.4 252.4 L439.9 251.5 L439.4 250.5 L438.9 249.6 L438.5 248.7 L438.1 247.8 L437.8 246.9 L437.5 246.1 L437.3 245.4 L437.2 244.7 L437.2 244.2 L437.3 243.9 L437.3 243.7 L437.4 243.7 L437.5 243.7 L437.7 243.6 L438.0 243.3 L438.4 242.8 L438.8 242.3 L439.4 241.8 L440.1 241.2 L440.8 240.6 L441.6 240.0 L442.5 239.4 L443.4 238.8 L444.3 238.2 L445.3 237.6 L446.2 237.1 L447.2 236.7 L448.2 236.2 L449.1 235.9 L450.1 235.6 L450.9 235.3 L451.7 235.1 L452.4 235.0 L453.1 235.0 L453.5 235.1 L453.9 235.1 L454.1 235.3 L454.4 235.4 L454.9 235.6 L455.5 235.9 L456.2 236.2 L457.0 236.6 L457.8 237.0 L458.7 237.5 L459.6 238.0 L460.5 238.6 L461.4 239.2 L462.3 239.9 L463.1 240.6 L463.9 241.3 L464.7 242.0 L465.4 242.7 L466.0 243.5 L466.5 244.2 L467.0 244.8 L467.3 245.4 L467.5 246.0 L467.6 246.4 L467.6 246.7 L467.5 246.9 L467.4 246.9 L467.3 247.2 L467.2 247.7 L467.2 248.3 L467.1 249.1 L467.0 249.9 L466.9 250.9 L466.7 251.9 L466.5 252.9 L466.2 254.0 L465.9 255.1 L465.6 256.2 L465.2 257.4 L464.8 258.5 L464.3 259.5 L463.8 260.6 L463.3 261.6 L462.8 262.5 L462.2 263.3 L461.7 264.1 L461.1 264.8 L460.5 265.3 L460.0 265.7 L459.6 266.0 L459.1 266.3 L458.4 266.7 L457.6 267.3 L456.8 267.8 L455.8 268.4 L454.8 268.9 L453.8 269.5 L452.6 270.1 L451.5 270.6 L450.3 271.1 L449.0 271.6 L447.7 272.1 L446.4 272.5 L445.1 272.9 L443.7 273.3 L442.3 273.6 L441.0 273.9 L439.6 274.1 L438.2 274.3 L436.9 274.4 L435.5 274.5 L434.2 274.5 L432.9 274.5 L431.7 274.4 L430.4 274.2 L429.1 274.1 L427.7 273.8 L426.1 273.6 L424.5 273.3 L422.8 272.9 L421.0 272.5 L419.1 272.0 L417.1 271.5 L415.1 270.9 L413.1 270.3 L411.0 269.6 L408.9 268.9 L406.7 268.2 L404.5 267.4 L402.3 266.5 L400.1 265.7 L397.8 264.7 L395.6 263.8 L393.3 262.8 L391.1 261.8 L388.8 260.8 L386.6 259.7 L384.4 258.6 L382.4 257.6 L380.6 256.5 L378.8 255.4 L376.7 254.1 L374.5 252.6 L372.1 251.1 L369.7 249.4 L367.1 247.7 L364.5 245.9 L361.8 244.0 L359.2 242.1 L356.5 240.2 L353.8 238.3 L351.1 236.3 L348.5 234.4 L345.9 232.5 L343.4 230.6 L341.0 228.8 L338.6 227.1 L336.3 225.4 L334.2 223.8 L332.0 222.3 L330.0 220.9 L328.0 219.6 L326.3 218.5 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M311.3 287.4 L314.0 288.8 L316.9 290.3 L319.9 291.8 L323.0 293.3 L326.2 294.9 L329.4 296.4 L332.7 297.9 L336.1 299.4 L339.5 300.9 L342.9 302.4 L346.3 303.8 L349.7 305.1 L353.1 306.4 L356.5 307.6 L359.9 308.7 L363.2 309.7 L366.4 310.6 L369.4 311.4 L372.3 312.1 L375.3 312.8 L378.2 313.4 L381.2 314.0 L384.2 314.6 L387.2 315.1 L390.2 315.5 L393.2 316.0 L396.2 316.4 L399.2 316.7 L402.1 317.0 L405.1 317.2 L408.1 317.4 L411.0 317.5 L413.9 317.6 L416.8 317.6 L419.6 317.5 L422.5 317.4 L425.3 317.2 L428.0 316.9 L430.8 316.6 L433.5 316.2 L436.2 315.7 L438.8 315.1 L441.4 314.4 L444.0 313.7 L446.5 312.8 L449.0 311.9 L451.3 310.9 L453.7 309.8 L455.9 308.7 L458.1 307.5 L460.3 306.2 L462.3 304.9 L464.4 303.6 L466.3 302.2 L468.2 300.8 L470.0 299.4 L471.7 297.9 L473.4 296.4 L475.0 294.8 L476.5 293.3 L478.0 291.7 L479.3 290.1 L480.6 288.4 L481.9 286.8 L483.1 285.1 L484.2 283.2 L485.3 281.3 L486.3 279.3 L487.1 277.3 L487.8 275.2 L488.4 273.2 L488.9 271.1 L489.4 269.1 L489.7 267.0 L490.0 265.0 L490.2 263.0 L490.3 260.9 L490.3 258.9 L490.3 257.0 L490.2 255.0 L490.1 253.1 L489.9 251.2 L489.6 249.4 L489.2 247.6 L488.8 245.9 L488.4 244.2 L487.8 242.6 L487.2 241.0 L486.5 239.5 L485.6 237.9 L484.6 236.4 L483.5 235.1 L482.3 233.8 L481.0 232.7 L480.4 233.3 L481.4 234.6 L482.3 235.9 L483.2 237.3 L484.0 238.7 L484.6 240.2 L485.1 241.7 L485.5 243.2 L485.8 244.7 L486.1 246.3 L486.3 247.9 L486.4 249.6 L486.5 251.3 L486.5 253.1 L486.5 254.9 L486.4 256.7 L486.2 258.5 L486.0 260.3 L485.7 262.2 L485.3 264.0 L484.9 265.8 L484.5 267.7 L483.9 269.5 L483.3 271.3 L482.6 273.0 L481.9 274.8 L481.1 276.5 L480.2 278.1 L479.2 279.7 L478.1 281.2 L477.0 282.6 L475.8 284.0 L474.5 285.3 L473.2 286.7 L471.9 288.0 L470.4 289.4 L468.9 290.7 L467.3 291.9 L465.7 293.2 L464.0 294.4 L462.2 295.6 L460.4 296.8 L458.6 297.9 L456.6 299.0 L454.7 300.1 L452.7 301.1 L450.6 302.0 L448.5 302.9 L446.3 303.8 L444.1 304.5 L441.9 305.2 L439.6 305.9 L437.3 306.5 L435.0 307.0 L432.6 307.4 L430.1 307.7 L427.7 308.0 L425.1 308.2 L422.5 308.4 L419.9 308.5 L417.2 308.6 L414.5 308.6 L411.8 308.6 L409.0 308.5 L406.2 308.4 L403.4 308.2 L400.5 308.0 L397.6 307.8 L394.7 307.5 L391.8 307.2 L388.9 306.9 L386.0 306.5 L383.1 306.1 L380.2 305.7 L377.2 305.2 L374.3 304.7 L371.4 304.2 L368.5 303.7 L365.4 303.0 L362.1 302.3 L358.8 301.4 L355.5 300.5 L352.0 299.5 L348.6 298.5 L345.1 297.4 L341.6 296.3 L338.1 295.2 L334.6 294.1 L331.1 292.9 L327.7 291.8 L324.3 290.7 L321.0 289.6 L317.8 288.5 L314.7 287.5 L311.7 286.6 Z" fill="#0b0b0c"/>
<circle cx="426.5" cy="281.0" r="10.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.6"/>
<circle cx="426.5" cy="281.0" r="3.5" fill="#0b0b0c"/>
<circle cx="442.0" cy="280.3" r="9.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.0"/>
<circle cx="442.0" cy="280.3" r="3.0" fill="#0b0b0c"/>
<circle cx="456.2" cy="274.6" r="8.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.5"/>
<circle cx="456.2" cy="274.6" r="2.7" fill="#0b0b0c"/>
<circle cx="465.5" cy="266.9" r="7.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.1"/>
<circle cx="465.5" cy="266.9" r="2.3" fill="#0b0b0c"/>
<circle cx="469.9" cy="256.7" r="6.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.7"/>
<circle cx="469.9" cy="256.7" r="2.0" fill="#0b0b0c"/>
<circle cx="471.0" cy="247.6" r="5.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="471.0" cy="247.6" r="1.8" fill="#0b0b0c"/>
<circle cx="468.7" cy="241.7" r="5.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="462.7" cy="236.5" r="4.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="456.0" cy="233.3" r="3.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="451.7" cy="232.8" r="3.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="446.0" cy="234.9" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="441.2" cy="238.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="437.0" cy="242.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="435.8" cy="244.5" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="437.9" cy="250.2" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<path d="M181.4 234.6 L180.7 235.8 L180.0 237.1 L179.3 238.5 L178.6 239.9 L177.9 241.3 L177.2 242.7 L176.4 244.2 L175.7 245.7 L175.0 247.3 L174.2 248.9 L173.4 250.5 L172.6 252.1 L171.8 253.8 L171.0 255.5 L170.1 257.2 L169.2 259.0 L168.4 260.7 L167.4 262.5 L166.5 264.2 L165.6 265.9 L164.7 267.6 L163.7 269.3 L162.8 271.0 L161.9 272.6 L161.0 274.1 L160.0 275.7 L158.9 277.4 L157.7 279.1 L156.5 281.0 L155.1 282.9 L153.6 285.0 L152.0 287.1 L150.4 289.3 L148.7 291.5 L146.9 293.9 L145.1 296.3 L143.2 298.7 L141.2 301.3 L139.3 303.9 L137.3 306.5 L135.3 309.3 L133.2 312.1 L131.2 315.0 L129.1 317.9 L127.1 321.0 L125.0 324.1 L123.0 327.2 L121.1 330.3 L119.5 333.0 L117.9 335.6 L116.3 338.3 L114.6 341.1 L112.9 343.9 L111.1 346.8 L109.3 349.7 L107.4 352.8 L105.5 355.9 L103.6 359.1 L101.7 362.3 L99.7 365.7 L97.8 369.2 L95.8 372.7 L93.9 376.4 L92.0 380.1 L90.2 384.0 L88.3 388.0 L86.6 392.0 L84.8 396.2 L83.2 400.5 L81.6 404.9 L80.1 409.4 L78.6 414.1 L77.2 419.0 L75.9 424.2 L74.7 429.5 L73.6 435.0 L72.5 440.7 L71.5 446.4 L70.6 452.3 L69.7 458.2 L68.8 464.2 L68.0 470.2 L67.2 476.1 L66.4 482.0 L65.7 487.9 L65.0 493.6 L64.3 499.1 L63.7 504.5 L63.1 509.6 L62.5 514.5 L61.9 519.0 L61.4 523.3 L60.9 527.2 L60.4 530.6 L59.9 533.6 L59.4 536.2 L92.6 543.8 L93.3 541.1 L94.2 537.9 L95.2 534.3 L96.3 530.4 L97.5 526.3 L98.7 521.8 L100.1 517.1 L101.5 512.1 L103.0 507.0 L104.5 501.8 L106.2 496.4 L107.8 491.0 L109.6 485.5 L111.3 480.0 L113.1 474.5 L114.9 469.2 L116.8 463.9 L118.6 458.8 L120.5 453.9 L122.4 449.2 L124.2 444.8 L126.0 440.8 L127.7 437.2 L129.4 433.9 L131.1 430.9 L132.8 427.9 L134.6 425.0 L136.4 422.2 L138.3 419.5 L140.1 416.9 L142.0 414.4 L144.0 411.9 L145.9 409.4 L147.9 407.0 L150.0 404.6 L152.0 402.3 L154.1 400.0 L156.2 397.6 L158.4 395.3 L160.6 393.0 L162.8 390.7 L165.0 388.4 L167.3 386.0 L169.6 383.6 L171.9 381.2 L174.3 378.7 L176.7 376.1 L178.9 373.7 L180.9 371.7 L182.8 369.8 L184.7 367.9 L186.7 366.1 L188.7 364.3 L190.7 362.4 L192.8 360.6 L194.9 358.8 L197.0 357.0 L199.1 355.1 L201.3 353.3 L203.4 351.5 L205.6 349.6 L207.8 347.8 L210.1 345.9 L212.3 344.0 L214.5 342.1 L216.7 340.1 L219.0 338.2 L221.2 336.1 L223.5 334.0 L225.7 331.9 L228.0 329.6 L230.1 327.4 L232.2 325.2 L234.2 323.1 L236.1 321.0 L238.0 318.9 L239.8 316.8 L241.6 314.8 L243.3 312.8 L245.0 310.8 L246.6 308.9 L248.2 307.0 L249.7 305.1 L251.1 303.4 L252.5 301.6 L253.8 300.0 L255.1 298.4 L256.3 296.9 L257.4 295.5 L258.4 294.3 L259.4 293.1 L260.2 292.0 L261.0 291.2 L261.6 290.4 L262.1 289.9 L262.6 289.4 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M195.2 264.6 L194.1 266.2 L193.0 267.8 L191.8 269.4 L190.6 271.1 L189.4 272.8 L188.2 274.5 L186.9 276.2 L185.7 277.9 L184.4 279.7 L183.1 281.4 L181.8 283.1 L180.5 284.8 L179.1 286.5 L177.8 288.1 L176.4 289.7 L175.0 291.4 L173.4 293.2 L171.8 295.0 L170.1 296.9 L168.3 298.8 L166.5 300.8 L164.6 302.8 L162.7 304.9 L160.7 307.0 L158.7 309.2 L156.7 311.4 L154.6 313.7 L152.5 316.1 L150.4 318.5 L148.3 320.9 L146.2 323.4 L144.1 326.0 L142.0 328.7 L139.8 331.4 L137.8 334.1 L135.7 337.0 L133.7 339.8 L131.9 342.4 L130.1 345.0 L128.3 347.6 L126.5 350.2 L124.6 352.9 L122.7 355.7 L120.7 358.5 L118.8 361.3 L116.8 364.3 L114.8 367.3 L112.8 370.4 L110.9 373.5 L108.9 376.8 L107.0 380.1 L105.1 383.5 L103.2 387.0 L101.4 390.6 L99.6 394.3 L97.9 398.0 L96.2 401.9 L94.6 405.9 L93.0 410.0 L91.6 414.3 L90.2 418.6 L88.9 423.2 L87.7 428.1 L86.6 433.2 L85.5 438.5 L84.5 444.0 L83.6 449.6 L82.8 455.4 L84.2 455.7 L85.8 450.2 L87.4 444.8 L89.0 439.5 L90.6 434.4 L92.2 429.6 L93.8 425.0 L95.4 420.6 L97.1 416.6 L98.8 412.6 L100.6 408.8 L102.4 405.1 L104.2 401.4 L106.1 397.9 L108.0 394.4 L109.9 391.1 L111.9 387.8 L113.9 384.6 L115.9 381.5 L117.9 378.4 L119.9 375.4 L121.9 372.4 L123.9 369.6 L125.8 366.7 L127.8 363.9 L129.8 361.1 L131.7 358.4 L133.6 355.7 L135.5 353.1 L137.3 350.4 L139.1 347.8 L140.8 345.1 L142.7 342.4 L144.6 339.6 L146.6 336.9 L148.5 334.2 L150.5 331.5 L152.5 328.9 L154.4 326.4 L156.4 323.9 L158.3 321.4 L160.3 319.0 L162.2 316.6 L164.1 314.3 L165.9 312.0 L167.8 309.7 L169.5 307.5 L171.3 305.3 L173.0 303.1 L174.6 301.0 L176.1 299.0 L177.6 297.0 L179.0 295.0 L180.4 293.1 L181.6 291.2 L182.8 289.4 L184.0 287.6 L185.1 285.7 L186.2 283.8 L187.3 281.8 L188.4 279.9 L189.5 278.0 L190.5 276.1 L191.5 274.2 L192.4 272.3 L193.4 270.5 L194.3 268.6 L195.1 266.8 L195.9 265.0 Z" fill="#0b0b0c"/>
<circle cx="182.7" cy="355.4" r="15.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="6.4"/>
<circle cx="182.7" cy="355.4" r="4.9" fill="#0b0b0c"/>
<circle cx="159.8" cy="380.2" r="13.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.8"/>
<circle cx="159.8" cy="380.2" r="4.4" fill="#0b0b0c"/>
<circle cx="140.8" cy="402.3" r="12.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.3"/>
<circle cx="140.8" cy="402.3" r="4.0" fill="#0b0b0c"/>
<circle cx="127.4" cy="421.6" r="11.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.8"/>
<circle cx="127.4" cy="421.6" r="3.7" fill="#0b0b0c"/>
<circle cx="117.4" cy="442.7" r="10.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.4"/>
<circle cx="117.4" cy="442.7" r="3.3" fill="#0b0b0c"/>
<circle cx="110.3" cy="462.3" r="9.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.0"/>
<circle cx="110.3" cy="462.3" r="3.1" fill="#0b0b0c"/>
<circle cx="103.8" cy="484.2" r="8.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.7"/>
<circle cx="103.8" cy="484.2" r="2.8" fill="#0b0b0c"/>
<circle cx="99.0" cy="500.6" r="8.1" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.4"/>
<circle cx="99.0" cy="500.6" r="2.6" fill="#0b0b0c"/>
<circle cx="93.8" cy="520.8" r="7.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.1"/>
<circle cx="93.8" cy="520.8" r="2.4" fill="#0b0b0c"/>
<circle cx="89.6" cy="536.9" r="7.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.9"/>
<circle cx="89.6" cy="536.9" r="2.2" fill="#0b0b0c"/>
<path d="M249.4 289.4 L250.0 290.0 L250.5 290.6 L251.2 291.3 L252.0 292.3 L252.9 293.3 L253.9 294.5 L255.0 295.7 L256.1 297.1 L257.4 298.5 L258.6 300.1 L260.0 301.7 L261.4 303.3 L262.9 305.1 L264.4 306.8 L266.0 308.7 L267.6 310.5 L269.3 312.4 L271.0 314.3 L272.7 316.3 L274.5 318.3 L276.4 320.3 L278.2 322.3 L280.2 324.3 L282.0 326.3 L283.8 328.0 L285.5 329.7 L287.4 331.5 L289.2 333.4 L291.1 335.3 L293.1 337.3 L295.1 339.3 L297.2 341.3 L299.3 343.4 L301.4 345.5 L303.7 347.7 L305.9 349.8 L308.2 352.0 L310.5 354.2 L312.9 356.4 L315.3 358.7 L317.8 360.9 L320.3 363.1 L322.8 365.4 L325.4 367.6 L328.0 369.8 L330.7 372.0 L333.4 374.2 L336.1 376.4 L339.1 378.7 L342.0 380.9 L345.1 383.1 L348.1 385.2 L351.1 387.2 L354.2 389.2 L357.2 391.1 L360.2 393.0 L363.3 394.9 L366.3 396.7 L369.3 398.5 L372.2 400.2 L375.1 402.0 L378.0 403.7 L380.8 405.4 L383.6 407.0 L386.3 408.7 L388.9 410.3 L391.5 411.9 L394.0 413.5 L396.3 415.0 L398.6 416.5 L400.8 418.0 L402.9 419.6 L405.3 421.4 L407.7 423.2 L410.1 425.1 L412.5 426.9 L414.9 428.8 L417.3 430.6 L419.6 432.4 L421.9 434.1 L424.1 435.9 L426.3 437.7 L428.4 439.4 L430.4 441.1 L432.3 442.8 L434.2 444.4 L435.9 446.0 L437.6 447.6 L439.1 449.1 L440.5 450.6 L441.8 451.9 L442.9 453.3 L443.9 454.5 L444.8 455.6 L445.5 456.6 L446.1 457.5 L446.6 458.3 L447.1 459.2 L447.5 460.2 L447.8 461.3 L448.1 462.5 L448.3 463.8 L448.5 465.1 L448.6 466.5 L448.6 468.0 L448.6 469.4 L448.5 470.9 L448.4 472.4 L448.1 473.9 L447.9 475.3 L447.5 476.7 L447.2 478.0 L446.8 479.3 L446.4 480.5 L445.9 481.6 L445.5 482.6 L445.1 483.4 L444.7 484.1 L444.4 484.7 L444.4 485.0 L444.5 485.1 L444.5 485.2 L444.3 485.4 L443.9 485.8 L443.2 486.1 L442.4 486.4 L441.4 486.7 L440.2 487.0 L438.9 487.2 L437.6 487.4 L436.2 487.5 L434.7 487.6 L433.2 487.6 L431.7 487.6 L430.2 487.5 L428.8 487.3 L427.4 487.2 L426.0 487.0 L424.8 486.7 L423.6 486.5 L422.6 486.2 L421.8 485.9 L421.1 485.7 L420.7 485.6 L420.4 485.5 L420.1 485.4 L419.8 485.1 L419.4 484.7 L418.9 484.1 L418.5 483.5 L418.0 482.7 L417.6 481.8 L417.1 480.9 L416.7 479.8 L416.4 478.7 L416.0 477.6 L415.7 476.5 L415.5 475.3 L415.3 474.1 L415.1 472.9 L415.0 471.8 L414.9 470.7 L414.8 469.6 L414.8 468.6 L414.8 467.7 L414.8 466.8 L414.9 466.1 L414.9 465.6 L415.0 465.3 L415.0 465.0 L415.2 464.6 L415.4 464.2 L415.8 463.7 L416.2 463.2 L416.8 462.7 L417.4 462.1 L418.1 461.6 L418.9 461.1 L419.7 460.5 L420.5 460.0 L421.3 459.5 L422.2 459.0 L423.1 458.5 L424.0 458.1 L424.8 457.7 L425.6 457.2 L426.5 456.8 L427.2 456.5 L427.9 456.1 L428.6 455.7 L429.3 455.3 L429.8 455.0 L426.2 449.0 L425.9 449.2 L425.5 449.3 L425.0 449.6 L424.3 449.8 L423.6 450.0 L422.8 450.3 L421.9 450.6 L420.9 450.9 L419.9 451.3 L418.9 451.7 L417.8 452.1 L416.8 452.5 L415.7 453.0 L414.6 453.5 L413.5 454.0 L412.4 454.6 L411.3 455.3 L410.2 456.0 L409.2 456.8 L408.2 457.7 L407.3 458.7 L406.4 459.8 L405.7 461.1 L405.1 462.4 L404.7 463.7 L404.3 464.9 L404.0 466.2 L403.8 467.5 L403.5 468.9 L403.4 470.3 L403.2 471.8 L403.1 473.3 L403.1 474.8 L403.1 476.4 L403.1 478.0 L403.2 479.6 L403.4 481.3 L403.6 482.9 L403.9 484.5 L404.2 486.2 L404.7 487.8 L405.2 489.4 L405.8 491.0 L406.6 492.6 L407.5 494.2 L408.6 495.7 L409.9 497.1 L411.3 498.4 L412.8 499.5 L414.3 500.5 L415.9 501.4 L417.5 502.2 L419.2 503.0 L421.0 503.8 L422.8 504.4 L424.7 505.1 L426.6 505.7 L428.6 506.2 L430.7 506.7 L432.8 507.2 L434.9 507.5 L437.1 507.8 L439.2 508.0 L441.4 508.1 L443.6 508.1 L445.9 508.0 L448.1 507.7 L450.4 507.3 L452.8 506.6 L455.1 505.7 L457.5 504.5 L459.6 503.0 L461.5 501.5 L463.1 500.0 L464.6 498.4 L466.0 496.7 L467.4 494.9 L468.7 493.1 L470.0 491.1 L471.2 489.1 L472.3 486.9 L473.4 484.7 L474.4 482.5 L475.4 480.1 L476.3 477.7 L477.1 475.2 L477.8 472.6 L478.3 469.9 L478.8 467.2 L479.2 464.4 L479.4 461.6 L479.5 458.6 L479.4 455.7 L479.1 452.6 L478.6 449.6 L477.9 446.5 L477.0 443.5 L475.9 440.6 L474.8 437.8 L473.5 435.0 L472.1 432.3 L470.6 429.6 L469.1 426.9 L467.5 424.3 L465.8 421.7 L464.0 419.1 L462.2 416.5 L460.4 413.9 L458.5 411.4 L456.6 408.8 L454.6 406.3 L452.7 403.8 L450.7 401.3 L448.7 398.8 L446.7 396.4 L444.8 393.9 L442.8 391.5 L440.9 389.1 L439.0 386.8 L437.1 384.4 L434.9 381.8 L432.5 379.1 L430.2 376.5 L427.7 373.9 L425.3 371.4 L422.8 368.8 L420.4 366.3 L417.9 363.8 L415.4 361.3 L412.9 358.8 L410.5 356.4 L408.0 354.0 L405.6 351.6 L403.3 349.2 L401.0 346.9 L398.7 344.6 L396.5 342.3 L394.4 340.1 L392.4 337.9 L390.5 335.7 L388.6 333.6 L386.9 331.5 L385.4 329.5 L383.9 327.6 L382.3 325.5 L380.8 323.4 L379.2 321.2 L377.7 319.0 L376.1 316.7 L374.6 314.5 L373.1 312.2 L371.6 309.9 L370.2 307.6 L368.7 305.3 L367.3 303.0 L365.9 300.7 L364.4 298.4 L363.0 296.0 L361.7 293.7 L360.3 291.4 L359.0 289.1 L357.6 286.9 L356.3 284.6 L355.0 282.4 L353.7 280.2 L352.4 278.0 L351.1 275.8 L350.0 273.7 L348.9 271.9 L348.0 270.1 L347.1 268.4 L346.1 266.5 L345.2 264.7 L344.3 262.9 L343.4 261.1 L342.5 259.3 L341.6 257.5 L340.7 255.7 L339.9 253.9 L339.1 252.2 L338.3 250.5 L337.5 248.8 L336.7 247.2 L336.0 245.6 L335.3 244.0 L334.6 242.5 L333.9 241.1 L333.2 239.7 L332.6 238.3 L331.9 23Line truncated
<path d="M318.0 268.5 L318.9 270.3 L319.8 272.2 L320.8 274.1 L321.8 276.0 L322.8 278.0 L323.8 279.9 L324.9 281.9 L326.0 283.8 L327.1 285.7 L328.3 287.7 L329.4 289.6 L330.7 291.6 L332.0 293.7 L333.4 295.9 L334.7 298.1 L336.1 300.3 L337.5 302.5 L339.0 304.8 L340.5 307.1 L342.0 309.4 L343.5 311.8 L345.0 314.1 L346.6 316.4 L348.2 318.8 L349.9 321.2 L351.5 323.5 L353.2 325.9 L354.9 328.2 L356.7 330.6 L358.4 332.9 L360.2 335.2 L362.0 337.5 L363.9 339.8 L365.8 342.0 L367.6 344.2 L369.6 346.3 L371.5 348.5 L373.6 350.6 L375.8 352.8 L378.1 355.0 L380.4 357.2 L382.8 359.4 L385.2 361.6 L387.7 363.8 L390.2 366.1 L392.7 368.3 L395.3 370.5 L397.8 372.7 L400.4 375.0 L402.9 377.2 L405.5 379.4 L408.0 381.6 L410.5 383.9 L413.0 386.1 L415.4 388.3 L417.8 390.6 L420.1 392.8 L422.4 395.1 L424.6 397.3 L426.6 399.5 L428.7 401.7 L430.8 403.8 L432.9 406.0 L435.0 408.2 L437.2 410.5 L439.3 412.7 L441.4 414.9 L443.4 417.1 L445.5 419.4 L447.5 421.6 L449.4 423.8 L451.3 426.0 L453.2 428.3 L455.0 430.5 L456.7 432.7 L458.3 434.9 L459.8 437.1 L461.3 439.3 L462.6 441.5 L463.9 443.7 L465.0 445.9 L465.9 448.1 L466.8 450.3 L467.5 452.6 L468.0 454.9 L468.4 457.2 L468.6 459.6 L468.8 461.9 L468.8 464.2 L468.6 466.5 L468.4 468.8 L468.1 471.1 L467.7 473.3 L467.3 475.5 L466.7 477.6 L466.1 479.7 L465.4 481.8 L464.7 483.8 L463.9 485.7 L463.0 487.6 L462.1 489.4 L462.8 489.7 L464.0 488.0 L465.1 486.3 L466.1 484.4 L467.1 482.4 L468.1 480.4 L468.9 478.3 L469.7 476.1 L470.4 473.8 L471.1 471.5 L471.6 469.2 L472.0 466.7 L472.3 464.3 L472.5 461.8 L472.6 459.2 L472.5 456.6 L472.2 454.0 L471.8 451.4 L471.2 448.8 L470.4 446.2 L469.5 443.7 L468.4 441.2 L467.3 438.7 L466.0 436.3 L464.6 433.8 L463.1 431.4 L461.5 428.9 L459.9 426.5 L458.1 424.1 L456.3 421.6 L454.5 419.2 L452.6 416.8 L450.7 414.4 L448.7 412.0 L446.7 409.7 L444.7 407.3 L442.6 404.9 L440.6 402.6 L438.5 400.3 L436.5 398.0 L434.5 395.7 L432.5 393.5 L430.4 391.2 L428.3 388.8 L425.9 386.4 L423.6 384.0 L421.1 381.7 L418.7 379.3 L416.2 377.0 L413.6 374.7 L411.1 372.4 L408.5 370.1 L405.9 367.9 L403.3 365.6 L400.8 363.4 L398.2 361.2 L395.7 359.0 L393.2 356.8 L390.7 354.7 L388.3 352.6 L385.9 350.4 L383.6 348.4 L381.4 346.3 L379.3 344.3 L377.2 342.3 L375.2 340.3 L373.4 338.3 L371.5 336.3 L369.6 334.2 L367.7 332.1 L365.8 330.0 L364.0 327.8 L362.2 325.6 L360.3 323.5 L358.5 321.3 L356.8 319.1 L355.0 316.9 L353.2 314.6 L351.5 312.4 L349.8 310.2 L348.1 308.0 L346.4 305.9 L344.8 303.7 L343.2 301.5 L341.6 299.4 L340.0 297.3 L338.4 295.2 L336.9 293.2 L335.4 291.2 L333.9 289.2 L332.4 287.3 L331.1 285.5 L329.8 283.8 L328.5 282.0 L327.2 280.2 L326.0 278.4 L324.7 276.6 L323.5 274.9 L322.3 273.1 L321.1 271.4 L319.9 269.7 L318.7 268.0 Z" fill="#0b0b0c"/>
<circle cx="382.7" cy="397.6" r="11.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.8"/>
<circle cx="382.7" cy="397.6" r="3.7" fill="#0b0b0c"/>
<circle cx="405.5" cy="413.0" r="10.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.2"/>
<circle cx="405.5" cy="413.0" r="3.2" fill="#0b0b0c"/>
<circle cx="426.1" cy="430.0" r="8.7" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.7"/>
<circle cx="426.1" cy="430.0" r="2.8" fill="#0b0b0c"/>
<circle cx="441.7" cy="444.3" r="7.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.2"/>
<circle cx="441.7" cy="444.3" r="2.4" fill="#0b0b0c"/>
<circle cx="451.1" cy="457.1" r="6.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.8"/>
<circle cx="451.1" cy="457.1" r="2.1" fill="#0b0b0c"/>
<circle cx="452.5" cy="470.2" r="5.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="452.5" cy="470.2" r="1.9" fill="#0b0b0c"/>
<circle cx="449.5" cy="482.2" r="5.1" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="449.5" cy="482.2" r="1.6" fill="#0b0b0c"/>
<circle cx="444.8" cy="488.7" r="4.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="436.0" cy="490.3" r="4.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="426.7" cy="489.6" r="3.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="419.4" cy="487.3" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="415.8" cy="482.4" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="413.8" cy="475.4" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="413.2" cy="468.4" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="414.9" cy="462.8" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<path d="M188.1 246.3 L188.2 247.7 L188.2 249.4 L188.3 251.0 L188.4 252.7 L188.5 254.4 L188.6 256.2 L188.8 258.1 L188.9 260.0 L189.1 261.9 L189.2 263.9 L189.4 266.0 L189.5 268.1 L189.7 270.2 L189.9 272.4 L190.0 274.7 L190.1 277.0 L190.3 279.3 L190.4 281.6 L190.5 284.0 L190.6 286.3 L190.7 288.7 L190.7 291.1 L190.8 293.5 L190.8 295.9 L190.7 298.7 L190.7 301.7 L190.6 304.8 L190.6 307.9 L190.5 311.1 L190.5 314.4 L190.4 317.7 L190.4 321.1 L190.3 324.5 L190.2 327.9 L190.1 331.3 L190.0 334.7 L189.8 338.2 L189.7 341.6 L189.5 345.0 L189.3 348.3 L189.1 351.6 L188.9 354.9 L188.7 358.0 L188.4 361.1 L188.1 364.1 L187.8 367.0 L187.5 369.7 L187.2 372.2 L186.9 374.4 L186.6 376.4 L186.3 378.4 L185.8 380.4 L185.4 382.5 L184.8 384.5 L184.1 386.7 L183.4 388.9 L182.7 391.2 L181.8 393.6 L180.9 396.0 L179.9 398.6 L178.9 401.3 L177.9 404.1 L176.8 407.0 L175.7 410.1 L174.6 413.3 L173.5 416.6 L172.5 420.1 L171.5 423.7 L170.6 427.4 L169.7 431.2 L168.9 435.2 L168.2 439.3 L167.6 443.5 L167.1 447.7 L166.7 452.1 L166.4 456.6 L166.1 461.2 L165.9 465.9 L165.6 470.6 L165.5 475.4 L165.3 480.2 L165.2 485.0 L165.1 489.8 L165.0 494.5 L165.0 499.1 L164.9 503.7 L164.8 508.1 L164.8 512.4 L164.7 516.5 L164.7 520.4 L164.6 524.0 L164.6 527.4 L164.5 530.5 L164.4 533.2 L164.3 535.6 L164.1 537.6 L203.9 542.4 L204.2 540.2 L204.7 537.5 L205.2 534.6 L205.7 531.5 L206.3 528.1 L207.0 524.5 L207.7 520.6 L208.4 516.7 L209.2 512.5 L210.0 508.3 L210.8 503.9 L211.7 499.5 L212.6 495.1 L213.6 490.6 L214.6 486.2 L215.6 481.8 L216.6 477.5 L217.6 473.3 L218.7 469.3 L219.7 465.4 L220.8 461.8 L221.8 458.4 L222.8 455.4 L223.8 452.7 L224.8 450.3 L225.7 448.1 L226.8 446.0 L227.8 443.9 L228.9 441.9 L230.1 439.9 L231.2 437.9 L232.4 436.0 L233.7 434.0 L235.0 431.9 L236.4 429.8 L237.8 427.6 L239.3 425.4 L240.8 423.0 L242.4 420.5 L244.0 417.9 L245.6 415.2 L247.2 412.3 L248.9 409.3 L250.6 406.1 L252.2 402.7 L253.8 399.2 L255.3 395.5 L256.8 391.8 L258.1 388.2 L259.4 384.6 L260.7 381.0 L261.9 377.4 L263.1 373.7 L264.3 370.1 L265.4 366.3 L266.5 362.6 L267.6 358.9 L268.7 355.2 L269.8 351.5 L270.8 347.8 L271.8 344.1 L272.8 340.4 L273.7 336.8 L274.7 333.3 L275.6 329.8 L276.5 326.4 L277.3 323.1 L278.2 319.9 L279.0 316.8 L279.8 313.8 L280.5 310.9 L281.2 308.1 L282.0 305.0 L282.7 302.0 L283.4 298.9 L284.0 295.9 L284.6 292.9 L285.2 290.0 L285.8 287.2 L286.3 284.4 L286.8 281.6 L287.3 279.0 L287.8 276.4 L288.2 273.9 L288.6 271.5 L289.0 269.2 L289.4 267.0 L289.7 264.9 L290.1 263.0 L290.4 261.1 L290.7 259.5 L291.0 258.0 L291.2 256.6 L291.4 255.5 L291.7 254.6 L291.9 253.7 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M260.5 267.7 L260.1 269.9 L259.7 272.2 L259.2 274.6 L258.7 277.1 L258.3 279.6 L257.8 282.2 L257.2 284.8 L256.7 287.5 L256.2 290.2 L255.6 293.0 L255.0 295.8 L254.4 298.6 L253.7 301.5 L253.1 304.3 L252.4 307.1 L251.7 310.0 L251.0 313.0 L250.3 316.1 L249.6 319.3 L248.8 322.6 L248.0 325.9 L247.3 329.3 L246.5 332.8 L245.6 336.3 L244.8 339.9 L244.0 343.4 L243.1 347.0 L242.3 350.6 L241.4 354.2 L240.5 357.8 L239.7 361.4 L238.8 364.9 L237.8 368.4 L236.9 371.9 L236.0 375.3 L235.0 378.6 L234.1 381.9 L233.1 385.1 L232.0 388.3 L230.9 391.4 L229.7 394.4 L228.5 397.3 L227.3 400.1 L226.0 402.9 L224.7 405.5 L223.4 408.1 L222.2 410.6 L220.9 413.1 L219.6 415.5 L218.4 417.9 L217.1 420.3 L215.9 422.6 L214.8 425.0 L213.7 427.4 L212.6 429.8 L211.5 432.3 L210.5 434.8 L209.6 437.3 L208.7 440.0 L207.8 442.7 L207.1 445.5 L206.4 448.5 L205.7 451.7 L205.1 455.2 L204.5 458.9 L203.9 462.8 L203.5 466.9 L204.4 467.1 L205.6 463.1 L206.8 459.3 L207.9 455.7 L209.0 452.4 L210.1 449.4 L211.2 446.7 L212.3 444.0 L213.4 441.5 L214.5 439.1 L215.7 436.8 L216.9 434.5 L218.2 432.3 L219.5 430.0 L220.8 427.8 L222.1 425.6 L223.5 423.4 L224.8 421.1 L226.3 418.8 L227.7 416.5 L229.1 414.0 L230.6 411.5 L232.1 408.9 L233.5 406.2 L235.0 403.4 L236.4 400.5 L237.8 397.4 L239.1 394.2 L240.4 390.9 L241.6 387.5 L242.7 384.1 L243.7 380.8 L244.7 377.3 L245.7 373.8 L246.6 370.3 L247.6 366.7 L248.4 363.1 L249.3 359.4 L250.1 355.8 L250.9 352.1 L251.6 348.4 L252.3 344.8 L253.0 341.1 L253.7 337.5 L254.3 334.0 L254.9 330.4 L255.5 327.0 L256.0 323.6 L256.5 320.2 L257.0 317.0 L257.5 313.8 L257.9 310.8 L258.3 307.9 L258.7 305.0 L259.1 302.1 L259.5 299.2 L259.8 296.3 L260.1 293.4 L260.4 290.6 L260.6 287.8 L260.8 285.1 L261.0 282.4 L261.2 279.8 L261.3 277.2 L261.4 274.8 L261.5 272.3 L261.6 270.0 L261.6 267.8 Z" fill="#0b0b0c"/>
<circle cx="200.3" cy="346.9" r="15.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="6.7"/>
<circle cx="200.3" cy="346.9" r="5.1" fill="#0b0b0c"/>
<circle cx="196.3" cy="377.3" r="14.4" fill="#efe9dc" stroke="#0b0b0c" stroke-width="6.1"/>
<circle cx="196.3" cy="377.3" r="4.6" fill="#0b0b0c"/>
<circle cx="189.0" cy="400.1" r="13.1" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.5"/>
<circle cx="189.0" cy="400.1" r="4.2" fill="#0b0b0c"/>
<circle cx="178.2" cy="429.9" r="11.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.0"/>
<circle cx="178.2" cy="429.9" r="3.8" fill="#0b0b0c"/>
<circle cx="173.6" cy="457.8" r="10.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.6"/>
<circle cx="173.6" cy="457.8" r="3.5" fill="#0b0b0c"/>
<circle cx="172.0" cy="481.0" r="10.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.2"/>
<circle cx="172.0" cy="481.0" r="3.2" fill="#0b0b0c"/>
<circle cx="171.3" cy="499.8" r="9.3" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.9"/>
<circle cx="171.3" cy="499.8" r="3.0" fill="#0b0b0c"/>
<circle cx="170.4" cy="520.9" r="8.6" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.6"/>
<circle cx="170.4" cy="520.9" r="2.7" fill="#0b0b0c"/>
<circle cx="169.8" cy="536.2" r="8.1" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.4"/>
<circle cx="169.8" cy="536.2" r="2.6" fill="#0b0b0c"/>
<path d="M222.3 255.4 L222.6 256.2 L222.8 256.8 L223.2 257.8 L223.5 259.1 L223.9 260.6 L224.4 262.3 L224.8 264.2 L225.3 266.2 L225.8 268.4 L226.3 270.7 L226.9 273.2 L227.5 275.7 L228.2 278.3 L228.8 281.1 L229.6 283.9 L230.3 286.8 L231.1 289.7 L231.9 292.7 L232.8 295.8 L233.8 298.9 L234.7 302.0 L235.8 305.2 L236.9 308.4 L238.1 311.7 L239.4 315.2 L240.8 318.6 L242.2 321.9 L243.7 325.2 L245.3 328.4 L246.9 331.5 L248.5 334.5 L250.1 337.6 L251.7 340.5 L253.4 343.4 L255.0 346.3 L256.6 349.1 L258.2 351.9 L259.7 354.6 L261.2 357.3 L262.7 359.9 L264.0 362.4 L265.4 364.9 L266.6 367.2 L267.8 369.5 L268.8 371.6 L269.8 373.6 L270.7 375.5 L271.5 377.3 L272.3 379.4 L273.1 381.7 L273.8 384.0 L274.5 386.2 L275.2 388.4 L275.8 390.7 L276.5 392.9 L277.0 395.1 L277.6 397.3 L278.1 399.4 L278.5 401.6 L278.9 403.7 L279.3 405.8 L279.7 407.9 L280.0 410.0 L280.3 412.0 L280.5 414.0 L280.7 416.0 L280.8 418.0 L280.9 419.9 L281.0 421.7 L281.1 423.6 L281.1 425.4 L281.0 427.1 L280.9 428.9 L280.8 430.7 L280.6 432.6 L280.4 434.5 L280.1 436.4 L279.8 438.3 L279.4 440.3 L278.9 442.2 L278.5 444.2 L277.9 446.1 L277.4 448.0 L276.8 449.8 L276.2 451.6 L275.6 453.3 L275.0 454.9 L274.3 456.5 L273.7 457.9 L273.0 459.2 L272.4 460.5 L271.8 461.6 L271.2 462.5 L270.7 463.3 L270.3 464.0 L270.1 464.4 L270.1 464.7 L270.0 464.9 L269.8 465.2 L269.4 465.6 L268.9 465.9 L268.2 466.2 L267.4 466.5 L266.5 466.7 L265.5 466.9 L264.5 467.0 L263.3 467.1 L262.1 467.1 L260.9 467.1 L259.6 467.0 L258.4 466.9 L257.1 466.7 L255.9 466.5 L254.8 466.3 L253.6 466.0 L252.6 465.7 L251.6 465.4 L250.7 465.1 L249.9 464.8 L249.4 464.6 L249.1 464.6 L248.7 464.4 L248.3 464.2 L247.8 463.8 L247.3 463.3 L246.8 462.7 L246.2 462.0 L245.7 461.2 L245.2 460.4 L244.7 459.5 L244.2 458.5 L243.8 457.6 L243.3 456.5 L243.0 455.5 L242.6 454.5 L242.3 453.5 L242.1 452.5 L241.9 451.6 L241.7 450.7 L241.6 449.8 L241.5 449.1 L241.4 448.4 L241.4 447.9 L241.4 447.6 L241.3 447.6 L241.2 447.5 L241.3 447.3 L241.4 447.0 L241.6 446.7 L242.0 446.3 L242.5 445.8 L243.1 445.3 L243.8 444.9 L244.5 444.4 L245.3 443.9 L246.1 443.5 L247.0 443.0 L247.9 442.6 L248.7 442.2 L249.6 441.8 L250.5 441.4 L251.3 441.1 L252.1 440.7 L252.9 440.4 L253.7 440.1 L254.4 439.7 L255.0 439.4 L255.6 439.1 L252.4 432.9 L252.1 433.0 L251.7 433.1 L251.2 433.3 L250.6 433.4 L249.8 433.6 L249.0 433.8 L248.1 434.0 L247.1 434.2 L246.1 434.4 L245.1 434.7 L244.0 435.0 L242.9 435.3 L241.8 435.6 L240.6 436.0 L239.5 436.4 L238.4 436.9 L237.3 437.4 L236.2 438.0 L235.1 438.7 L234.0 439.6 L233.0 440.5 L232.1 441.7 L231.2 443.0 L230.6 444.4 L230.2 445.7 L229.9 446.9 L229.7 448.2 L229.5 449.5 L229.3 450.8 L229.3 452.2 L229.2 453.7 L229.2 455.1 L229.3 456.6 L229.4 458.1 L229.5 459.6 L229.7 461.2 L230.0 462.8 L230.3 464.3 L230.7 465.9 L231.2 467.5 L231.7 469.1 L232.4 470.6 L233.1 472.2 L233.9 473.7 L234.9 475.2 L236.0 476.7 L237.2 478.1 L238.6 479.4 L239.9 480.4 L241.2 481.4 L242.6 482.3 L244.0 483.3 L245.5 484.2 L247.1 485.1 L248.7 485.9 L250.4 486.8 L252.2 487.5 L254.0 488.3 L255.9 489.0 L257.9 489.6 L259.9 490.2 L262.0 490.7 L264.1 491.1 L266.3 491.4 L268.6 491.5 L270.9 491.6 L273.3 491.5 L275.8 491.2 L278.3 490.7 L280.9 489.9 L283.4 488.9 L285.9 487.6 L288.1 486.2 L290.1 484.8 L292.1 483.3 L293.9 481.7 L295.7 480.0 L297.5 478.3 L299.2 476.4 L300.9 474.5 L302.6 472.5 L304.2 470.5 L305.9 468.4 L307.4 466.2 L309.0 464.0 L310.5 461.7 L311.9 459.4 L313.4 457.0 L314.7 454.6 L316.1 452.2 L317.4 449.7 L318.6 447.2 L319.8 444.6 L320.9 442.1 L322.0 439.5 L323.0 436.9 L323.9 434.2 L324.8 431.6 L325.6 428.9 L326.3 426.2 L327.1 423.5 L327.7 420.7 L328.4 417.9 L328.9 415.1 L329.5 412.2 L330.0 409.4 L330.4 406.4 L330.8 403.5 L331.2 400.6 L331.5 397.6 L331.8 394.6 L332.0 391.6 L332.2 388.5 L332.4 385.5 L332.5 382.4 L332.6 379.3 L332.6 376.2 L332.6 373.1 L332.6 370.0 L332.5 366.7 L332.3 363.1 L332.0 359.3 L331.5 355.6 L331.1 352.0 L330.5 348.3 L330.0 344.7 L329.4 341.1 L328.7 337.6 L328.1 334.1 L327.5 330.6 L326.8 327.2 L326.2 323.9 L325.5 320.6 L324.9 317.3 L324.3 314.2 L323.8 311.2 L323.3 308.3 L322.9 305.5 L322.5 302.8 L322.3 300.3 L322.1 298.0 L321.9 295.9 L321.9 294.0 L321.9 292.3 L322.0 290.5 L322.1 288.6 L322.2 286.6 L322.3 284.5 L322.4 282.4 L322.5 280.3 L322.7 278.2 L322.9 276.1 L323.1 273.9 L323.3 271.8 L323.5 269.7 L323.7 267.6 L324.0 265.5 L324.2 263.4 L324.4 261.4 L324.6 259.4 L324.8 257.5 L325.0 255.6 L325.2 253.7 L325.4 251.8 L325.5 250.0 L325.6 248.1 L325.7 246.1 L325.7 244.6 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7" stroke-linejoin="round"/>
<path d="M296.4 265.5 L296.1 267.7 L296.0 269.9 L295.8 272.2 L295.7 274.5 L295.5 276.8 L295.5 279.2 L295.4 281.6 L295.4 284.0 L295.4 286.5 L295.4 288.9 L295.5 291.3 L295.6 293.7 L295.7 296.0 L295.9 298.3 L296.1 300.6 L296.4 303.0 L296.8 305.6 L297.3 308.2 L297.8 311.0 L298.4 313.8 L299.1 316.8 L299.8 319.8 L300.5 322.8 L301.3 326.0 L302.1 329.1 L302.9 332.3 L303.8 335.5 L304.6 338.7 L305.4 342.0 L306.2 345.2 L307.0 348.4 L307.7 351.6 L308.4 354.9 L309.1 358.0 L309.7 361.2 L310.2 364.3 L310.6 367.4 L311.0 370.4 L311.3 373.3 L311.5 376.2 L311.7 379.0 L311.9 381.8 L312.0 384.6 L312.1 387.3 L312.2 390.1 L312.2 392.8 L312.2 395.6 L312.2 398.3 L312.1 400.9 L312.0 403.6 L311.9 406.2 L311.7 408.8 L311.5 411.4 L311.3 414.0 L311.0 416.5 L310.7 419.0 L310.3 421.5 L309.9 423.9 L309.5 426.3 L309.0 428.7 L308.4 431.0 L307.9 433.4 L307.2 435.7 L306.5 438.0 L305.8 440.3 L305.0 442.6 L304.1 445.0 L303.2 447.3 L302.2 449.6 L301.2 451.8 L300.2 454.1 L299.1 456.3 L298.0 458.4 L296.9 460.6 L295.7 462.6 L294.5 464.6 L293.3 466.6 L292.0 468.5 L290.8 470.3 L289.5 472.0 L288.1 473.7 L286.8 475.2 L285.4 476.7 L284.0 478.0 L282.6 479.3 L281.0 480.5 L279.4 481.5 L277.6 482.4 L275.8 483.2 L276.0 483.9 L278.0 483.4 L280.0 482.7 L281.9 481.8 L283.7 480.7 L285.4 479.6 L287.0 478.3 L288.7 476.9 L290.3 475.4 L291.8 473.9 L293.4 472.2 L294.9 470.4 L296.4 468.6 L297.9 466.7 L299.4 464.7 L300.8 462.7 L302.2 460.6 L303.6 458.4 L304.9 456.2 L306.2 453.9 L307.4 451.7 L308.6 449.3 L309.8 447.0 L310.9 444.6 L311.9 442.2 L312.9 439.8 L313.8 437.3 L314.6 434.9 L315.4 432.5 L316.1 430.0 L316.7 427.5 L317.4 425.0 L317.9 422.4 L318.4 419.8 L318.9 417.1 L319.3 414.5 L319.7 411.8 L320.0 409.1 L320.3 406.3 L320.5 403.6 L320.7 400.8 L320.9 398.0 L320.9 395.1 L321.0 392.3 L321.0 389.4 L321.0 386.5 L320.9 383.6 L320.8 380.7 L320.6 377.8 L320.4 374.9 L320.2 371.9 L319.9 368.9 L319.4 365.6 L318.9 362.3 L318.3 359.0 L317.6 355.7 L316.9 352.4 L316.0 349.1 L315.2 345.8 L314.3 342.5 L313.3 339.2 L312.4 336.0 L311.4 332.8 L310.4 329.6 L309.4 326.4 L308.5 323.4 L307.5 320.3 L306.6 317.4 L305.7 314.5 L304.8 311.7 L304.0 308.9 L303.3 306.3 L302.6 303.8 L302.0 301.5 L301.5 299.2 L301.0 297.1 L300.6 295.0 L300.3 292.8 L299.9 290.5 L299.6 288.2 L299.3 285.9 L299.0 283.5 L298.7 281.2 L298.5 278.9 L298.2 276.6 L298.0 274.3 L297.8 272.0 L297.6 269.8 L297.4 267.6 L297.2 265.4 Z" fill="#0b0b0c"/>
<circle cx="281.1" cy="380.5" r="12.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="5.1"/>
<circle cx="281.1" cy="380.5" r="3.9" fill="#0b0b0c"/>
<circle cx="286.0" cy="403.7" r="10.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="4.4"/>
<circle cx="286.0" cy="403.7" r="3.3" fill="#0b0b0c"/>
<circle cx="286.9" cy="424.7" r="9.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.8"/>
<circle cx="286.9" cy="424.7" r="2.9" fill="#0b0b0c"/>
<circle cx="284.8" cy="440.3" r="7.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="3.3"/>
<circle cx="284.8" cy="440.3" r="2.5" fill="#0b0b0c"/>
<circle cx="279.5" cy="455.6" r="6.8" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.8"/>
<circle cx="279.5" cy="455.6" r="2.2" fill="#0b0b0c"/>
<circle cx="274.1" cy="465.4" r="5.9" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="274.1" cy="465.4" r="1.9" fill="#0b0b0c"/>
<circle cx="268.6" cy="469.7" r="5.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="268.6" cy="469.7" r="1.7" fill="#0b0b0c"/>
<circle cx="260.2" cy="470.1" r="4.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="251.4" cy="468.1" r="4.0" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="246.5" cy="465.7" r="3.5" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="243.2" cy="461.2" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="240.9" cy="454.8" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="239.9" cy="449.0" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="240.8" cy="445.6" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<circle cx="245.7" cy="442.4" r="3.2" fill="#efe9dc" stroke="#0b0b0c" stroke-width="2.6"/>
<clipPath id="head"><path d="M262.0 62.0 L265.2 62.1 L268.4 62.1 L271.7 62.2 L274.9 62.4 L278.2 62.5 L281.6 62.8 L284.9 63.0 L288.2 63.3 L291.6 63.6 L294.9 63.9 L298.2 64.3 L301.5 64.8 L304.8 65.2 L308.0 65.8 L311.3 66.3 L314.4 67.0 L317.6 67.6 L320.7 68.4 L323.7 69.2 L326.7 70.0 L329.6 70.9 L332.5 71.9 L335.3 72.9 L338.0 74.0 L340.7 75.2 L343.3 76.4 L345.9 77.7 L348.5 79.1 L351.0 80.5 L353.5 82.0 L356.0 83.5 L358.4 85.1 L360.8 86.8 L363.2 88.5 L365.5 90.2 L367.8 92.0 L370.0 93.8 L372.1 95.7 L374.2 97.6 L376.2 99.6 L378.2 101.5 L380.1 103.5 L381.9 105.6 L383.7 107.6 L385.4 109.7 L387.0 111.8 L388.5 113.9 L390.0 116.0 L391.4 118.2 L392.7 120.4 L394.0 122.7 L395.3 125.1 L396.4 127.5 L397.6 130.0 L398.6 132.5 L399.6 135.0 L400.6 137.6 L401.4 140.2 L402.3 142.9 L403.0 145.5 L403.7 148.1 L404.3 150.8 L404.8 153.4 L405.3 156.1 L405.6 158.7 L405.9 161.3 L406.2 163.8 L406.3 166.4 L406.4 168.9 L406.3 171.3 L406.2 173.7 L406.0 176.0 L405.7 178.3 L405.2 180.6 L404.5 182.9 L403.7 185.2 L402.8 187.4 L401.8 189.7 L400.6 192.0 L399.4 194.2 L398.1 196.4 L396.7 198.7 L395.3 200.8 L393.9 203.0 L392.4 205.1 L390.9 207.2 L389.4 209.3 L387.9 211.3 L386.5 213.3 L385.0 215.3 L383.7 217.2 L382.4 219.1 L381.1 220.9 L380.0 222.6 L378.9 224.3 L378.0 226.0 L377.2 227.6 L376.4 229.1 L375.7 230.5 L375.1 231.9 L374.5 233.2 L373.9 234.5 L373.4 235.7 L373.0 236.8 L372.5 237.9 L372.1 239.0 L371.7 240.1 L371.2 241.1 L370.8 242.1 L370.4 243.2 L370.0 244.2 L369.5 245.2 L369.0 246.2 L368.4 247.2 L367.9 248.3 L367.2 249.4 L366.5 250.5 L365.8 251.6 L364.9 252.8 L364.0 254.0 L363.0 255.3 L362.1 256.6 L361.2 257.9 L360.2 259.3 L359.3 260.7 L358.3 262.1 L357.3 263.5 L356.3 265.0 L355.3 266.4 L354.2 267.9 L353.0 269.3 L351.9 270.8 L350.6 272.2 L349.4 273.6 L348.0 275.0 L346.6 276.4 L345.1 277.7 L343.5 279.0 L341.8 280.3 L340.1 281.5 L338.2 282.7 L336.3 283.9 L334.2 285.0 L332.0 286.0 L329.7 287.0 L327.2 288.0 L324.6 289.0 L321.9 290.0 L319.0 290.9 L316.1 291.9 L313.1 292.8 L309.9 293.7 L306.7 294.6 L303.5 295.4 L300.1 296.2 L296.8 297.0 L293.3 297.7 L289.9 298.4 L286.4 299.0 L283.0 299.6 L279.5 300.2 L276.0 300.6 L272.6 301.0 L269.2 301.4 L265.8 301.6 L262.5 301.8 L259.2 302.0 L256.0 302.0 L252.8 302.0 L249.5 301.8 L246.2 301.6 L242.8 301.4 L239.4 301.0 L236.0 300.6 L232.5 300.2 L229.0 299.6 L225.6 299.0 L222.1 298.4 L218.7 297.7 L215.2 297.0 L211.9 296.2 L208.5 295.4 L205.3 294.6 L202.1 293.7 L198.9 292.8 L195.9 291.9 L193.0 290.9 L190.1 290.0 L187.4 289.0 L184.8 288.0 L182.3 287.0 L180.0 286.0 L177.8 285.0 L175.7 283.9 L173.8 282.7 L171.9 281.5 L170.2 280.3 L168.5 279.0 L166.9 277.7 L165.4 276.4 L164.0 275.0 L162.6 273.6 L161.4 272.2 L160.1 270.8 L159.0 269.3 L157.8 267.9 L156.7 266.4 L155.7 265.0 L154.7 263.5 L153.7 262.1 L152.7 260.7 L151.8 259.3 L150.8 257.9 L149.9 256.6 L149.0 255.3 L148.0 254.0 L147.1 252.8 L146.2 251.6 L145.5 250.5 L144.8 249.4 L144.1 248.3 L143.5 247.2 L143.0 246.2 L142.4 245.2 L142.0 244.2 L141.5 243.2 L141.1 242.1 L140.6 241.1 L140.2 240.1 L139.8 239.0 L139.3 237.9 L138.9 236.8 L138.4 235.7 L137.9 234.5 L137.4 233.2 L136.8 231.9 L136.2 230.5 L135.5 229.1 L134.8 227.6 L134.0 226.0 L133.1 224.3 L132.1 222.6 L131.0 220.9 L129.8 219.1 L128.6 217.3 L127.3 215.4 L125.9 213.4 L124.5 211.5 L123.1 209.5 L121.7 207.4 L120.3 205.4 L118.9 203.2 L117.5 201.1 L116.2 198.9 L114.9 196.7 L113.7 194.5 L112.6 192.3 L111.5 190.0 L110.6 187.7 L109.8 185.4 L109.1 183.1 L108.6 180.7 L108.2 178.4 L108.0 176.0 L107.9 173.6 L107.9 171.1 L108.0 168.5 L108.2 165.9 L108.5 163.2 L108.9 160.4 L109.3 157.6 L109.9 154.8 L110.5 152.0 L111.1 149.1 L111.9 146.2 L112.8 143.4 L113.7 140.5 L114.6 137.7 L115.7 134.9 L116.8 132.1 L118.0 129.3 L119.2 126.6 L120.6 124.0 L121.9 121.4 L123.4 118.9 L124.9 116.5 L126.4 114.2 L128.0 112.0 L129.7 109.8 L131.4 107.7 L133.3 105.6 L135.3 103.6 L137.3 101.6 L139.4 99.6 L141.6 97.7 L143.9 95.8 L146.2 93.9 L148.6 92.1 L151.0 90.3 L153.5 88.6 L156.0 87.0 L158.6 85.3 L161.3 83.7 L163.9 82.2 L166.6 80.7 L169.3 79.3 L172.1 78.0 L174.9 76.7 L177.6 75.4 L180.4 74.2 L183.2 73.1 L186.0 72.0 L188.8 71.0 L191.7 70.0 L194.6 69.2 L197.6 68.3 L200.7 67.6 L203.7 66.9 L206.8 66.2 L210.0 65.6 L213.2 65.1 L216.4 64.6 L219.6 64.1 L222.9 63.8 L226.1 63.4 L229.4 63.1 L232.7 62.8 L236.0 62.6 L239.3 62.4 L242.6 62.2 L245.9 62.1 L249.1 62.0 L252.4 62.0 L255.6 62.0 L258.8 62.0 Z"/></clipPath>
<path d="M262.0 62.0 L265.2 62.1 L268.4 62.1 L271.7 62.2 L274.9 62.4 L278.2 62.5 L281.6 62.8 L284.9 63.0 L288.2 63.3 L291.6 63.6 L294.9 63.9 L298.2 64.3 L301.5 64.8 L304.8 65.2 L308.0 65.8 L311.3 66.3 L314.4 67.0 L317.6 67.6 L320.7 68.4 L323.7 69.2 L326.7 70.0 L329.6 70.9 L332.5 71.9 L335.3 72.9 L338.0 74.0 L340.7 75.2 L343.3 76.4 L345.9 77.7 L348.5 79.1 L351.0 80.5 L353.5 82.0 L356.0 83.5 L358.4 85.1 L360.8 86.8 L363.2 88.5 L365.5 90.2 L367.8 92.0 L370.0 93.8 L372.1 95.7 L374.2 97.6 L376.2 99.6 L378.2 101.5 L380.1 103.5 L381.9 105.6 L383.7 107.6 L385.4 109.7 L387.0 111.8 L388.5 113.9 L390.0 116.0 L391.4 118.2 L392.7 120.4 L394.0 122.7 L395.3 125.1 L396.4 127.5 L397.6 130.0 L398.6 132.5 L399.6 135.0 L400.6 137.6 L401.4 140.2 L402.3 142.9 L403.0 145.5 L403.7 148.1 L404.3 150.8 L404.8 153.4 L405.3 156.1 L405.6 158.7 L405.9 161.3 L406.2 163.8 L406.3 166.4 L406.4 168.9 L406.3 171.3 L406.2 173.7 L406.0 176.0 L405.7 178.3 L405.2 180.6 L404.5 182.9 L403.7 185.2 L402.8 187.4 L401.8 189.7 L400.6 192.0 L399.4 194.2 L398.1 196.4 L396.7 198.7 L395.3 200.8 L393.9 203.0 L392.4 205.1 L390.9 207.2 L389.4 209.3 L387.9 211.3 L386.5 213.3 L385.0 215.3 L383.7 217.2 L382.4 219.1 L381.1 220.9 L380.0 222.6 L378.9 224.3 L378.0 226.0 L377.2 227.6 L376.4 229.1 L375.7 230.5 L375.1 231.9 L374.5 233.2 L373.9 234.5 L373.4 235.7 L373.0 236.8 L372.5 237.9 L372.1 239.0 L371.7 240.1 L371.2 241.1 L370.8 242.1 L370.4 243.2 L370.0 244.2 L369.5 245.2 L369.0 246.2 L368.4 247.2 L367.9 248.3 L367.2 249.4 L366.5 250.5 L365.8 251.6 L364.9 252.8 L364.0 254.0 L363.0 255.3 L362.1 256.6 L361.2 257.9 L360.2 259.3 L359.3 260.7 L358.3 262.1 L357.3 263.5 L356.3 265.0 L355.3 266.4 L354.2 267.9 L353.0 269.3 L351.9 270.8 L350.6 272.2 L349.4 273.6 L348.0 275.0 L346.6 276.4 L345.1 277.7 L343.5 279.0 L341.8 280.3 L340.1 281.5 L338.2 282.7 L336.3 283.9 L334.2 285.0 L332.0 286.0 L329.7 287.0 L327.2 288.0 L324.6 289.0 L321.9 290.0 L319.0 290.9 L316.1 291.9 L313.1 292.8 L309.9 293.7 L306.7 294.6 L303.5 295.4 L300.1 296.2 L296.8 297.0 L293.3 297.7 L289.9 298.4 L286.4 299.0 L283.0 299.6 L279.5 300.2 L276.0 300.6 L272.6 301.0 L269.2 301.4 L265.8 301.6 L262.5 301.8 L259.2 302.0 L256.0 302.0 L252.8 302.0 L249.5 301.8 L246.2 301.6 L242.8 301.4 L239.4 301.0 L236.0 300.6 L232.5 300.2 L229.0 299.6 L225.6 299.0 L222.1 298.4 L218.7 297.7 L215.2 297.0 L211.9 296.2 L208.5 295.4 L205.3 294.6 L202.1 293.7 L198.9 292.8 L195.9 291.9 L193.0 290.9 L190.1 290.0 L187.4 289.0 L184.8 288.0 L182.3 287.0 L180.0 286.0 L177.8 285.0 L175.7 283.9 L173.8 282.7 L171.9 281.5 L170.2 280.3 L168.5 279.0 L166.9 277.7 L165.4 276.4 L164.0 275.0 L162.6 273.6 L161.4 272.2 L160.1 270.8 L159.0 269.3 L157.8 267.9 L156.7 266.4 L155.7 265.0 L154.7 263.5 L153.7 262.1 L152.7 260.7 L151.8 259.3 L150.8 257.9 L149.9 256.6 L149.0 255.3 L148.0 254.0 L147.1 252.8 L146.2 251.6 L145.5 250.5 L144.8 249.4 L144.1 248.3 L143.5 247.2 L143.0 246.2 L142.4 245.2 L142.0 244.2 L141.5 243.2 L141.1 242.1 L140.6 241.1 L140.2 240.1 L139.8 239.0 L139.3 237.9 L138.9 236.8 L138.4 235.7 L137.9 234.5 L137.4 233.2 L136.8 231.9 L136.2 230.5 L135.5 229.1 L134.8 227.6 L134.0 226.0 L133.1 224.3 L132.1 222.6 L131.0 220.9 L129.8 219.1 L128.6 217.3 L127.3 215.4 L125.9 213.4 L124.5 211.5 L123.1 209.5 L121.7 207.4 L120.3 205.4 L118.9 203.2 L117.5 201.1 L116.2 198.9 L114.9 196.7 L113.7 194.5 L112.6 192.3 L111.5 190.0 L110.6 187.7 L109.8 185.4 L109.1 183.1 L108.6 180.7 L108.2 178.4 L108.0 176.0 L107.9 173.6 L107.9 171.1 L108.0 168.5 L108.2 165.9 L108.5 163.2 L108.9 160.4 L109.3 157.6 L109.9 154.8 L110.5 152.0 L111.1 149.1 L111.9 146.2 L112.8 143.4 L113.7 140.5 L114.6 137.7 L115.7 134.9 L116.8 132.1 L118.0 129.3 L119.2 126.6 L120.6 124.0 L121.9 121.4 L123.4 118.9 L124.9 116.5 L126.4 114.2 L128.0 112.0 L129.7 109.8 L131.4 107.7 L133.3 105.6 L135.3 103.6 L137.3 101.6 L139.4 99.6 L141.6 97.7 L143.9 95.8 L146.2 93.9 L148.6 92.1 L151.0 90.3 L153.5 88.6 L156.0 87.0 L158.6 85.3 L161.3 83.7 L163.9 82.2 L166.6 80.7 L169.3 79.3 L172.1 78.0 L174.9 76.7 L177.6 75.4 L180.4 74.2 L183.2 73.1 L186.0 72.0 L188.8 71.0 L191.7 70.0 L194.6 69.2 L197.6 68.3 L200.7 67.6 L203.7 66.9 L206.8 66.2 L210.0 65.6 L213.2 65.1 L216.4 64.6 L219.6 64.1 L222.9 63.8 L226.1 63.4 L229.4 63.1 L232.7 62.8 L236.0 62.6 L239.3 62.4 L242.6 62.2 L245.9 62.1 L249.1 62.0 L252.4 62.0 L255.6 62.0 L258.8 62.0 Z" fill="#efe9dc" stroke="#0b0b0c" stroke-width="8" stroke-linejoin="round"/>
<path d="M291.9 68.8 L295.0 69.4 L298.1 70.1 L301.2 70.7 L304.2 71.4 L307.3 72.1 L310.2 72.8 L313.2 73.6 L316.0 74.4 L318.9 75.3 L321.6 76.2 L324.3 77.2 L326.9 78.2 L329.5 79.2 L332.0 80.3 L334.4 81.5 L336.8 82.7 L339.2 84.0 L341.5 85.4 L343.8 86.8 L346.1 88.2 L348.4 89.7 L350.6 91.2 L352.8 92.8 L354.9 94.5 L357.0 96.1 L359.0 97.8 L361.0 99.5 L363.0 101.3 L364.9 103.1 L366.7 104.9 L368.5 106.8 L370.2 108.6 L371.9 110.5 L373.5 112.4 L375.0 114.3 L376.5 116.2 L377.9 118.1 L379.2 120.1 L380.4 122.0 L381.7 124.1 L382.8 126.2 L384.0 128.3 L385.0 130.5 L386.1 132.8 L387.1 135.1 L388.0 137.4 L388.9 139.8 L389.7 142.1 L390.5 144.5 L391.2 147.0 L391.8 149.4 L392.4 151.8 L392.9 154.2 L393.4 156.6 L393.8 159.0 L394.1 161.4 L394.4 163.7 L394.6 166.0 L394.7 168.2 L394.7 170.4 L394.6 172.6 L394.5 174.7 L394.3 176.7 L393.9 178.7 L393.4 180.7 L392.8 182.8 L392.0 184.8 L391.2 186.9 L390.2 189.0 L389.2 191.1 L388.0 193.2 L386.8 195.3 L385.6 197.4 L384.3 199.5 L383.0 201.6 L381.7 203.6 L380.4 205.6 L379.1 207.6 L377.8 209.6 L376.5 211.5 L375.3 213.4 L374.1 215.3 L373.0 217.1 L372.0 218.8 L371.1 220.5 L370.3 222.2 L369.6 223.8 L369.0 225.3 L368.5 226.7 L368.9 226.9 L369.7 225.6 L370.6 224.3 L371.5 222.8 L372.5 221.3 L373.5 219.8 L374.7 218.2 L376.0 216.5 L377.3 214.8 L378.7 213.1 L380.1 211.3 L381.6 209.5 L383.1 207.6 L384.6 205.7 L386.1 203.8 L387.6 201.8 L389.1 199.8 L390.6 197.7 L392.0 195.6 L393.3 193.5 L394.6 191.3 L395.8 189.1 L396.9 186.9 L397.9 184.7 L398.8 182.4 L399.5 180.1 L400.1 177.7 L400.5 175.3 L400.7 173.0 L400.9 170.6 L401.0 168.2 L401.0 165.7 L400.9 163.2 L400.8 160.7 L400.5 158.1 L400.2 155.5 L399.8 152.9 L399.3 150.3 L398.7 147.7 L398.1 145.1 L397.4 142.5 L396.7 139.9 L395.8 137.3 L394.9 134.8 L393.9 132.3 L392.9 129.8 L391.8 127.3 L390.6 124.9 L389.4 122.6 L388.1 120.3 L386.8 118.1 L385.4 115.9 L384.0 113.8 L382.4 111.8 L380.8 109.7 L379.1 107.7 L377.4 105.7 L375.5 103.7 L373.7 101.7 L371.7 99.8 L369.7 98.0 L367.6 96.1 L365.5 94.3 L363.3 92.6 L361.1 90.9 L358.8 89.2 L356.4 87.6 L354.1 86.1 L351.6 84.6 L349.2 83.1 L346.7 81.8 L344.2 80.4 L341.6 79.2 L339.1 78.0 L336.5 76.9 L333.8 75.9 L331.2 74.9 L328.4 74.0 L325.6 73.2 L322.7 72.4 L319.8 71.7 L316.9 71.1 L313.9 70.5 L310.8 70.0 L307.7 69.6 L304.6 69.2 L301.5 68.8 L298.3 68.6 L295.2 68.4 L292.0 68.3 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M299.3 76.8 L302.1 77.6 L304.9 78.3 L307.6 79.1 L310.3 79.9 L312.9 80.7 L315.5 81.6 L318.0 82.5 L320.4 83.4 L322.8 84.4 L325.1 85.5 L327.3 86.6 L329.5 87.7 L331.8 88.9 L333.9 90.2 L336.1 91.5 L338.2 92.9 L340.3 94.3 L342.3 95.7 L344.4 97.2 L346.3 98.7 L348.3 100.3 L350.2 101.8 L352.0 103.5 L353.8 105.1 L355.6 106.8 L357.3 108.5 L358.9 110.2 L360.5 111.9 L362.1 113.7 L363.6 115.4 L365.0 117.2 L366.3 119.0 L367.6 120.8 L368.8 122.6 L370.0 124.4 L371.1 126.3 L372.2 128.2 L373.2 130.2 L374.2 132.3 L375.2 134.4 L376.1 136.5 L377.0 138.7 L377.8 140.9 L378.6 143.1 L379.3 145.3 L379.9 147.6 L380.5 149.8 L381.1 152.1 L381.6 154.3 L382.0 156.5 L382.4 158.7 L382.7 160.9 L382.9 163.1 L383.1 165.2 L383.2 167.3 L383.2 169.4 L383.2 171.4 L383.1 173.3 L382.8 175.2 L382.5 177.0 L382.0 178.9 L381.4 180.9 L380.7 182.8 L379.9 184.7 L379.0 186.7 L378.1 188.7 L377.0 190.6 L375.9 192.6 L374.8 194.5 L373.6 196.5 L372.4 198.4 L371.2 200.3 L370.0 202.2 L368.8 204.0 L367.6 205.8 L366.4 207.6 L365.3 209.4 L364.2 211.1 L363.2 212.8 L362.3 214.4 L361.6 216.0 L362.0 216.3 L363.1 214.9 L364.2 213.4 L365.4 211.9 L366.6 210.3 L367.9 208.7 L369.3 207.1 L370.6 205.4 L372.0 203.7 L373.4 201.9 L374.8 200.1 L376.2 198.3 L377.6 196.4 L379.0 194.5 L380.3 192.6 L381.5 190.6 L382.7 188.6 L383.8 186.6 L384.8 184.6 L385.7 182.5 L386.5 180.4 L387.2 178.2 L387.8 176.1 L388.1 173.9 L388.4 171.7 L388.6 169.5 L388.6 167.3 L388.6 165.0 L388.6 162.7 L388.4 160.4 L388.2 158.0 L387.9 155.6 L387.5 153.2 L387.1 150.8 L386.6 148.4 L386.0 146.0 L385.3 143.5 L384.6 141.1 L383.8 138.8 L383.0 136.4 L382.1 134.1 L381.1 131.8 L380.1 129.5 L379.0 127.3 L377.9 125.2 L376.7 123.0 L375.5 121.0 L374.2 119.0 L372.9 117.1 L371.4 115.2 L369.9 113.3 L368.4 111.4 L366.8 109.6 L365.1 107.7 L363.3 105.9 L361.5 104.2 L359.6 102.5 L357.7 100.8 L355.7 99.1 L353.7 97.5 L351.6 95.9 L349.5 94.4 L347.4 92.9 L345.2 91.5 L342.9 90.2 L340.7 88.8 L338.4 87.6 L336.0 86.4 L333.7 85.2 L331.3 84.1 L328.9 83.1 L326.5 82.2 L324.0 81.3 L321.4 80.5 L318.9 79.8 L316.2 79.1 L313.5 78.5 L310.8 77.9 L308.0 77.4 L305.2 77.0 L302.3 76.6 L299.4 76.3 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M304.5 85.3 L306.9 86.1 L309.3 87.0 L311.6 87.8 L313.9 88.7 L316.0 89.7 L318.2 90.7 L320.2 91.7 L322.3 92.8 L324.3 93.9 L326.3 95.1 L328.3 96.3 L330.3 97.6 L332.2 98.9 L334.1 100.2 L336.0 101.6 L337.8 103.0 L339.6 104.4 L341.3 105.9 L343.0 107.4 L344.7 108.9 L346.3 110.5 L347.9 112.0 L349.4 113.6 L350.8 115.2 L352.3 116.9 L353.6 118.5 L354.9 120.1 L356.2 121.8 L357.4 123.4 L358.5 125.1 L359.6 126.8 L360.6 128.5 L361.6 130.3 L362.5 132.2 L363.5 134.1 L364.4 136.0 L365.2 138.0 L366.0 140.0 L366.7 142.0 L367.4 144.1 L368.1 146.1 L368.7 148.2 L369.3 150.3 L369.8 152.3 L370.2 154.4 L370.6 156.5 L371.0 158.5 L371.2 160.5 L371.5 162.5 L371.6 164.5 L371.7 166.4 L371.7 168.3 L371.7 170.2 L371.6 172.0 L371.4 173.7 L371.1 175.4 L370.7 177.2 L370.1 179.0 L369.5 180.8 L368.7 182.6 L367.9 184.4 L367.0 186.2 L366.1 188.0 L365.1 189.8 L364.0 191.6 L362.9 193.4 L361.8 195.2 L360.7 197.0 L359.6 198.7 L358.5 200.4 L357.4 202.1 L356.4 203.8 L355.4 205.4 L355.8 205.7 L357.1 204.3 L358.3 202.8 L359.6 201.2 L360.9 199.7 L362.2 198.0 L363.5 196.4 L364.8 194.7 L366.1 193.0 L367.3 191.3 L368.5 189.5 L369.7 187.7 L370.8 185.9 L371.8 184.0 L372.7 182.2 L373.6 180.3 L374.3 178.3 L374.9 176.4 L375.4 174.4 L375.8 172.4 L376.0 170.5 L376.2 168.5 L376.3 166.4 L376.3 164.3 L376.2 162.2 L376.1 160.0 L375.9 157.9 L375.6 155.7 L375.2 153.5 L374.8 151.2 L374.4 149.0 L373.8 146.8 L373.2 144.6 L372.6 142.4 L371.9 140.2 L371.1 138.1 L370.3 135.9 L369.4 133.8 L368.4 131.7 L367.5 129.7 L366.4 127.7 L365.3 125.8 L364.2 123.9 L363.0 122.1 L361.8 120.3 L360.4 118.6 L359.1 116.8 L357.6 115.1 L356.1 113.4 L354.6 111.8 L353.0 110.1 L351.3 108.5 L349.6 106.9 L347.8 105.4 L346.0 103.9 L344.1 102.4 L342.2 101.0 L340.3 99.6 L338.3 98.3 L336.3 97.0 L334.2 95.7 L332.1 94.5 L330.0 93.4 L327.9 92.3 L325.7 91.2 L323.5 90.3 L321.3 89.4 L319.1 88.5 L316.8 87.7 L314.5 87.0 L312.1 86.3 L309.7 85.7 L307.2 85.2 L304.7 84.8 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M307.3 94.0 L309.3 94.9 L311.3 95.9 L313.2 96.8 L315.0 97.8 L316.9 98.9 L318.7 100.0 L320.5 101.1 L322.3 102.3 L324.1 103.5 L325.8 104.7 L327.5 106.0 L329.2 107.3 L330.8 108.6 L332.4 110.0 L334.0 111.3 L335.5 112.7 L337.0 114.2 L338.4 115.6 L339.8 117.1 L341.1 118.6 L342.4 120.0 L343.7 121.5 L344.9 123.1 L346.0 124.6 L347.1 126.1 L348.1 127.6 L349.1 129.2 L350.1 130.8 L351.0 132.4 L351.8 134.1 L352.7 135.9 L353.5 137.6 L354.3 139.4 L355.0 141.3 L355.7 143.1 L356.3 145.0 L356.9 146.9 L357.5 148.8 L358.0 150.7 L358.5 152.6 L358.9 154.5 L359.3 156.4 L359.6 158.2 L359.8 160.1 L360.0 161.9 L360.2 163.7 L360.3 165.5 L360.3 167.3 L360.3 169.0 L360.2 170.6 L360.0 172.2 L359.7 173.8 L359.3 175.5 L358.8 177.1 L358.2 178.8 L357.6 180.4 L356.8 182.1 L356.0 183.8 L355.1 185.4 L354.2 187.1 L353.3 188.8 L352.3 190.4 L351.3 192.0 L350.3 193.7 L349.3 195.3 L349.7 195.6 L351.0 194.2 L352.2 192.7 L353.4 191.2 L354.5 189.6 L355.7 188.0 L356.8 186.4 L357.8 184.8 L358.8 183.2 L359.8 181.5 L360.6 179.8 L361.4 178.1 L362.1 176.3 L362.6 174.6 L363.1 172.8 L363.4 171.0 L363.6 169.2 L363.8 167.4 L363.9 165.5 L363.9 163.6 L363.8 161.7 L363.7 159.7 L363.5 157.7 L363.3 155.7 L362.9 153.7 L362.6 151.7 L362.1 149.7 L361.7 147.7 L361.1 145.7 L360.5 143.7 L359.9 141.7 L359.2 139.7 L358.4 137.8 L357.6 135.8 L356.8 133.9 L355.9 132.1 L354.9 130.3 L353.9 128.5 L352.9 126.8 L351.8 125.2 L350.7 123.6 L349.5 122.0 L348.2 120.4 L346.9 118.8 L345.5 117.3 L344.1 115.8 L342.6 114.3 L341.1 112.8 L339.5 111.4 L337.9 110.0 L336.3 108.7 L334.6 107.3 L332.8 106.0 L331.0 104.8 L329.2 103.6 L327.4 102.4 L325.5 101.3 L323.6 100.2 L321.7 99.1 L319.7 98.2 L317.7 97.2 L315.8 96.4 L313.7 95.5 L311.7 94.8 L309.6 94.1 L307.5 93.5 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M307.8 102.9 L309.4 103.9 L311.1 104.9 L312.7 105.9 L314.4 107.0 L316.0 108.1 L317.5 109.3 L319.1 110.4 L320.6 111.6 L322.1 112.8 L323.5 114.1 L324.9 115.3 L326.3 116.6 L327.6 117.9 L328.9 119.2 L330.2 120.5 L331.4 121.9 L332.6 123.2 L333.7 124.6 L334.8 126.0 L335.9 127.4 L336.8 128.8 L337.8 130.1 L338.7 131.6 L339.5 133.0 L340.3 134.5 L341.1 136.1 L341.9 137.6 L342.6 139.3 L343.3 140.9 L344.0 142.6 L344.6 144.3 L345.2 146.0 L345.8 147.7 L346.3 149.4 L346.7 151.1 L347.2 152.9 L347.5 154.6 L347.9 156.3 L348.2 158.0 L348.4 159.7 L348.6 161.4 L348.7 163.0 L348.8 164.6 L348.9 166.2 L348.8 167.8 L348.8 169.3 L348.6 170.7 L348.3 172.2 L348.0 173.7 L347.5 175.2 L347.0 176.7 L346.4 178.3 L345.7 179.8 L345.0 181.3 L344.2 182.8 L343.4 184.4 L342.5 185.9 L343.0 186.2 L344.0 184.8 L345.0 183.4 L346.0 181.9 L346.9 180.4 L347.8 178.9 L348.5 177.4 L349.2 175.9 L349.8 174.3 L350.3 172.7 L350.8 171.1 L351.0 169.5 L351.2 167.9 L351.4 166.3 L351.5 164.6 L351.5 162.9 L351.4 161.2 L351.3 159.4 L351.1 157.6 L350.9 155.8 L350.6 154.0 L350.3 152.2 L349.9 150.4 L349.5 148.5 L349.0 146.7 L348.5 144.9 L347.9 143.1 L347.3 141.3 L346.6 139.6 L345.8 137.9 L345.1 136.2 L344.3 134.5 L343.4 132.9 L342.5 131.3 L341.6 129.7 L340.6 128.3 L339.6 126.8 L338.5 125.4 L337.4 124.0 L336.2 122.6 L334.9 121.2 L333.7 119.8 L332.3 118.5 L330.9 117.2 L329.5 115.9 L328.1 114.6 L326.6 113.4 L325.0 112.2 L323.5 111.0 L321.8 109.9 L320.2 108.8 L318.5 107.8 L316.8 106.7 L315.1 105.8 L313.4 104.9 L311.6 104.0 L309.8 103.2 L308.0 102.4 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M343.5 267.5 L342.1 268.7 L340.7 269.9 L339.2 271.1 L337.7 272.3 L336.0 273.4 L334.3 274.4 L332.5 275.5 L330.7 276.4 L328.7 277.4 L326.6 278.2 L324.4 279.1 L322.1 279.9 L319.6 280.7 L317.0 281.5 L314.3 282.4 L311.5 283.1 L308.6 283.9 L305.6 284.7 L302.6 285.4 L299.5 286.1 L296.3 286.8 L293.2 287.4 L289.9 288.1 L286.7 288.6 L283.4 289.2 L280.2 289.7 L276.9 290.1 L273.7 290.5 L270.4 290.9 L267.3 291.1 L264.1 291.4 L261.0 291.6 L258.0 291.7 L255.0 291.7 L252.0 291.7 L249.0 291.6 L245.9 291.4 L242.7 291.2 L239.6 290.9 L236.3 290.6 L233.1 290.2 L229.8 289.7 L226.6 289.2 L223.3 288.7 L220.0 288.1 L216.8 287.5 L213.6 286.9 L210.5 286.2 L207.4 285.5 L204.3 284.8 L201.4 284.0 L198.5 283.3 L195.7 282.5 L193.0 281.7 L190.4 280.9 L187.9 280.0 L185.5 279.2 L183.3 278.4 L181.2 277.5 L179.2 276.6 L177.4 275.6 L175.6 274.6 L173.8 273.5 L172.2 272.4 L170.6 271.3 L169.1 270.2 L168.8 270.5 L170.1 272.0 L171.5 273.3 L173.0 274.6 L174.7 275.9 L176.4 277.2 L178.3 278.4 L180.2 279.5 L182.3 280.6 L184.5 281.7 L186.8 282.8 L189.3 283.8 L191.9 284.9 L194.6 285.9 L197.3 286.9 L200.2 287.9 L203.2 288.8 L206.2 289.8 L209.4 290.7 L212.5 291.5 L215.8 292.4 L219.0 293.1 L222.3 293.9 L225.6 294.6 L228.9 295.2 L232.3 295.7 L235.6 296.2 L238.9 296.7 L242.2 297.0 L245.5 297.3 L248.7 297.5 L251.9 297.7 L255.0 297.7 L258.1 297.7 L261.3 297.5 L264.5 297.3 L267.8 297.1 L271.1 296.7 L274.4 296.3 L277.7 295.8 L281.1 295.2 L284.4 294.6 L287.7 294.0 L291.0 293.2 L294.3 292.5 L297.5 291.6 L300.7 290.8 L303.8 289.9 L306.8 289.0 L309.8 288.0 L312.7 287.0 L315.5 286.0 L318.2 285.0 L320.8 283.9 L323.2 282.9 L325.6 281.8 L327.8 280.8 L329.9 279.7 L331.8 278.5 L333.7 277.3 L335.4 276.1 L337.1 274.8 L338.6 273.5 L340.1 272.1 L341.4 270.8 L342.7 269.3 L343.9 267.9 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M327.9 269.8 L326.1 270.8 L324.2 271.7 L322.2 272.5 L320.1 273.3 L317.8 274.1 L315.5 274.9 L313.0 275.7 L310.4 276.5 L307.8 277.3 L305.0 278.1 L302.2 278.8 L299.3 279.5 L296.4 280.2 L293.4 280.9 L290.4 281.5 L287.3 282.1 L284.2 282.7 L281.1 283.2 L278.0 283.7 L274.9 284.1 L271.8 284.5 L268.7 284.8 L265.7 285.1 L262.7 285.3 L259.7 285.5 L256.8 285.6 L254.0 285.7 L251.2 285.6 L248.3 285.5 L245.3 285.4 L242.3 285.1 L239.3 284.9 L236.2 284.5 L233.1 284.2 L230.0 283.7 L226.9 283.2 L223.8 282.7 L220.7 282.2 L217.6 281.6 L214.6 281.0 L211.6 280.3 L208.6 279.6 L205.8 278.9 L202.9 278.2 L200.2 277.4 L197.5 276.6 L195.0 275.9 L192.5 275.1 L190.1 274.3 L187.9 273.5 L185.8 272.7 L183.7 271.8 L183.5 272.3 L185.4 273.3 L187.5 274.3 L189.7 275.3 L192.0 276.3 L194.5 277.3 L197.0 278.2 L199.6 279.2 L202.4 280.1 L205.2 281.0 L208.1 281.8 L211.0 282.7 L214.0 283.5 L217.0 284.2 L220.1 284.9 L223.2 285.6 L226.3 286.2 L229.5 286.8 L232.6 287.3 L235.8 287.8 L238.9 288.2 L242.0 288.5 L245.1 288.8 L248.1 289.0 L251.1 289.1 L254.0 289.1 L256.9 289.1 L259.9 289.0 L262.9 288.8 L266.0 288.6 L269.1 288.2 L272.2 287.8 L275.4 287.4 L278.5 286.9 L281.7 286.3 L284.8 285.7 L287.9 285.0 L291.0 284.3 L294.0 283.5 L297.0 282.7 L300.0 281.9 L302.9 281.1 L305.7 280.2 L308.4 279.3 L311.0 278.3 L313.6 277.4 L316.0 276.4 L318.3 275.5 L320.6 274.5 L322.6 273.5 L324.6 272.5 L326.4 271.4 L328.1 270.3 Z" fill="#0b0b0c" clip-path="url(#head)"/>
<path d="M195.9 103.9 L195.3 104.2 L194.7 104.6 L193.9 105.0 L193.1 105.5 L192.3 106.0 L191.4 106.6 L190.4 107.2 L189.4 107.8 L188.4 108.5 L187.3 109.2 L186.3 110.0 L185.2 110.8 L184.1 111.6 L183.0 112.5 L181.9 113.4 L180.8 114.3 L179.7 115.2 L178.7 116.2 L177.7 117.2 L176.8 118.2 L175.9 119.2 L175.0 120.2 L174.2 121.3 L173.5 122.4 L172.8 123.5 L172.2 124.6 L171.6 125.8 L171.0 127.0 L170.5 128.3 L170.0 129.6 L169.5 130.9 L169.1 132.2 L168.7 133.6 L168.4 134.9 L168.0 136.3 L167.7 137.6 L167.5 138.9 L167.2 140.2 L167.0 141.4 L166.8 142.6 L166.6 143.7 L166.4 144.8 L166.3 145.9 L166.2 146.9 L166.1 147.7 L166.0 148.6 L165.9 149.3 L165.9 149.9 L166.1 150.1 L166.5 149.5 L166.9 148.9 L167.3 148.2 L167.8 147.4 L168.2 146.5 L168.7 145.5 L169.2 144.5 L169.7 143.5 L170.2 142.4 L170.7 141.3 L171.2 140.1 L171.8 138.9 L172.3 137.7 L172.9 136.5 L173.4 135.3 L174.0 134.1 L174.6 132.9 L175.1 131.8 L175.7 130.6 L176.3 129.5 L176.8 128.5 L177.4 127.5 L178.0 126.5 L178.5 125.6 L179.1 124.8 L179.7 123.9 L180.5 122.9 L181.2 122.0 L182.0 121.0 L182.8 120.0 L183.7 119.0 L184.5 118.0 L185.4 117.0 L186.3 116.0 L187.2 115.0 L188.1 114.0 L189.0 113.0 L189.8 112.0 L190.6 111.0 L191.5 110.1 L192.2 109.2 L193.0 108.3 L193.6 107.5 L194.3 106.7 L194.8 106.0 L195.4 105.3 L195.8 104.7 L196.1 104.1 Z" fill="#0b0b0c"/>
<path d="M221.9 95.9 L221.5 96.0 L221.0 96.2 L220.5 96.5 L220.0 96.7 L219.4 97.1 L218.8 97.5 L218.2 97.9 L217.6 98.3 L217.0 98.8 L216.4 99.4 L215.8 99.9 L215.3 100.6 L214.8 101.2 L214.3 101.9 L213.9 102.5 L213.5 103.2 L213.2 103.9 L212.9 104.6 L212.6 105.2 L212.4 105.9 L212.2 106.4 L212.0 107.0 L211.9 107.5 L211.9 107.9 L212.1 108.1 L212.5 108.0 L213.0 107.8 L213.5 107.5 L214.0 107.3 L214.6 106.9 L215.2 106.5 L215.8 106.1 L216.4 105.7 L217.0 105.2 L217.6 104.6 L218.2 104.1 L218.7 103.4 L219.2 102.8 L219.7 102.1 L220.1 101.5 L220.5 100.8 L220.8 100.1 L221.1 99.4 L221.4 98.8 L221.6 98.1 L221.8 97.6 L222.0 97.0 L222.1 96.5 L222.1 96.1 Z" fill="#0b0b0c"/>
<path d="M287.9 98.1 L288.4 98.6 L288.9 99.1 L289.6 99.6 L290.3 100.2 L291.1 100.8 L291.9 101.4 L292.8 102.0 L293.8 102.7 L294.7 103.4 L295.8 104.1 L296.8 104.8 L297.9 105.5 L299.0 106.2 L300.1 107.0 L301.1 107.7 L302.2 108.5 L303.3 109.2 L304.4 110.0 L305.4 110.7 L306.4 111.4 L307.4 112.2 L308.3 112.9 L309.2 113.6 L310.0 114.3 L310.9 115.0 L311.7 115.8 L312.5 116.6 L313.4 117.5 L314.3 118.4 L315.2 119.3 L316.1 120.3 L317.1 121.2 L318.0 122.2 L318.9 123.2 L319.9 124.2 L320.8 125.2 L321.7 126.1 L322.6 127.1 L323.5 128.0 L324.3 128.9 L325.1 129.8 L325.9 130.6 L326.7 131.3 L327.4 132.0 L328.1 132.7 L328.7 133.2 L329.3 133.7 L329.9 134.1 L330.1 133.9 L329.9 133.3 L329.6 132.6 L329.2 131.8 L328.8 131.0 L328.4 130.1 L327.9 129.2 L327.4 128.2 L326.8 127.1 L326.2 126.0 L325.6 124.9 L324.9 123.7 L324.2 122.6 L323.5 121.4 L322.7 120.2 L322.0 119.0 L321.2 117.9 L320.3 116.7 L319.5 115.6 L318.6 114.5 L317.7 113.5 L316.8 112.5 L315.9 111.5 L314.9 110.6 L314.0 109.7 L313.0 108.9 L311.9 108.1 L310.8 107.4 L309.7 106.6 L308.5 105.9 L307.3 105.2 L306.1 104.6 L304.9 104.0 L303.6 103.4 L302.4 102.8 L301.1 102.3 L299.9 101.8 L298.6 101.3 L297.4 100.8 L296.3 100.4 L295.1 100.0 L294.0 99.6 L293.0 99.3 L292.0 99.0 L291.1 98.7 L290.2 98.4 L289.4 98.2 L288.7 98.0 L288.1 97.9 Z" fill="#0b0b0c"/>
<circle cx="172" cy="214" r="52" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7"/>
<circle cx="176" cy="217" r="37" fill="#c2672b" stroke="#0b0b0c" stroke-width="5"/>
<ellipse cx="178.0" cy="218" rx="26" ry="18" fill="#0b0b0c"/>
<circle cx="169.0" cy="210" r="7.5" fill="#efe9dc"/>
<circle cx="188.0" cy="224" r="3.5" fill="#efe9dc"/>
<path d="M122.7 196.7 L123.6 196.1 L124.5 195.3 L125.5 194.3 L126.6 193.3 L127.7 192.2 L128.9 190.9 L130.2 189.6 L131.5 188.2 L132.9 186.8 L134.2 185.3 L135.7 183.9 L137.1 182.4 L138.6 180.9 L140.1 179.4 L141.6 178.0 L143.1 176.5 L144.6 175.2 L146.1 173.9 L147.6 172.8 L149.0 171.7 L150.4 170.7 L151.7 169.9 L153.0 169.2 L154.2 168.6 L155.5 168.1 L156.9 167.7 L158.4 167.2 L159.9 166.8 L161.5 166.4 L163.1 166.1 L164.8 165.8 L166.5 165.6 L168.2 165.4 L169.9 165.2 L171.7 165.1 L173.4 165.0 L175.2 164.9 L176.9 164.9 L178.7 164.9 L180.4 164.9 L182.1 165.0 L183.7 165.1 L185.3 165.3 L186.9 165.5 L188.4 165.7 L189.9 165.9 L191.2 166.2 L192.5 166.5 L193.6 166.8 L194.8 167.2 L196.0 167.8 L197.2 168.4 L198.4 169.1 L199.7 169.9 L201.0 170.8 L202.2 171.8 L203.5 172.8 L204.8 173.8 L206.0 174.9 L207.3 176.0 L208.5 177.1 L209.7 178.2 L210.9 179.3 L212.0 180.4 L213.1 181.4 L214.1 182.4 L215.1 183.3 L216.0 184.2 L216.9 185.0 L217.8 185.7 L218.6 186.3 L219.3 186.7 L220.7 185.3 L220.3 184.6 L219.8 183.8 L219.3 183.0 L218.7 182.0 L218.0 180.9 L217.3 179.8 L216.5 178.5 L215.7 177.3 L214.9 175.9 L213.9 174.6 L213.0 173.2 L212.0 171.8 L210.9 170.4 L209.8 168.9 L208.6 167.5 L207.4 166.2 L206.1 164.8 L204.8 163.6 L203.4 162.3 L201.9 161.2 L200.4 160.1 L198.9 159.1 L197.2 158.2 L195.5 157.5 L193.9 156.9 L192.2 156.4 L190.5 155.9 L188.7 155.5 L186.8 155.1 L185.0 154.8 L183.1 154.5 L181.1 154.3 L179.1 154.2 L177.1 154.1 L175.1 154.0 L173.1 154.0 L171.0 154.1 L169.0 154.2 L167.0 154.4 L164.9 154.7 L162.9 155.0 L160.9 155.4 L159.0 155.9 L157.1 156.5 L155.2 157.1 L153.3 157.7 L151.5 158.5 L149.8 159.4 L148.0 160.4 L146.2 161.5 L144.5 162.8 L142.9 164.3 L141.3 165.8 L139.8 167.3 L138.3 169.0 L136.9 170.7 L135.5 172.5 L134.2 174.3 L132.9 176.1 L131.6 177.9 L130.4 179.7 L129.3 181.5 L128.2 183.2 L127.2 185.0 L126.2 186.6 L125.3 188.2 L124.4 189.7 L123.6 191.0 L122.9 192.3 L122.3 193.4 L121.7 194.4 L121.3 195.3 Z" fill="#0b0b0c"/>
<path d="M137.9 258.2 L138.6 258.7 L139.4 259.3 L140.3 259.9 L141.2 260.6 L142.3 261.4 L143.5 262.2 L144.7 263.1 L146.0 264.0 L147.4 264.9 L148.8 265.8 L150.3 266.8 L151.8 267.7 L153.3 268.6 L155.0 269.5 L156.6 270.4 L158.3 271.2 L159.9 271.9 L161.6 272.6 L163.4 273.3 L165.1 273.8 L166.8 274.3 L168.5 274.6 L170.2 274.9 L171.9 275.0 L173.6 275.0 L175.4 274.8 L177.1 274.6 L178.9 274.2 L180.7 273.8 L182.5 273.3 L184.2 272.7 L186.0 272.0 L187.8 271.3 L189.6 270.6 L191.3 269.8 L193.0 268.9 L194.6 268.1 L196.2 267.2 L197.8 266.4 L199.3 265.5 L200.7 264.7 L202.0 263.9 L203.3 263.2 L204.4 262.5 L205.5 261.8 L206.5 261.2 L207.3 260.7 L208.1 260.2 L207.9 259.8 L207.0 259.9 L206.0 260.1 L204.9 260.4 L203.7 260.7 L202.4 261.2 L201.0 261.6 L199.5 262.1 L197.9 262.6 L196.3 263.1 L194.7 263.7 L193.0 264.3 L191.3 264.8 L189.5 265.4 L187.8 265.9 L186.1 266.4 L184.3 266.9 L182.6 267.4 L180.9 267.8 L179.3 268.2 L177.7 268.5 L176.2 268.7 L174.7 268.9 L173.4 269.0 L172.1 269.0 L170.8 268.9 L169.5 268.8 L168.0 268.5 L166.6 268.2 L165.0 267.8 L163.5 267.4 L161.9 266.9 L160.3 266.3 L158.6 265.7 L157.0 265.1 L155.3 264.5 L153.7 263.8 L152.1 263.1 L150.5 262.5 L149.0 261.8 L147.5 261.2 L146.0 260.6 L144.7 260.0 L143.3 259.5 L142.1 259.0 L141.0 258.6 L139.9 258.2 L138.9 257.9 L138.1 257.8 Z" fill="#0b0b0c"/>
<circle cx="340" cy="214" r="52" fill="#efe9dc" stroke="#0b0b0c" stroke-width="7"/>
<circle cx="336" cy="217" r="37" fill="#c2672b" stroke="#0b0b0c" stroke-width="5"/>
<ellipse cx="334.0" cy="218" rx="26" ry="18" fill="#0b0b0c"/>
<circle cx="325.0" cy="210" r="7.5" fill="#efe9dc"/>
<circle cx="344.0" cy="224" r="3.5" fill="#efe9dc"/>
<path d="M390.7 195.3 L390.3 194.4 L389.7 193.4 L389.1 192.3 L388.4 191.0 L387.6 189.7 L386.7 188.2 L385.8 186.6 L384.8 185.0 L383.8 183.2 L382.7 181.5 L381.6 179.7 L380.4 177.9 L379.1 176.1 L377.8 174.3 L376.5 172.5 L375.1 170.7 L373.7 169.0 L372.2 167.3 L370.7 165.8 L369.1 164.3 L367.5 162.8 L365.8 161.5 L364.0 160.4 L362.2 159.4 L360.5 158.5 L358.7 157.7 L356.8 157.1 L354.9 156.5 L353.0 155.9 L351.1 155.4 L349.1 155.0 L347.1 154.7 L345.0 154.4 L343.0 154.2 L341.0 154.1 L338.9 154.0 L336.9 154.0 L334.9 154.1 L332.9 154.2 L330.9 154.3 L328.9 154.5 L327.0 154.8 L325.2 155.1 L323.3 155.5 L321.5 155.9 L319.8 156.4 L318.1 156.9 L316.5 157.5 L314.8 158.2 L313.1 159.1 L311.6 160.1 L310.1 161.2 L308.6 162.3 L307.2 163.6 L305.9 164.8 L304.6 166.2 L303.4 167.5 L302.2 168.9 L301.1 170.4 L300.0 171.8 L299.0 173.2 L298.1 174.6 L297.1 175.9 L296.3 177.3 L295.5 178.5 L294.7 179.8 L294.0 180.9 L293.3 182.0 L292.7 183.0 L292.2 183.8 L291.7 184.6 L291.3 185.3 L292.7 186.7 L293.4 186.3 L294.2 185.7 L295.1 185.0 L296.0 184.2 L296.9 183.3 L297.9 182.4 L298.9 181.4 L300.0 180.4 L301.1 179.3 L302.3 178.2 L303.5 177.1 L304.7 176.0 L306.0 174.9 L307.2 173.8 L308.5 172.8 L309.8 171.8 L311.0 170.8 L312.3 169.9 L313.6 169.1 L314.8 168.4 L316.0 167.8 L317.2 167.2 L318.4 166.8 L319.5 166.5 L320.8 166.2 L322.1 165.9 L323.6 165.7 L325.1 165.5 L326.7 165.3 L328.3 165.1 L329.9 165.0 L331.6 164.9 L333.3 164.9 L335.1 164.9 L336.8 164.9 L338.6 165.0 L340.3 165.1 L342.1 165.2 L343.8 165.4 L345.5 165.6 L347.2 165.8 L348.9 166.1 L350.5 166.4 L352.1 166.8 L353.6 167.2 L355.1 167.7 L356.5 168.1 L357.8 168.6 L359.0 169.2 L360.3 169.9 L361.6 170.7 L363.0 171.7 L364.4 172.8 L365.9 173.9 L367.4 175.2 L368.9 176.5 L370.4 178.0 L371.9 179.4 L373.4 180.9 L374.9 182.4 L376.3 183.9 L377.8 185.3 L379.1 186.8 L380.5 188.2 L381.8 189.6 L383.1 190.9 L384.3 192.2 L385.4 193.3 L386.5 194.3 L387.5 195.3 L388.4 196.1 L389.3 196.7 Z" fill="#0b0b0c"/>
<path d="M373.9 257.8 L373.1 257.9 L372.1 258.2 L371.0 258.6 L369.9 259.0 L368.7 259.5 L367.3 260.0 L366.0 260.6 L364.5 261.2 L363.0 261.8 L361.5 262.5 L359.9 263.1 L358.3 263.8 L356.7 264.5 L355.0 265.1 L353.4 265.7 L351.7 266.3 L350.1 266.9 L348.5 267.4 L347.0 267.8 L345.4 268.2 L344.0 268.5 L342.5 268.8 L341.2 268.9 L339.9 269.0 L338.6 269.0 L337.3 268.9 L335.8 268.7 L334.3 268.5 L332.7 268.2 L331.1 267.8 L329.4 267.4 L327.7 266.9 L325.9 266.4 L324.2 265.9 L322.5 265.4 L320.7 264.8 L319.0 264.3 L317.3 263.7 L315.7 263.1 L314.1 262.6 L312.5 262.1 L311.0 261.6 L309.6 261.2 L308.3 260.7 L307.1 260.4 L306.0 260.1 L305.0 259.9 L304.1 259.8 L303.9 260.2 L304.7 260.7 L305.5 261.2 L306.5 261.8 L307.6 262.5 L308.7 263.2 L310.0 263.9 L311.3 264.7 L312.7 265.5 L314.2 266.4 L315.8 267.2 L317.4 268.1 L319.0 268.9 L320.7 269.8 L322.4 270.6 L324.2 271.3 L326.0 272.0 L327.8 272.7 L329.5 273.3 L331.3 273.8 L333.1 274.2 L334.9 274.6 L336.6 274.8 L338.4 275.0 L340.1 275.0 L341.8 274.9 L343.5 274.6 L345.2 274.3 L346.9 273.8 L348.6 273.3 L350.4 272.6 L352.1 271.9 L353.7 271.2 L355.4 270.4 L357.0 269.5 L358.7 268.6 L360.2 267.7 L361.7 266.8 L363.2 265.8 L364.6 264.9 L366.0 264.0 L367.3 263.1 L368.5 262.2 L369.7 261.4 L370.8 260.6 L371.7 259.9 L372.6 259.3 L373.4 258.7 L374.1 258.2 Z" fill="#0b0b0c"/>
</g>
</svg>

After

Width:  |  Height:  |  Size: 77 KiB

Binary file not shown.
Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

+4
View File
@@ -0,0 +1,4 @@
allow-unwrap-in-tests = true
allow-expect-in-tests = true
allow-panic-in-tests = true
allow-indexing-slicing-in-tests = true
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "texturecraft-automation"
description = "TextureCraft automation: MCP server (rmcp), headless JSON-lines RPC and a bridge to the running app"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
texturecraft-engine = { workspace = true }
texturecraft-render = { workspace = true }
texturecraft-formats = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
image = { workspace = true }
rayon = { workspace = true }
rmcp = { workspace = true }
tokio = { workspace = true }
schemars = { workspace = true }
base64 = { workspace = true }
cap-std = { workspace = true }
getrandom = { workspace = true }
[dev-dependencies]
rmcp = { workspace = true, features = ["client"] }
+45
View File
@@ -0,0 +1,45 @@
# texturecraft-automation
Agent-facing automation for TextureCraft (layer L4: engine, render and formats; no UI toolkit).
The protocol and tool reference is [`docs/control-protocol.md`](../../docs/control-protocol.md).
## Public API
```rust
// An in-process session with file access and windowless renders.
pub struct Headless { pub session: Session, .. }
impl Headless {
pub fn new(session: Session, fs: Filesystem) -> Headless;
pub fn default_session() -> Result<Session, AutomationError>; // material ball, 1024
pub fn command_run(&mut self, id: &str, params: Value) -> Result<Value, AutomationError>;
pub fn batch(&mut self, steps: &[Value]) -> Value; // stops at the first error
pub fn open(&mut self, path: &str) -> Result<Value, AutomationError>; // .tcraft or mesh
pub fn import_mesh(&mut self, path: &str, resolution: Option<u32>, name: Option<&str>) -> Result<Value, AutomationError>;
pub fn save(&mut self, path: Option<&str>) -> Result<Value, AutomationError>;
pub fn export(&mut self, params: &Value) -> Result<Value, AutomationError>;
pub fn render_png(&mut self, o: &RenderOptions) -> Result<(u32, u32, Vec<u8>), AutomationError>;
pub fn handle(&mut self, method: &str, params: &Value) -> Result<Value, AutomationError>; // JSON-lines methods
}
pub enum Filesystem { Denied, TrustedLocal, Workspace(AuthorizedWorkspace) }
// Read and write roots as cap-std directory capabilities: `..`, absolute paths, drive
// prefixes, device names and symlink/junction escapes fail.
pub struct AuthorizedWorkspace;
pub fn workspace::authorize_command(id: &str, params: &Value) -> Result<(), AutomationError>;
pub struct TexturecraftMcp; // rmcp server: ::headless(Headless) | ::bridge(BridgeClient)
pub struct BridgeClient; // client of `texturecraft --control <port>`
pub mod rpc; // serve_lines (stdio), serve_tcp (loopback + token)
pub mod security; // tokens, bounded line reads, connection limit
pub mod budgets; // reply ceilings: 8 MiB JSON, 5 MiB / 2048 px PNG
```
## Rules
- Untrusted callers (MCP, `serve`) reach files only through `Filesystem::Workspace`; path-taking
`file.*` commands are refused by `authorize_command`. The CLI's own subcommands use
`Filesystem::TrustedLocal` (the user typed the paths).
- Renders create the GPU device on first use and return an error when there is no adapter; a
wgpu panic is caught and reported, and the device is recreated on the next render.
- Tests: `tests/agent_tasks.rs` drives the MCP server in process (tokio duplex) through ten
agent tasks, the workspace boundary and junk params for every tool.
+107
View File
@@ -0,0 +1,107 @@
//! Client for the running app's control channel (`texturecraft --control <port>`): one JSON
//! request per line, replies matched by `id`. Keeps one connection, reconnects once on failure.
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::Duration;
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::net::tcp::{OwnedReadHalf, OwnedWriteHalf};
use tokio::sync::Mutex;
use crate::AutomationError;
use crate::budgets::MAX_BRIDGE_REPLY_BYTES;
type Conn = (BufReader<OwnedReadHalf>, OwnedWriteHalf);
pub struct BridgeClient {
port: u16,
token: String,
conn: Mutex<Option<Conn>>,
next_id: AtomicU64,
}
impl BridgeClient {
/// A client for the app on `127.0.0.1:port` (loopback only, like the server).
pub fn new(port: u16, token: String) -> BridgeClient {
BridgeClient { port, token, conn: Mutex::new(None), next_id: AtomicU64::new(1) }
}
pub fn port(&self) -> u16 {
self.port
}
async fn connect(&self) -> Result<Conn, AutomationError> {
let addr = ("127.0.0.1", self.port);
let s = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(addr))
.await
.map_err(|_| AutomationError::Bridge(format!("timed out connecting to 127.0.0.1:{}", self.port)))?
.map_err(|e| {
AutomationError::Bridge(format!("cannot connect to 127.0.0.1:{} ({e}); start the app with `texturecraft --control {}`", self.port, self.port))
})?;
let (r, w) = s.into_split();
let mut conn = (BufReader::new(r), w);
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
tokio::time::timeout(Duration::from_secs(5), exchange(&mut conn, id, "auth", &json!({"token": self.token})))
.await
.map_err(|_| AutomationError::Bridge("authentication timed out".into()))??
.map_err(|e| AutomationError::Bridge(format!("authentication failed: {e}")))?;
Ok(conn)
}
/// Call a control method; returns its `result` or the app's error.
pub async fn call(&self, method: &str, params: Value) -> Result<Value, AutomationError> {
let mut guard = self.conn.lock().await;
for attempt in 0..2 {
let mut conn = match guard.take() {
Some(c) => c,
None => self.connect().await?,
};
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
match tokio::time::timeout(Duration::from_secs(150), exchange(&mut conn, id, method, &params)).await {
Ok(Ok(reply)) => {
// An oversized reply (`Bridge`) leaves unread bytes: drop that connection.
if !matches!(reply, Err(AutomationError::Bridge(_))) {
*guard = Some(conn);
}
return reply;
}
// A dropped connection (the app restarted) is retried once on a fresh one.
Ok(Err(e)) if attempt == 1 => return Err(e),
Ok(Err(_)) => {}
Err(_) => return Err(AutomationError::Bridge(format!("`{method}` timed out"))),
}
}
Err(AutomationError::Bridge(format!("`{method}` failed")))
}
}
/// Outer `Err`: transport failure (retryable). Inner: the app's answer.
async fn exchange(conn: &mut Conn, id: u64, method: &str, params: &Value) -> Result<Result<Value, AutomationError>, AutomationError> {
let io = |e: std::io::Error| AutomationError::Bridge(e.to_string());
let line = format!("{}\n", json!({"id": id, "method": method, "params": params}));
conn.1.write_all(line.as_bytes()).await.map_err(io)?;
conn.1.flush().await.map_err(io)?;
let mut buf = Vec::new();
loop {
buf.clear();
let n = (&mut conn.0).take(MAX_BRIDGE_REPLY_BYTES as u64 + 1).read_until(b'\n', &mut buf).await.map_err(io)?;
if n == 0 {
return Err(AutomationError::Bridge("the app closed the connection".into()));
}
if n > MAX_BRIDGE_REPLY_BYTES {
// Not retried: the request may have completed.
return Ok(Err(AutomationError::Bridge(format!("reply over {MAX_BRIDGE_REPLY_BYTES} bytes; the operation may have completed"))));
}
let Ok(v) = serde_json::from_slice::<Value>(&buf) else { continue };
if v.get("id").and_then(Value::as_u64) != Some(id) {
continue; // a stale reply to an earlier, timed-out request
}
return Ok(if v.get("ok").and_then(Value::as_bool) == Some(true) {
Ok(v.get("result").cloned().unwrap_or(Value::Null))
} else {
Err(AutomationError::App(v.get("error").and_then(Value::as_str).unwrap_or("unknown error").to_string()))
});
}
}
+75
View File
@@ -0,0 +1,75 @@
//! Ceilings for automation replies: rendered and screenshot PNGs and JSON payloads.
use serde::Serialize;
use crate::{AutomationError, bad};
/// Largest JSON reply (MCP tool text, one JSON line).
pub const MAX_RESPONSE_BYTES: usize = 8 << 20;
/// Largest PNG returned to a client (before base64).
pub const MAX_PNG_BYTES: usize = 5 << 20;
/// Largest render or screenshot edge returned to a client; larger screenshots are downscaled.
pub const MAX_PNG_SIDE: u32 = 2048;
/// Largest render edge for local CLI renders.
pub const MAX_LOCAL_RENDER_SIDE: u32 = 4096;
/// Largest reply line read from the app (full-window screenshots are big).
pub const MAX_BRIDGE_REPLY_BYTES: usize = 64 << 20;
/// Serialize compactly, refusing replies over [`MAX_RESPONSE_BYTES`].
pub fn json_text(v: &impl Serialize) -> Result<String, AutomationError> {
let s = serde_json::to_string(v).map_err(|e| AutomationError::Other(format!("cannot encode the reply: {e}")))?;
if s.len() > MAX_RESPONSE_BYTES {
return Err(bad(format!("reply is {} bytes, over the {MAX_RESPONSE_BYTES}-byte limit; the operation may have completed", s.len())));
}
Ok(s)
}
pub fn check_png(bytes: usize) -> Result<(), AutomationError> {
if bytes > MAX_PNG_BYTES {
return Err(bad(format!("PNG is {bytes} bytes, over the {MAX_PNG_BYTES}-byte limit; render smaller")));
}
Ok(())
}
pub fn encode_png(w: u32, h: u32, rgba: Vec<u8>) -> Result<Vec<u8>, AutomationError> {
let img = image::RgbaImage::from_raw(w, h, rgba).ok_or_else(|| AutomationError::Other("render buffer has the wrong size".into()))?;
let mut png = Vec::new();
img.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png).map_err(|e| AutomationError::Other(format!("PNG encoding failed: {e}")))?;
Ok(png)
}
/// Downscale a PNG (an app screenshot) so its longest edge is at most `max_side`, then check its
/// byte size. Decoding is capped: a small compressed reply can still claim a huge image.
pub fn fit_png(png: Vec<u8>, max_side: u32) -> Result<Vec<u8>, AutomationError> {
let mut reader = image::ImageReader::with_format(std::io::Cursor::new(&png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(16_384);
limits.max_image_height = Some(16_384);
limits.max_alloc = Some(1 << 30);
reader.limits(limits);
let img = reader.decode().map_err(|e| AutomationError::Other(format!("screenshot is not a valid PNG: {e}")))?;
let out = if img.width().max(img.height()) > max_side {
let small = img.thumbnail(max_side, max_side).into_rgba8();
encode_png(small.width(), small.height(), small.into_raw())?
} else {
png
};
check_png(out.len())?;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn fit_png_downscales_and_rejects_garbage() {
let big = encode_png(3000, 10, vec![200; 3000 * 10 * 4]).unwrap();
let small = fit_png(big, MAX_PNG_SIDE).unwrap();
let img = image::load_from_memory(&small).unwrap();
assert_eq!(img.width(), MAX_PNG_SIDE);
assert!(fit_png(b"not a png".to_vec(), 64).is_err());
assert!(json_text(&"x".repeat(MAX_RESPONSE_BYTES)).is_err());
assert!(check_png(MAX_PNG_BYTES + 1).is_err());
}
}
+306
View File
@@ -0,0 +1,306 @@
//! The headless backend: a [`Session`] plus file I/O and windowless renders. Synchronous and
//! UI-free; the MCP server, the RPC server and the CLI all drive it.
use std::path::Path;
use serde_json::{Value, json};
use texturecraft_engine::core::PROJECT_EXT;
use texturecraft_engine::geom::primitives;
use texturecraft_engine::{Session, commands, file_cmds, inspect};
use texturecraft_render::ViewKind;
use crate::budgets::{MAX_LOCAL_RENDER_SIDE, MAX_PNG_SIDE, check_png, encode_png};
use crate::render::Gpu;
use crate::workspace::{MAX_READ_BYTES, authorize_command};
use crate::{AuthorizedWorkspace, AutomationError, bad};
/// Where file paths given to [`Headless`] may point.
pub enum Filesystem {
/// No file access (an MCP server started without roots).
Denied,
/// Host paths as given: the local CLI user typed them.
TrustedLocal,
/// Relative paths under the authorized roots (remote or agent callers).
Workspace(AuthorizedWorkspace),
}
/// What [`Headless::render_png`] draws.
#[derive(Clone, Debug, Default)]
pub struct RenderOptions {
/// `3d` (default) or `2d`/`uv` (the UV view of the active texture set).
pub view: Option<String>,
/// Pixels; default the session viewport (the space `tool.stroke` points live in).
pub width: Option<u32>,
pub height: Option<u32>,
/// Camera overrides in degrees (the session camera is not changed).
pub yaw: Option<f32>,
pub pitch: Option<f32>,
/// Path trace with this many samples per pixel (Rendering mode) instead of the GPU view.
pub samples: Option<u32>,
/// Light bounces for path tracing (default 6).
pub bounces: Option<u32>,
}
/// Most samples per pixel a path-traced render may take.
pub const MAX_TRACE_SAMPLES: u32 = 4096;
pub struct Headless {
pub session: Session,
fs: Filesystem,
/// Created on the first render; `Err` once no adapter was found.
gpu: Option<Result<Gpu, String>>,
}
fn ext_of(path: &str) -> String {
Path::new(path).extension().and_then(|e| e.to_str()).unwrap_or_default().to_ascii_lowercase()
}
fn join(dir: &str, name: &str) -> String {
if dir == "." { name.to_string() } else { format!("{}/{name}", dir.trim_end_matches('/')) }
}
impl Headless {
pub fn new(session: Session, fs: Filesystem) -> Headless {
Headless { session, fs, gpu: None }
}
/// The session a fresh server starts with: the material ball at 1024.
pub fn default_session() -> Result<Session, AutomationError> {
Ok(Session::new_project("Untitled", primitives::material_ball(), "builtin:material_ball", None, 1024)?)
}
fn trusted(&self) -> bool {
matches!(self.fs, Filesystem::TrustedLocal)
}
fn read(&self, path: &str) -> Result<Vec<u8>, AutomationError> {
match &self.fs {
Filesystem::Denied => Err(bad("file access is not granted: start the server with --read-root <dir>")),
Filesystem::TrustedLocal => {
let len = std::fs::metadata(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))?.len();
if len > MAX_READ_BYTES {
return Err(bad(format!("{path} is {len} bytes (limit {MAX_READ_BYTES})")));
}
std::fs::read(path).map_err(|e| AutomationError::Io(format!("cannot read {path}: {e}")))
}
Filesystem::Workspace(w) => w.read(path),
}
}
fn write(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> {
match &self.fs {
Filesystem::Denied => Err(bad("file access is not granted: start the server with --write-root <dir>")),
Filesystem::TrustedLocal => {
// Atomic: a crash or full disk never leaves a half-written project.
let tmp = format!("{path}.tmp");
let res = std::fs::write(&tmp, bytes).and_then(|()| std::fs::rename(&tmp, path));
if res.is_err() {
let _ = std::fs::remove_file(&tmp);
}
res.map_err(|e| AutomationError::Io(format!("cannot write {path}: {e}")))
}
Filesystem::Workspace(w) => w.write(path, bytes),
}
}
fn create_dir_all(&self, dir: &str) -> Result<(), AutomationError> {
match &self.fs {
_ if dir == "." => Ok(()),
Filesystem::Denied => Err(bad("file access is not granted: start the server with --write-root <dir>")),
Filesystem::TrustedLocal => std::fs::create_dir_all(dir).map_err(|e| AutomationError::Io(format!("cannot create {dir}: {e}"))),
Filesystem::Workspace(w) => w.create_dir_all(dir),
}
}
/// Replace the session, keeping the viewport size scripted strokes use.
fn replace(&mut self, mut next: Session) -> Value {
next.viewport = self.session.viewport;
self.session = next;
self.inspect()
}
pub fn inspect(&self) -> Value {
inspect::session(&self.session)
}
pub fn command_list(&self, filter: Option<&str>) -> Value {
commands::list(&self.session, filter)
}
/// Run an engine command. Untrusted callers can't reach host paths through it.
pub fn command_run(&mut self, id: &str, params: Value) -> Result<Value, AutomationError> {
if !self.trusted() {
authorize_command(id, &params)?;
}
Ok(texturecraft_engine::execute(&mut self.session, id, &params)?)
}
/// Run `[{id, params?}]` in order, stopping at the first error (reported with its index).
pub fn batch(&mut self, steps: &[Value]) -> Value {
let mut results = Vec::new();
for (i, step) in steps.iter().enumerate() {
let id = step.get("id").and_then(Value::as_str).unwrap_or_default();
match self.command_run(id, step.get("params").cloned().unwrap_or(Value::Null)) {
Ok(v) => results.push(v),
Err(e) => return batch_reply(results, Some((i, id, e.to_string()))),
}
}
batch_reply(results, None)
}
/// Open a `.tcraft` project or a mesh file (a new project at 2048).
pub fn open(&mut self, path: &str) -> Result<Value, AutomationError> {
if ext_of(path) != PROJECT_EXT {
return self.import_mesh(path, None, None);
}
let mut next = Session::from_project_bytes(&self.read(path)?)?;
next.path = Some(path.to_string());
next.modified = false;
Ok(self.replace(next))
}
/// A new project from a mesh file: one texture set per material.
pub fn import_mesh(&mut self, path: &str, resolution: Option<u32>, name: Option<&str>) -> Result<Value, AutomationError> {
let bytes = self.read(path)?;
let stem = Path::new(path).file_stem().and_then(|s| s.to_str()).unwrap_or("Untitled");
let next = Session::from_mesh_bytes(path, &bytes, resolution.unwrap_or(2048), name.unwrap_or(stem))?;
Ok(self.replace(next))
}
/// Import an image file as a project resource (for `layer.add.image`, `tool.stencil`).
pub fn import_resource(&mut self, path: &str) -> Result<Value, AutomationError> {
let bytes = self.read(path)?;
Ok(json!({ "name": self.session.import_resource_bytes(path, bytes)? }))
}
/// Save a layer (default: the selected one) as a smart material file (`.tcmat`).
pub fn material_save(&mut self, p: &Value) -> Result<Value, AutomationError> {
let path = p.get("path").and_then(Value::as_str).ok_or_else(|| bad("`path` is required"))?;
let s = &self.session;
let id = match p.get("layer").and_then(Value::as_u64) {
Some(i) => texturecraft_engine::core::LayerId(i),
None => s.selected_layer().ok_or_else(|| bad("no layer selected and no `layer` given"))?,
};
let name = match p.get("name").and_then(Value::as_str) {
Some(n) => n.to_string(),
None => s.doc.project.layer(id).map(|l| l.name.clone()).map_err(|_| bad(format!("no layer {}", id.0)))?,
};
let bytes = s.smart_material_bytes(id, &name)?;
let ext = texturecraft_engine::material_lib::SMART_MATERIAL_EXT;
let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") };
self.write(&path, &bytes)?;
Ok(json!({ "path": path }))
}
/// Add a smart material from a `.tcmat` file above the selection.
pub fn material_load(&mut self, path: &str) -> Result<Value, AutomationError> {
let bytes = self.read(path)?;
Ok(json!({ "layer": self.session.add_smart_material_bytes(&bytes)?.0 }))
}
/// Save as `.tcraft` to `path`, or to the project's own file.
pub fn save(&mut self, path: Option<&str>) -> Result<Value, AutomationError> {
let target = match path.or(self.session.path.as_deref()) {
Some(p) if ext_of(p) == PROJECT_EXT => p.to_string(),
Some(p) => format!("{p}.{PROJECT_EXT}"),
None => return Err(bad("the project has no file yet: give `path`")),
};
self.write(&target, &self.session.to_project_bytes()?)?;
self.session.path = Some(target.clone());
self.session.modified = false;
Ok(json!({ "path": target }))
}
/// Export textures to `dir` (`file.exportTextures` params: preset, ts, format, padding, size…).
pub fn export(&mut self, p: &Value) -> Result<Value, AutomationError> {
let dir = p.get("dir").and_then(Value::as_str).filter(|d| !d.is_empty()).ok_or_else(|| bad("`dir` is required"))?;
let opts = file_cmds::export_options(p, "textures.export")?;
let n = self.session.set_count();
let sets: Vec<usize> = match p.get("ts") {
None | Some(Value::Null) => (0..n).collect(),
Some(Value::String(a)) if a == "all" => (0..n).collect(),
Some(v) => vec![v.as_u64().and_then(|t| usize::try_from(t).ok()).filter(|t| *t < n).ok_or_else(|| bad(format!("invalid `ts` {v}")))?],
};
let files = self.session.export_files(&sets, &opts)?;
self.create_dir_all(dir)?;
let mut written = Vec::new();
for f in &files {
let path = join(dir, &f.name);
self.write(&path, &f.bytes)?;
written.push(path);
}
let warnings: Vec<&String> = files.iter().flat_map(|f| &f.warnings).collect();
Ok(json!({ "files": written, "warnings": warnings }))
}
/// Render the session to PNG: `(width, height, png)`. Errors without a GPU adapter.
pub fn render_png(&mut self, o: &RenderOptions) -> Result<(u32, u32, Vec<u8>), AutomationError> {
let s = &self.session;
let kind = match o.view.as_deref().unwrap_or("3d") {
"3d" => ViewKind::Scene,
"2d" | "uv" => ViewKind::Uv { ts: s.ts(), zoom: 1.0, pan: [0.0, 0.0] },
other => return Err(bad(format!("unknown view `{other}` (3d, 2d or uv)"))),
};
let max = if self.trusted() { MAX_LOCAL_RENDER_SIDE } else { MAX_PNG_SIDE };
let side = |v: Option<u32>, d: f32| {
let v = v.unwrap_or(d.round() as u32);
if (16..=max).contains(&v) { Ok(v) } else { Err(bad(format!("render size {v} must be 16 to {max} pixels"))) }
};
let size = [side(o.width, s.viewport.x)?, side(o.height, s.viewport.y)?];
let mut camera = s.camera;
for (v, slot, lim) in [(o.yaw, &mut camera.yaw, 1e6), (o.pitch, &mut camera.pitch, 89.0)] {
if let Some(v) = v {
if !v.is_finite() {
return Err(bad("camera angles must be finite"));
}
*slot = v.clamp(-lim, lim).to_radians();
}
}
if let Some(samples) = o.samples {
if !(1..=MAX_TRACE_SAMPLES).contains(&samples) || o.view.as_deref().is_some_and(|v| v != "3d") {
return Err(bad(format!("path tracing renders the 3D view with 1 to {MAX_TRACE_SAMPLES} samples")));
}
let settings = texturecraft_render::trace::TraceSettings { bounces: o.bounces.unwrap_or(6).clamp(1, 32) };
let (w, h, rgba) = crate::render::path_trace(&mut self.session, size, camera, samples, &settings);
let png = encode_png(w, h, rgba)?;
if !self.trusted() {
check_png(png.len())?;
}
return Ok((w, h, png));
}
let gpu = match self.gpu.get_or_insert_with(Gpu::new) {
Ok(g) => g,
Err(e) => return Err(AutomationError::Other(format!("cannot render: {e}"))),
};
// Last-resort guard: wgpu panics on device errors; drop the device and report instead.
let session = &mut self.session;
let out = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| gpu.render(session, kind, size, camera)));
let (w, h, rgba) = match out {
Ok(Some(px)) => px,
Ok(None) => return Err(AutomationError::Other("the GPU returned no image".into())),
Err(_) => {
self.gpu = None;
return Err(AutomationError::Other("the GPU renderer failed".into()));
}
};
let png = encode_png(w, h, rgba)?;
if !self.trusted() {
check_png(png.len())?;
}
Ok((w, h, png))
}
/// The GPU adapter used for renders, if one was created.
pub fn adapter(&self) -> Option<&str> {
self.gpu.as_ref().and_then(|g| g.as_ref().ok()).map(Gpu::adapter)
}
}
/// `{completed, results, failed: {index, id, error} | null}` for `command_batch`.
pub fn batch_reply(results: Vec<Value>, failed: Option<(usize, &str, String)>) -> Value {
json!({
"completed": results.len(),
"results": results,
"failed": failed.map(|(index, id, error)| json!({ "index": index, "id": id, "error": error })),
})
}
+49
View File
@@ -0,0 +1,49 @@
//! # texturecraft-automation
//!
//! Agent-facing automation, L4 (no UI toolkit):
//!
//! * [`TexturecraftMcp`]: an MCP server (official `rmcp` SDK). Headless mode drives an in-process
//! [`Headless`] session; bridge mode forwards to a running desktop app over the JSON-lines
//! control channel (`docs/control-protocol.md`).
//! * [`Headless`]: a [`texturecraft_engine::Session`] plus file I/O through an
//! [`AuthorizedWorkspace`] and windowless GPU renders. Shared by the MCP server, the RPC server
//! and `texturecraft-cli`.
//! * [`rpc`]: the control channel's methods (plus `render`) over stdio or loopback TCP, used by
//! `texturecraft-cli serve`.
//! * [`BridgeClient`]: the client side of the app's control channel.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod bridge;
pub mod budgets;
pub mod headless;
pub mod render;
pub mod rpc;
pub mod security;
pub mod server;
pub mod workspace;
pub use bridge::BridgeClient;
pub use headless::{Filesystem, Headless, RenderOptions};
pub use server::{Backend, TexturecraftMcp};
pub use workspace::AuthorizedWorkspace;
#[derive(Debug, thiserror::Error)]
pub enum AutomationError {
#[error("{0}")]
BadRequest(String),
#[error("I/O: {0}")]
Io(String),
#[error(transparent)]
Engine(#[from] texturecraft_engine::EngineError),
#[error("bridge: {0}")]
Bridge(String),
#[error("app: {0}")]
App(String),
#[error("{0}")]
Other(String),
}
pub(crate) fn bad(msg: impl Into<String>) -> AutomationError {
AutomationError::BadRequest(msg.into())
}
+168
View File
@@ -0,0 +1,168 @@
//! Windowless renders of a session: the desktop app's per-frame GPU sync (`ui-egui/src/gpu.rs`)
//! and viewport shading (`ui-egui/src/viewport.rs`), done in one shot.
use rayon::prelude::*;
use texturecraft_engine::compose::{DisplayKind, all_tiles, tile_bytes};
use texturecraft_engine::{Session, ViewMode};
use texturecraft_render::trace::{TraceDisplay, TraceScene, TraceSet, TraceSettings, Tracer};
use texturecraft_render::{Frame, Shade, ViewKind};
/// A headless GPU device that remembers what it already holds of the session.
pub struct Gpu {
h: texturecraft_render::headless::Headless,
mesh_id: u64,
sets: Vec<(u32, usize)>,
env: String,
}
impl Gpu {
/// Errors when there is no GPU (or software) adapter.
pub fn new() -> Result<Gpu, String> {
Ok(Gpu { h: texturecraft_render::headless::Headless::new()?, mesh_id: 0, sets: Vec::new(), env: String::new() })
}
pub fn adapter(&self) -> &str {
&self.h.adapter_name
}
/// Bring the GPU up to date with `s` (mesh, texture sets, environment, dirty tiles).
fn sync(&mut self, s: &mut Session) {
s.update();
let h = &mut self.h;
let mut reupload = false;
if self.mesh_id != s.mesh_id {
h.renderer.set_mesh(&h.device, &h.queue, &s.mesh, s.mesh_id);
self.mesh_id = s.mesh_id;
self.sets.clear();
reupload = true;
}
let sets: Vec<(u32, usize)> = s.doc.project.texture_sets.iter().map(|t| (t.resolution, t.material)).collect();
if sets != self.sets {
h.renderer.set_texture_sets(&h.device, &h.queue, &sets, s.mesh.materials.len().max(1));
self.sets = sets;
reupload = true;
}
let d = &s.doc.project.display;
if d.environment != self.env {
let image = d.environment_resource().and_then(|n| s.images.get(n));
h.renderer.set_environment(&h.device, &h.queue, &d.environment, image.map(|i| i.as_ref()));
self.env.clone_from(&d.environment);
}
for ts in 0..s.caches.len() {
let mut tiles = s.take_uploads(ts);
let Some(cache) = s.caches.get(ts) else { continue };
if reupload {
tiles = all_tiles(cache.resolution);
}
let empty = Default::default();
let baked = s.doc.baked.get(&ts).unwrap_or(&empty);
let comp = &cache.composite;
let bytes: Vec<_> = tiles
.par_iter()
.flat_map_iter(|&(tx, ty)| DisplayKind::ALL.into_iter().map(move |k| (k, tx, ty)))
.map(|(k, tx, ty)| (k, tx, ty, tile_bytes(comp, baked, k, tx, ty)))
.collect();
for (k, tx, ty, b) in bytes {
h.renderer.upload_tile(&h.queue, ts, k, tx, ty, &b);
}
// The aux texture behind the mesh-map and mask views (rebuilt every render).
let res = cache.resolution.min(2048);
let aux = match s.view {
ViewMode::MeshMap(m) => Some(texturecraft_render::mesh_maps::mesh_map_rgba(s.doc.baked.get(&ts), m, res)),
ViewMode::Mask(id) if s.doc.project.locate(id).is_some_and(|(t, _, _)| t == ts) => s.mask_view_rgba(id, res),
_ => None,
};
if let Some(rgba) = aux {
h.renderer.upload_aux(&h.queue, ts, res, &rgba);
}
}
}
/// Render `s` with `kind` at `size` through `camera`; RGBA8 (sRGB) pixels.
pub fn render(&mut self, s: &mut Session, kind: ViewKind, size: [u32; 2], camera: texturecraft_engine::geom::OrbitCamera) -> Option<(u32, u32, Vec<u8>)> {
self.sync(s);
let frame = Frame { view_id: 1, size, kind, camera, shade: shade(s), visible: s.doc.project.texture_sets.iter().map(|t| t.visible).collect() };
self.h.render(&frame)
}
}
/// A progressive CPU path trace of the session's 3D view (the app's Rendering mode), finished
/// after `samples` passes and denoised; RGBA8 (sRGB) pixels.
pub fn path_trace(s: &mut Session, size: [u32; 2], camera: texturecraft_engine::geom::OrbitCamera, samples: u32, settings: &TraceSettings) -> (u32, u32, Vec<u8>) {
s.update();
let sets = s
.doc
.project
.texture_sets
.iter()
.zip(&s.caches)
.map(|(ts, c)| TraceSet { material: ts.material, composite: c.composite.clone(), height_strength: ts.height_strength })
.collect();
let d = &s.doc.project.display;
let env_image = d.environment_resource().and_then(|n| s.images.get(n));
let scene = TraceScene::for_display(s.mesh.clone(), s.bvh.clone(), sets, d, env_image.map(|i| i.as_ref()));
let mut tracer = Tracer::new(size[0], size[1]);
for _ in 0..samples {
tracer.pass(&scene, &camera, settings);
}
(tracer.width, tracer.height, tracer.rgba8(&TraceDisplay { denoise: true, ..TraceDisplay::from_display(d) }))
}
/// How the viewport shades the session (the app's `viewport::shade`).
pub fn shade(s: &Session) -> Shade {
let (view_mode, channel) = match s.view {
ViewMode::Material => (0, 0),
ViewMode::Channel(c) => (1, c.index() as u32),
ViewMode::MeshMap(_) | ViewMode::Mask(_) => (2, 0),
ViewMode::UvChecker => (3, 0),
};
Shade {
height_strength: s.doc.project.texture_sets.get(s.ts()).map(|t| t.height_strength).unwrap_or(1.0),
view_mode,
channel,
// The app's default (only the 2D view draws it).
wireframe: true,
..Shade::from_display(&s.doc.project.display)
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use texturecraft_engine::execute;
/// A 64×32 Radiance `.hdr` (flat RGBE scanlines): a hot orange sky over a dim blue ground.
fn sky_hdr() -> Vec<u8> {
let rgbe = |c: [f32; 3]| {
let e = c.iter().copied().fold(0.0f32, f32::max).log2().floor() as i32 + 1;
let k = 256.0 / 2f32.powi(e);
[(c[0] * k) as u8, (c[1] * k) as u8, (c[2] * k) as u8, (e + 128) as u8]
};
let mut out = b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\n\n-Y 32 +X 64\n".to_vec();
for y in 0..32 {
let px = rgbe(if y < 16 { [12.0, 4.0, 1.0] } else { [0.02, 0.05, 0.2] });
out.extend((0..64).flat_map(|_| px));
}
out
}
#[test]
fn renders_with_an_imported_hdr_environment() {
let mesh = texturecraft_engine::geom::primitives::material_ball();
let mut s = Session::new_project("t", mesh, "builtin:material_ball", None, 256).unwrap();
let name = s.import_resource_bytes("sky.hdr", sky_hdr()).unwrap();
assert!(s.images[&name].rgba[0][0] > 10.0, "the decoder keeps HDR values");
let Ok(mut gpu) = Gpu::new() else {
eprintln!("skipping: no GPU adapter");
return;
};
let cam = s.camera;
let (_, _, base) = gpu.render(&mut s, ViewKind::Scene, [160, 120], cam).unwrap();
execute(&mut s, "display.set", &json!({"environment": format!("resource:{name}"), "specGloss": true, "parallax": true})).unwrap();
let (_, _, lit) = gpu.render(&mut s, ViewKind::Scene, [160, 120], cam).unwrap();
assert_ne!(base, lit, "the HDR environment changes the render");
let warm = |px: &[u8]| px.chunks(4).map(|p| p[0] as f32 - p[2] as f32).sum::<f32>();
assert!(warm(&lit) > warm(&base), "the orange sky warms the image");
}
}
+273
View File
@@ -0,0 +1,273 @@
//! Headless JSON-lines server with the app's control-channel envelope:
//! `{"id","method","params"}` → `{"id","ok":true,"result"}` | `{"id","ok":false,"error"}`.
//! `texturecraft-cli serve` runs it on stdio or on a loopback TCP port (first request `auth`).
//!
//! Methods: the app's `ping`, `command.run {id, params?}`, `command.list {filter?}`,
//! `session.inspect`, plus `command.batch {steps}`, `project.open {path}`,
//! `project.save {path?}`, `mesh.import {path, resolution?, name?}`, `resource.import {path}`,
//! `material.save {path, layer?, name?}`, `material.load {path}` (workspace-scoped versions of
//! the engine commands),
//! `textures.export {dir, …}`, `render {view?, width?, height?, yaw?, pitch?}` (PNG base64, the
//! shape of the app's `viewport.screenshot`) and `methods`.
use std::io::{BufRead, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex, PoisonError};
use base64::Engine as _;
use serde_json::{Value, json};
use crate::budgets::json_text;
use crate::headless::RenderOptions;
use crate::security::{ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, read_bounded_line, token_matches};
use crate::{AutomationError, Headless, bad};
pub const METHODS: &[&str] = &[
"ping",
"methods",
"session.inspect",
"command.list",
"command.run",
"command.batch",
"project.open",
"project.save",
"mesh.import",
"resource.import",
"material.save",
"material.load",
"textures.export",
"render",
];
fn str_of<'a>(p: &'a Value, k: &str) -> Option<&'a str> {
p.get(k).and_then(Value::as_str)
}
fn u32_of(p: &Value, k: &str) -> Result<Option<u32>, AutomationError> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_u64().and_then(|v| u32::try_from(v).ok()).map(Some).ok_or_else(|| bad(format!("`{k}` must be a whole number"))),
}
}
fn f32_of(p: &Value, k: &str) -> Result<Option<f32>, AutomationError> {
match p.get(k) {
None | Some(Value::Null) => Ok(None),
Some(v) => v.as_f64().map(|v| Some(v as f32)).ok_or_else(|| bad(format!("`{k}` must be a number"))),
}
}
fn required<'a>(p: &'a Value, k: &str) -> Result<&'a str, AutomationError> {
str_of(p, k).ok_or_else(|| bad(format!("`{k}` is required")))
}
impl Headless {
/// Dispatch one request. Unknown methods and bad params are errors, never panics.
pub fn handle(&mut self, method: &str, p: &Value) -> Result<Value, AutomationError> {
match method {
"ping" => Ok(json!("pong")),
"methods" => Ok(json!(METHODS)),
"session.inspect" => Ok(self.inspect()),
"command.list" => Ok(self.command_list(str_of(p, "filter"))),
"command.run" => self.command_run(required(p, "id")?, p.get("params").cloned().unwrap_or(Value::Null)),
"command.batch" => {
let steps = p.get("steps").and_then(Value::as_array).ok_or_else(|| bad("`steps` must be an array of {id, params}"))?;
if steps.len() > MAX_BATCH_STEPS {
return Err(bad(format!("at most {MAX_BATCH_STEPS} steps per batch")));
}
Ok(self.batch(steps))
}
"project.open" => self.open(required(p, "path")?),
"project.save" => self.save(str_of(p, "path")),
"mesh.import" => self.import_mesh(required(p, "path")?, u32_of(p, "resolution")?, str_of(p, "name")),
"resource.import" => self.import_resource(required(p, "path")?),
"material.save" => self.material_save(p),
"material.load" => self.material_load(required(p, "path")?),
"textures.export" => self.export(p),
"render" => {
let o = RenderOptions {
view: str_of(p, "view").map(str::to_string),
width: u32_of(p, "width")?,
height: u32_of(p, "height")?,
yaw: f32_of(p, "yaw")?,
pitch: f32_of(p, "pitch")?,
samples: u32_of(p, "samples")?,
bounces: u32_of(p, "bounces")?,
};
let (w, h, png) = self.render_png(&o)?;
Ok(json!({ "width": w, "height": h, "png": base64::engine::general_purpose::STANDARD.encode(png) }))
}
m if m.starts_with("ui.") || m == "viewport.screenshot" => {
Err(bad(format!("`{m}` needs the running app (texturecraft --control <port>); headless renders use `render`")))
}
other => Err(bad(format!("unknown method `{other}` (see `methods`)"))),
}
}
}
/// Answer one request line. A panic inside a command becomes an error reply (edits run on a
/// snapshot, so the session stays consistent).
pub fn respond(h: &Mutex<Headless>, line: &str) -> Value {
let req: Value = match serde_json::from_str(line) {
Ok(v) => v,
Err(e) => return json!({"id": null, "ok": false, "error": format!("bad JSON: {e}")}),
};
let id = req.get("id").cloned().unwrap_or(Value::Null);
let Some(method) = req.get("method").and_then(Value::as_str) else {
return json!({"id": id, "ok": false, "error": "`method` is required"});
};
let params = req.get("params").cloned().unwrap_or(Value::Null);
let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| h.lock().unwrap_or_else(PoisonError::into_inner).handle(method, &params)))
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))));
match r {
Ok(v) => json!({"id": id, "ok": true, "result": v}),
Err(e) => json!({"id": id, "ok": false, "error": e.to_string()}),
}
}
/// Write one reply line; an oversized reply becomes an error with the same id.
fn write_reply(w: &mut impl Write, reply: &Value) -> std::io::Result<()> {
let text = json_text(reply).unwrap_or_else(|e| json!({"id": reply.get("id"), "ok": false, "error": e.to_string()}).to_string());
writeln!(w, "{text}")?;
w.flush()
}
/// Serve JSON lines from `r` to `w` until EOF (stdio mode: no authentication).
pub fn serve_lines(h: &Mutex<Headless>, mut r: impl BufRead, mut w: impl Write) -> std::io::Result<()> {
let mut line = String::new();
loop {
let reply = match read_bounded_line(&mut r, &mut line) {
Ok(LineRead::Eof) => return Ok(()),
Ok(LineRead::TooLong) => json!({"id": null, "ok": false, "error": format!("request exceeds {MAX_REQUEST_BYTES} bytes")}),
Err(e) if e.kind() == std::io::ErrorKind::InvalidData => json!({"id": null, "ok": false, "error": "request is not UTF-8"}),
Err(e) => return Err(e),
Ok(LineRead::Line) if line.trim().is_empty() => continue,
Ok(LineRead::Line) => respond(h, &line),
};
write_reply(&mut w, &reply)?;
}
}
/// One TCP connection: the first request must be `auth {token}`, as on the app's channel.
fn serve_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &str) -> std::io::Result<()> {
stream.set_read_timeout(Some(std::time::Duration::from_secs(600)))?;
let mut r = std::io::BufReader::new(stream.try_clone()?);
let mut w = stream;
let mut line = String::new();
let mut authed = false;
loop {
match read_bounded_line(&mut r, &mut line)? {
LineRead::Eof => return Ok(()),
LineRead::TooLong => return write_reply(&mut w, &json!({"id": null, "ok": false, "error": "request too large"})),
LineRead::Line if line.trim().is_empty() => continue,
LineRead::Line => {}
}
if authed {
write_reply(&mut w, &respond(h, &line))?;
continue;
}
let req: Value = serde_json::from_str(&line).unwrap_or(Value::Null);
let supplied = req.get("params").and_then(|p| p.get("token")).and_then(Value::as_str).unwrap_or_default();
authed = req.get("method").and_then(Value::as_str) == Some("auth") && token_matches(token, supplied);
let id = req.get("id").cloned().unwrap_or(Value::Null);
if !authed {
return write_reply(&mut w, &json!({"id": id, "ok": false, "error": "authenticate first: {\"method\":\"auth\",\"params\":{\"token\":…}}"}));
}
write_reply(&mut w, &json!({"id": id, "ok": true}))?;
}
}
/// Serve authenticated JSON lines on `127.0.0.1:port` (0 picks a port) with one shared
/// session. `ready` gets the bound address.
pub fn serve_tcp(port: u16, h: Arc<Mutex<Headless>>, token: String, ready: impl FnOnce(std::net::SocketAddr)) -> Result<(), AutomationError> {
let listener = TcpListener::bind(("127.0.0.1", port)).map_err(|e| AutomationError::Io(format!("cannot listen on 127.0.0.1:{port}: {e}")))?;
ready(listener.local_addr().map_err(|e| AutomationError::Io(e.to_string()))?);
let limiter = ConnectionLimiter::default();
let token = Arc::new(token);
for stream in listener.incoming() {
let Ok(mut stream) = stream else { continue };
let Some(permit) = limiter.try_acquire(MAX_CONNECTIONS) else {
let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "too many connections"}));
continue;
};
let (h, token) = (h.clone(), token.clone());
std::thread::spawn(move || {
let _permit = permit;
let _ = serve_connection(&h, stream, &token);
});
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::headless::Filesystem;
fn session() -> Mutex<Headless> {
let s = texturecraft_engine::Session::new_project("t", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
Mutex::new(Headless::new(s, Filesystem::Denied))
}
#[test]
fn lines_round_trip_and_errors() {
let h = session();
let input = concat!(
r#"{"id":1,"method":"command.run","params":{"id":"layer.add.fill","params":{"color":[1,0,0]}}}"#,
"\n\n",
r#"{"id":2,"method":"session.inspect"}"#,
"\n",
r#"{"id":3,"method":"nope"}"#,
"\n",
"not json\n",
r#"{"id":4,"method":"command.run","params":{"id":"file.open","params":{"path":"/etc/passwd"}}}"#,
"\n",
r#"{"id":5,"method":"project.open","params":{"path":"x.tcraft"}}"#,
"\n",
r#"{"id":6,"method":"command.batch","params":{"steps":[{"id":"layer.add.paint"},{"id":"nope"},{"id":"layer.add.paint"}]}}"#,
"\n",
);
let mut out = Vec::new();
serve_lines(&h, input.as_bytes(), &mut out).unwrap();
let r: Vec<Value> = String::from_utf8(out).unwrap().lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(r.len(), 7);
assert_eq!(r[0]["ok"], true);
assert_eq!(r[1]["result"]["layers"][0]["kind"], "fill");
assert_eq!(r[2]["ok"], false);
assert_eq!(r[3]["id"], Value::Null);
assert!(r[4]["error"].as_str().unwrap().contains("disabled for automation"), "{}", r[4]);
assert!(r[5]["error"].as_str().unwrap().contains("not granted"), "{}", r[5]);
assert_eq!(r[6]["result"]["completed"], 1);
assert_eq!(r[6]["result"]["failed"]["index"], 1);
}
#[test]
fn tcp_requires_the_token() {
use std::io::{BufRead, BufReader};
let h = Arc::new(session());
let (tx, rx) = std::sync::mpsc::channel();
let token = "0123456789abcdef0123".to_string();
std::thread::spawn(move || serve_tcp(0, h, token, |a| tx.send(a).unwrap()));
let addr = rx.recv().unwrap();
let talk = |lines: &[&str]| {
let s = std::net::TcpStream::connect(addr).unwrap();
let mut w = s.try_clone().unwrap();
let mut r = BufReader::new(s);
lines
.iter()
.map(|l| {
writeln!(w, "{l}").unwrap();
let mut reply = String::new();
r.read_line(&mut reply).unwrap();
serde_json::from_str::<Value>(&reply).unwrap()
})
.collect::<Vec<_>>()
};
let denied = talk(&[r#"{"id":1,"method":"session.inspect"}"#]);
assert_eq!(denied[0]["ok"], false);
let ok = talk(&[r#"{"id":1,"method":"auth","params":{"token":"0123456789abcdef0123"}}"#, r#"{"id":2,"method":"ping"}"#]);
assert_eq!(ok[0]["ok"], true);
assert_eq!(ok[1]["result"], "pong");
assert_eq!(ok[1]["id"], 2);
}
}
+171
View File
@@ -0,0 +1,171 @@
//! Tokens and bounded framing for the loopback JSON-lines transports (the app's control channel
//! and `texturecraft-cli serve` share the token conventions).
use std::io::BufRead;
use std::path::PathBuf;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use crate::{AutomationError, bad};
/// Environment variable holding the control token (both sides).
pub const TOKEN_ENV: &str = "TEXTURECRAFT_CONTROL_TOKEN";
/// Largest JSON request line, newline included (the app's limit too).
pub const MAX_REQUEST_BYTES: usize = 8 << 20;
/// Simultaneous TCP connections served by `serve --port`.
pub const MAX_CONNECTIONS: usize = 16;
/// Steps in one `command_batch`.
pub const MAX_BATCH_STEPS: usize = 256;
/// The token file the app (and `serve --port`) writes when the environment gives no token.
pub fn token_file(port: u16) -> PathBuf {
std::env::temp_dir().join(format!("texturecraft-control-{port}.token"))
}
/// The app accepts any environment token of at least 16 characters; generated ones are 64 hex.
fn validate_token(t: &str) -> Result<(), AutomationError> {
if (16..=1024).contains(&t.len()) && t.bytes().all(|b| b.is_ascii_graphic()) {
Ok(())
} else {
Err(bad("control token must be 16 to 1024 printable ASCII characters"))
}
}
/// A fresh 256-bit token as 64 hex digits, from the OS random generator.
pub fn generate_token() -> Result<String, AutomationError> {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).map_err(|e| AutomationError::Other(format!("cannot generate a control token: {e}")))?;
Ok(bytes.iter().map(|b| format!("{b:02x}")).collect())
}
/// Token for a client of `port`: explicit, else `TEXTURECRAFT_CONTROL_TOKEN`, else the token file.
pub fn client_token(port: u16, supplied: Option<String>) -> Result<String, AutomationError> {
let token = match supplied.or_else(|| std::env::var(TOKEN_ENV).ok()) {
Some(t) => t,
None => {
let path = token_file(port);
std::fs::read_to_string(&path)
.map_err(|e| bad(format!("no control token: set {TOKEN_ENV} or start the app with `--control {port}` so it writes {} ({e})", path.display())))?
}
};
let token = token.trim().to_string();
validate_token(&token)?;
Ok(token)
}
/// Token for a server on `port`: `TEXTURECRAFT_CONTROL_TOKEN`, else a fresh one written to
/// [`token_file`] (owner-only on Unix). Returns the token and where it was written.
pub fn server_token(port: u16) -> Result<(String, Option<PathBuf>), AutomationError> {
if let Ok(t) = std::env::var(TOKEN_ENV) {
validate_token(t.trim())?;
return Ok((t.trim().to_string(), None));
}
let token = generate_token()?;
let path = token_file(port);
let mut o = std::fs::OpenOptions::new();
o.write(true).create(true).truncate(true);
#[cfg(unix)]
std::os::unix::fs::OpenOptionsExt::mode(&mut o, 0o600);
let res = o.open(&path).and_then(|mut f| std::io::Write::write_all(&mut f, token.as_bytes()));
res.map_err(|e| AutomationError::Io(format!("cannot write the control token to {}: {e}", path.display())))?;
Ok((token, Some(path)))
}
/// Compare equal-length tokens without an early exit.
pub fn token_matches(expected: &str, supplied: &str) -> bool {
expected.len() == supplied.len() && expected.bytes().zip(supplied.bytes()).fold(0u8, |d, (a, b)| d | (a ^ b)) == 0
}
pub enum LineRead {
Eof,
Line,
/// Over [`MAX_REQUEST_BYTES`]; the rest of the line is still unread.
TooLong,
}
/// Read one line, never buffering more than [`MAX_REQUEST_BYTES`] + 1 bytes.
pub fn read_bounded_line(r: &mut impl BufRead, line: &mut String) -> std::io::Result<LineRead> {
line.clear();
let mut bytes = Vec::new();
let n = std::io::Read::take(&mut *r, (MAX_REQUEST_BYTES + 1) as u64).read_until(b'\n', &mut bytes)?;
if n == 0 {
return Ok(LineRead::Eof);
}
if n > MAX_REQUEST_BYTES {
if bytes.last() != Some(&b'\n') {
discard_rest_of_line(r)?;
}
return Ok(LineRead::TooLong);
}
*line = String::from_utf8(bytes).map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?;
Ok(LineRead::Line)
}
fn discard_rest_of_line(r: &mut impl BufRead) -> std::io::Result<()> {
loop {
let buf = r.fill_buf()?;
if buf.is_empty() {
return Ok(());
}
if let Some(end) = buf.iter().position(|&b| b == b'\n') {
r.consume(end + 1);
return Ok(());
}
let n = buf.len();
r.consume(n);
}
}
/// Counts live connections; a permit is released when dropped.
#[derive(Clone, Default)]
pub struct ConnectionLimiter(Arc<AtomicUsize>);
pub struct Permit(Arc<AtomicUsize>);
impl ConnectionLimiter {
pub fn try_acquire(&self, max: usize) -> Option<Permit> {
self.0.fetch_update(Ordering::AcqRel, Ordering::Acquire, |n| (n < max).then_some(n + 1)).ok().map(|_| Permit(self.0.clone()))
}
}
impl Drop for Permit {
fn drop(&mut self) {
self.0.fetch_sub(1, Ordering::AcqRel);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn tokens() {
let a = generate_token().unwrap();
assert_eq!(a.len(), 64);
assert_ne!(a, generate_token().unwrap());
assert!(token_matches(&a, &a.clone()));
assert!(!token_matches(&a, "short"));
assert!(client_token(1, Some("too short".into())).is_err());
assert!(client_token(1, Some(format!(" {a}\n"))).is_ok());
}
#[test]
fn oversized_lines_are_skipped() {
let input = format!("{}\n{{\"ok\":1}}\n", "x".repeat(MAX_REQUEST_BYTES + 10));
let mut r = std::io::Cursor::new(input);
let mut line = String::new();
assert!(matches!(read_bounded_line(&mut r, &mut line).unwrap(), LineRead::TooLong));
assert!(matches!(read_bounded_line(&mut r, &mut line).unwrap(), LineRead::Line));
assert_eq!(line, "{\"ok\":1}\n");
assert!(matches!(read_bounded_line(&mut r, &mut line).unwrap(), LineRead::Eof));
}
#[test]
fn limiter_releases() {
let l = ConnectionLimiter::default();
let p = l.try_acquire(1).unwrap();
assert!(l.try_acquire(1).is_none());
drop(p);
assert!(l.try_acquire(1).is_some());
}
}
+499
View File
@@ -0,0 +1,499 @@
//! The MCP server (rmcp). Tool names are `snake_case`; each tool maps to one control-channel
//! method (see [`crate::rpc`]), answered in process (headless) or by the running app (bridge).
use std::sync::{Arc, Mutex, PoisonError};
use base64::Engine as _;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{CallToolResult, ContentBlock as Content};
use rmcp::{ErrorData as McpError, ServerHandler, ServiceExt, tool, tool_handler, tool_router};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use crate::budgets::{MAX_PNG_SIDE, check_png, fit_png, json_text};
use crate::headless::batch_reply;
use crate::security::MAX_BATCH_STEPS;
use crate::workspace::authorize_command;
use crate::{AutomationError, BridgeClient, Headless, bad};
/// Where tools run.
pub enum Backend {
/// An in-process session.
Headless(Arc<Mutex<Headless>>),
/// The running desktop app, over its control channel.
Bridge(Arc<BridgeClient>),
}
#[derive(Clone)]
pub struct TexturecraftMcp {
backend: Arc<Backend>,
tool_router: ToolRouter<Self>,
}
// ---------------------------------------------------------------------------------------------
// Parameters (serialized back to JSON as the control method's params)
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct FilterParams {
/// Only commands whose id or label contains this text (case-insensitive).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub filter: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct RunParams {
/// Command id from `command_list`, e.g. `layer.add.fill`, `mask.add.black`, `edit.undo`.
pub id: String,
/// Command parameters (see the command's `params` doc). Omitted = defaults; never a dialog.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub params: Option<Value>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct BatchParams {
/// Commands run in order; the batch stops at the first error and reports its index.
pub steps: Vec<RunParams>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct NewParams {
/// Built-in mesh: material_ball (default), sphere, cube, rounded_cube, cylinder, torus, plane, crate.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub mesh: Option<String>,
/// Texture set resolution, a power of two from 128 to 8192 (default 1024).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolution: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct OpenParams {
/// Forward-slash path relative to the read root.
pub path: String,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct SaveParams {
/// Forward-slash path relative to the write root (`.tcraft` is appended if missing). Omit to
/// save to the project's own file.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub path: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MaterialSaveParams {
/// `.tcmat` file relative to the write root (the extension is appended if missing).
pub path: String,
/// Layer or folder id (default: the selected layer).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layer: Option<u64>,
/// Material name (default: the layer name).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ImportParams {
/// Mesh file relative to the read root: .glb, .gltf (self-contained), .fbx, .dae, .obj, .ply, .stl.
pub path: String,
/// Texture set resolution (default 2048).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolution: Option<u32>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct ExportParams {
/// Output folder relative to the write root (created if missing; `.` = the root).
pub dir: String,
/// Preset name from `command_run export.presets`, e.g. "glTF PBR Metal Roughness".
#[serde(default, skip_serializing_if = "Option::is_none")]
pub preset: Option<String>,
/// Texture set index or "all" (default all).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ts: Option<Value>,
/// File format override: png, jpg, tga, tif, exr, …
#[serde(default, skip_serializing_if = "Option::is_none")]
pub format: Option<String>,
/// none | dilation | dilationDefault | infinite
#[serde(default, skip_serializing_if = "Option::is_none")]
pub padding: Option<String>,
/// Output size in pixels (power of two).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<u32>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct BakeParams {
/// Texture set index or "all" (default: the active one).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ts: Option<Value>,
/// Bake resolution (power of two).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub resolution: Option<u32>,
/// Mesh map ids, e.g. ["ambientOcclusion", "curvature"] (default: the set's bake settings).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub maps: Option<Vec<String>>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct StrokeParams {
/// Stroke points `[[x, y], …]` in viewport pixels (origin top-left), as in `viewport_render`.
pub points: Vec<[f64; 2]>,
/// Viewport size `[w, h]` the points refer to (default: the session viewport, 1280×800).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub viewport: Option<[f64; 2]>,
/// Base color: `[r, g, b]` linear 0..1 or `"#rrggbb"`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub color: Option<Value>,
/// 0..1
#[serde(default, skip_serializing_if = "Option::is_none")]
pub roughness: Option<f64>,
/// 0..1
#[serde(default, skip_serializing_if = "Option::is_none")]
pub metallic: Option<f64>,
/// -1..1
#[serde(default, skip_serializing_if = "Option::is_none")]
pub height: Option<f64>,
/// Brush size 0..100 (Painter's scale).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub size: Option<f64>,
/// Brush hardness 0..100.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub hardness: Option<f64>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct RenderParams {
/// `3d` (default) or `2d` (the UV view of the active texture set).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
/// Pixels, 16..2048 (default: the session viewport, the space `paint_stroke` points use).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub width: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub height: Option<u32>,
/// Camera yaw in degrees for this render only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub yaw: Option<f32>,
/// Camera pitch in degrees (-89..89) for this render only.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub pitch: Option<f32>,
/// Path trace the 3D view with this many samples per pixel (1..4096) instead of the
/// real-time viewport: slower, physically based light transport, no GPU needed.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub samples: Option<u32>,
/// Light bounces when path tracing (default 6).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub bounces: Option<u32>,
}
#[derive(Debug, Default, Deserialize, Serialize, JsonSchema)]
pub struct ScreenshotParams {
/// `3d` (default) or `2d`.
#[serde(default, skip_serializing_if = "Option::is_none")]
pub view: Option<String>,
}
#[derive(Debug, Deserialize, Serialize, JsonSchema)]
pub struct MenuParams {
/// Menu item id from the app's `ui.menu.list`, e.g. `file.save`, `viewport.frame`.
pub id: String,
}
// ---------------------------------------------------------------------------------------------
// Results
fn ok_json(v: &Value) -> CallToolResult {
match json_text(v) {
Ok(text) => CallToolResult::success(vec![Content::text(text)]),
Err(e) => fail(e),
}
}
fn fail(e: impl std::fmt::Display) -> CallToolResult {
CallToolResult::error(vec![Content::text(e.to_string())])
}
fn to_result(r: Result<Value, AutomationError>) -> Result<CallToolResult, McpError> {
Ok(match r {
Ok(v) => ok_json(&v),
Err(e) => fail(e),
})
}
/// A `{width, height, png: base64}` reply (render or app screenshot) as image content.
fn image_result(r: Result<Value, AutomationError>, note: &str, refit: bool) -> Result<CallToolResult, McpError> {
let png = r.and_then(|v| {
let b64 = v.get("png").and_then(Value::as_str).ok_or_else(|| AutomationError::Other("the reply has no PNG".into()))?;
if !refit {
check_png(b64.len() / 4 * 3)?;
return Ok(b64.to_string());
}
let bytes = base64::engine::general_purpose::STANDARD.decode(b64).map_err(|e| AutomationError::Other(format!("bad PNG data: {e}")))?;
Ok(base64::engine::general_purpose::STANDARD.encode(fit_png(bytes, MAX_PNG_SIDE)?))
});
Ok(match png {
Ok(b64) => CallToolResult::success(vec![Content::image(b64, "image/png"), Content::text(note.to_string())]),
Err(e) => fail(e),
})
}
fn params<T: Serialize>(p: &T) -> Value {
serde_json::to_value(p).unwrap_or(Value::Null)
}
impl TexturecraftMcp {
pub fn headless(h: Headless) -> Self {
Self::with_backend(Backend::Headless(Arc::new(Mutex::new(h))))
}
pub fn bridge(client: BridgeClient) -> Self {
Self::with_backend(Backend::Bridge(Arc::new(client)))
}
pub fn with_backend(backend: Backend) -> Self {
TexturecraftMcp { backend: Arc::new(backend), tool_router: Self::tool_router() }
}
/// Serve MCP on stdin/stdout until the client disconnects.
pub async fn serve_stdio(self) -> Result<(), AutomationError> {
let running = self.serve(rmcp::transport::stdio()).await.map_err(|e| AutomationError::Other(format!("MCP start: {e}")))?;
running.waiting().await.map_err(|e| AutomationError::Other(e.to_string()))?;
Ok(())
}
fn is_bridge(&self) -> bool {
matches!(*self.backend, Backend::Bridge(_))
}
/// One control-channel method on the backend.
async fn call(&self, method: &str, p: Value) -> Result<Value, AutomationError> {
match &*self.backend {
Backend::Headless(h) => {
let (h, m) = (h.clone(), method.to_string());
// A panicking command poisons the lock, but edits run on a document snapshot
// (`Session::edit`), so the session stays consistent: keep serving.
tokio::task::spawn_blocking(move || h.lock().unwrap_or_else(PoisonError::into_inner).handle(&m, &p))
.await
.unwrap_or_else(|_| Err(AutomationError::Other(format!("internal error in `{method}`"))))
}
Backend::Bridge(b) => match method {
"command.run" => {
let id = p.get("id").and_then(Value::as_str).unwrap_or_default();
authorize_command(id, p.get("params").unwrap_or(&Value::Null))?;
b.call(method, p).await
}
"project.save" if p.get("path").is_none() => b.call("ui.menu.invoke", json!({"id": "file.save"})).await,
"project.save" | "project.open" | "mesh.import" | "resource.import" | "material.save" | "material.load" | "textures.export"
| "command.batch" | "render" => {
Err(bad(format!("`{method}` with paths works in headless mode only: the running app reads and writes its own files (use ui_menu_invoke)")))
}
_ => b.call(method, p).await,
},
}
}
async fn run(&self, id: &str, p: Value) -> Result<Value, AutomationError> {
self.call("command.run", json!({"id": id, "params": p})).await
}
async fn bridge_only(&self, method: &str, p: Value) -> Result<Value, AutomationError> {
if self.is_bridge() {
self.call(method, p).await
} else {
Err(bad(format!(
"`{method}` needs the running app: start `texturecraft --control <port>` and run `texturecraft-cli mcp --bridge <port>` (headless renders: viewport_render)"
)))
}
}
async fn stroke(&self, p: StrokeParams) -> Result<Value, AutomationError> {
self.run("tool.paint", json!({})).await?;
if let Some(c) = p.color {
self.run("tool.material", json!({"channel": "baseColor", "color": c})).await?;
}
for (channel, v) in [("roughness", p.roughness), ("metallic", p.metallic), ("height", p.height)] {
if let Some(v) = v {
self.run("tool.material", json!({"channel": channel, "value": v})).await?;
}
}
if p.size.is_some() || p.hardness.is_some() {
self.run("tool.brush", json!({"size": p.size, "hardness": p.hardness})).await?;
}
self.run("tool.stroke", json!({"points": p.points, "viewport": p.viewport})).await
}
}
// ---------------------------------------------------------------------------------------------
// Tools
#[tool_router]
impl TexturecraftMcp {
#[tool(description = "The whole session as JSON: project, mesh, texture sets (resolution, channels, baked maps), the layer stack \
top to bottom (fill sources, masks, effects, painted tile counts), tool, camera, display and history.")]
async fn session_inspect(&self) -> Result<CallToolResult, McpError> {
to_result(self.call("session.inspect", json!({})).await)
}
#[tool(description = "List engine commands: id, label, menu path, shortcut, params doc and whether it can run now.")]
async fn command_list(&self, Parameters(p): Parameters<FilterParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("command.list", params(&p)).await)
}
#[tool(description = "Run an engine command by id with JSON params (see command_list). Runs with defaults, never opens a \
dialog. Commands given host paths (file.open, file.save, resource.import, material.save, …) are disabled: use the \
workspace tools (project_open, project_save, mesh_import, resource_import, material_save, material_load, textures_export).")]
async fn command_run(&self, Parameters(p): Parameters<RunParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("command.run", params(&p)).await)
}
#[tool(description = "Run several commands in order: steps [{id, params}]. Stops at the first error. Returns {completed, \
results, failed: {index, id, error} | null}; a failed batch is a tool error.")]
async fn command_batch(&self, Parameters(p): Parameters<BatchParams>) -> Result<CallToolResult, McpError> {
if p.steps.len() > MAX_BATCH_STEPS {
return Ok(fail(format!("at most {MAX_BATCH_STEPS} steps per batch")));
}
let reply = if self.is_bridge() {
let mut results = Vec::new();
let mut failed = None;
for (i, s) in p.steps.iter().enumerate() {
match self.call("command.run", params(s)).await {
Ok(v) => results.push(v),
Err(e) => {
failed = Some((i, s.id.as_str(), e.to_string()));
break;
}
}
}
batch_reply(results, failed)
} else {
match self.call("command.batch", params(&p)).await {
Ok(v) => v,
Err(e) => return Ok(fail(e)),
}
};
Ok(if reply["failed"].is_null() { ok_json(&reply) } else { fail(json_text(&reply).unwrap_or_else(|e| e.to_string())) })
}
#[tool(description = "Start a new project on a built-in mesh (one texture set per material, each with an empty paint layer). \
Returns the session.")]
async fn project_new(&self, Parameters(p): Parameters<NewParams>) -> Result<CallToolResult, McpError> {
to_result(self.run("project.new", params(&p)).await)
}
#[tool(description = "Open a .tcraft project or a mesh file (path relative to the read root). Returns the session.")]
async fn project_open(&self, Parameters(p): Parameters<OpenParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("project.open", params(&p)).await)
}
#[tool(description = "Save the project as .tcraft (path relative to the write root; omit to save to its own file).")]
async fn project_save(&self, Parameters(p): Parameters<SaveParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("project.save", params(&p)).await)
}
#[tool(description = "New project from a mesh file (path relative to the read root): one texture set per material. Returns \
the session; import warnings are in the session log.")]
async fn mesh_import(&self, Parameters(p): Parameters<ImportParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("mesh.import", params(&p)).await)
}
#[tool(description = "Import an image (png, jpg, tga, tif, bmp, webp, exr, hdr; path relative to the read root) as a project \
resource. Returns its name, for command_run layer.add.image {name} or tool.stencil {image}.")]
async fn resource_import(&self, Parameters(p): Parameters<OpenParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("resource.import", params(&p)).await)
}
#[tool(description = "Save a layer or folder (default: the selected one) as a smart material file (.tcmat) below the write root.")]
async fn material_save(&self, Parameters(p): Parameters<MaterialSaveParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("material.save", params(&p)).await)
}
#[tool(description = "Add a smart material from a .tcmat file (relative to the read root) above the selection. Returns its layer.")]
async fn material_load(&self, Parameters(p): Parameters<OpenParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("material.load", params(&p)).await)
}
#[tool(description = "Export textures with a preset into a folder relative to the write root. Returns the written files and \
warnings.")]
async fn textures_export(&self, Parameters(p): Parameters<ExportParams>) -> Result<CallToolResult, McpError> {
to_result(self.call("textures.export", params(&p)).await)
}
#[tool(description = "Bake mesh maps (ambient occlusion, curvature, thickness, …) for generators and smart materials.")]
async fn bake(&self, Parameters(p): Parameters<BakeParams>) -> Result<CallToolResult, McpError> {
to_result(self.run("bake.run", params(&p)).await)
}
#[tool(description = "Paint a stroke with the paint tool on the selected layer (or its mask target): sets the brush material \
(color, roughness, metallic, height) and size/hardness, then strokes through `points` in viewport pixels. See \
viewport_render for where the mesh is.")]
async fn paint_stroke(&self, Parameters(p): Parameters<StrokeParams>) -> Result<CallToolResult, McpError> {
to_result(self.stroke(p).await)
}
#[tool(description = "Headless: render the 3D view (or the 2D UV view) as a PNG image, up to 2048 px a side. Camera yaw/pitch \
apply to this render only. In bridge mode use viewport_screenshot.")]
async fn viewport_render(&self, Parameters(p): Parameters<RenderParams>) -> Result<CallToolResult, McpError> {
let note = format!("render {}", params(&p));
image_result(self.call("render", params(&p)).await, &note, false)
}
#[tool(description = "Bridge mode: PNG of the live app's 3D or 2D viewport.")]
async fn viewport_screenshot(&self, Parameters(p): Parameters<ScreenshotParams>) -> Result<CallToolResult, McpError> {
image_result(self.bridge_only("viewport.screenshot", params(&p)).await, "screenshot of the app viewport", true)
}
#[tool(description = "Bridge mode: PNG of the whole app window (downscaled to 2048 px a side at most).")]
async fn ui_screenshot(&self) -> Result<CallToolResult, McpError> {
image_result(self.bridge_only("ui.screenshot", json!({})).await, "screenshot of the app window", true)
}
#[tool(description = "Bridge mode: the app's UI state (panels, windows, mode, layout, viewport rect, toasts).")]
async fn ui_inspect(&self) -> Result<CallToolResult, McpError> {
to_result(self.bridge_only("ui.inspect", json!({})).await)
}
#[tool(description = "Bridge mode: activate a menu item by id like a click (may open a window). ui.menu.list lists ids.")]
async fn ui_menu_invoke(&self, Parameters(p): Parameters<MenuParams>) -> Result<CallToolResult, McpError> {
to_result(self.bridge_only("ui.menu.invoke", params(&p)).await)
}
}
#[tool_handler(
router = self.tool_router,
name = "texturecraft",
instructions = "TextureCraft 3D texture painter. Every edit is an engine command: `command_list` shows ids and params, \
`command_run`/`command_batch` run them. Start with `project_new` (built-in mesh) or `project_open`/`mesh_import` (files \
relative to the workspace root), check your work with `session_inspect` and `viewport_render`, paint with `paint_stroke`, \
bake with `bake`, then `project_save` (.tcraft) and `textures_export`. Undo: command_run edit.undo."
)]
impl ServerHandler for TexturecraftMcp {}
#[cfg(test)]
mod tests {
use super::*;
use crate::headless::Filesystem;
#[tokio::test(flavor = "multi_thread")]
async fn a_panic_does_not_wedge_the_session() {
let s = texturecraft_engine::Session::new_project("t", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
let mcp = TexturecraftMcp::headless(Headless::new(s, Filesystem::Denied));
let Backend::Headless(h) = &*mcp.backend else { panic!("headless") };
let h2 = h.clone();
let _ = tokio::task::spawn_blocking(move || {
let _g = h2.lock().unwrap();
panic!("boom")
})
.await;
assert!(mcp.call("session.inspect", json!({})).await.is_ok());
}
#[test]
fn oversized_replies_become_errors() {
let r = ok_json(&json!("x".repeat(crate::budgets::MAX_RESPONSE_BYTES)));
assert_eq!(r.is_error, Some(true));
}
}
+259
View File
@@ -0,0 +1,259 @@
//! Capability-based file access for untrusted automation paths (MCP, `serve`).
//!
//! Roots are trusted launch-time configuration (`--read-root`, `--write-root`); request paths
//! are untrusted, forward-slash relative paths resolved by `cap-std` beneath the held directory
//! handle, so `..`, absolute paths, drive prefixes and symlink or junction escapes all fail.
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use cap_std::ambient_authority;
use cap_std::fs::{Dir, OpenOptions};
use serde_json::Value;
use crate::{AutomationError, bad};
/// Largest file read through automation (the mesh importer's own limit).
pub const MAX_READ_BYTES: u64 = texturecraft_engine::formats::mesh_import::MAX_MESH_FILE_BYTES;
/// Separate read and write directory capabilities. A missing authority fails closed.
#[derive(Clone, Default)]
pub struct AuthorizedWorkspace {
read: Option<Arc<Dir>>,
write: Option<Arc<Dir>>,
}
impl AuthorizedWorkspace {
pub fn new(read_root: Option<&Path>, write_root: Option<&Path>) -> Result<Self, AutomationError> {
Ok(Self { read: open_root(read_root, "read")?, write: open_root(write_root, "write")? })
}
/// Read one regular file below the read root.
pub fn read(&self, path: &str) -> Result<Vec<u8>, AutomationError> {
let rel = relative_path(path)?;
let root = self.read.as_ref().ok_or_else(|| denied("read"))?;
let file = root.open(&rel).map_err(|e| file_error("read", path, e))?;
let meta = file.metadata().map_err(|e| file_error("read", path, e))?;
if !meta.is_file() {
return Err(bad(format!("not a regular file: `{path}`")));
}
if meta.len() > MAX_READ_BYTES {
return Err(bad(format!("`{path}` is {} bytes (limit {MAX_READ_BYTES})", meta.len())));
}
let mut bytes = Vec::new();
file.take(MAX_READ_BYTES).read_to_end(&mut bytes).map_err(|e| file_error("read", path, e))?;
Ok(bytes)
}
/// Create or replace one file below the write root: a temporary file beside the target,
/// synced and renamed over it. The parent directory must exist.
pub fn write(&self, path: &str, bytes: &[u8]) -> Result<(), AutomationError> {
let rel = relative_path(path)?;
let root = self.write.as_ref().ok_or_else(|| denied("write"))?;
let leaf = rel.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
let tmp = rel.with_file_name(format!(".{leaf}.{}.tmp", std::process::id()));
let mut options = OpenOptions::new();
options.write(true).create_new(true);
let res = root
.open_with(&tmp, &options)
.and_then(|mut f| {
f.write_all(bytes)?;
f.sync_all()
})
.and_then(|()| root.rename(&tmp, root, &rel));
if let Err(e) = res {
let _ = root.remove_file(&tmp);
return Err(file_error("write", path, e));
}
Ok(())
}
/// Create a directory (and its parents) below the write root.
pub fn create_dir_all(&self, path: &str) -> Result<(), AutomationError> {
let rel = relative_path(path)?;
let root = self.write.as_ref().ok_or_else(|| denied("write"))?;
root.create_dir_all(&rel).map_err(|e| file_error("create", path, e))
}
}
fn open_root(path: Option<&Path>, authority: &str) -> Result<Option<Arc<Dir>>, AutomationError> {
let Some(path) = path else { return Ok(None) };
if path.as_os_str().is_empty() {
return Err(bad(format!("the automation {authority} root is empty")));
}
let dir =
Dir::open_ambient_dir(path, ambient_authority()).map_err(|e| AutomationError::Io(format!("cannot open {authority} root `{}`: {e}", path.display())))?;
Ok(Some(Arc::new(dir)))
}
/// Validate an untrusted path before any I/O (cap-std then confines resolution to the root).
pub fn relative_path(raw: &str) -> Result<PathBuf, AutomationError> {
let reject = |why: &str| bad(format!("path rejected ({why}): `{raw}`; use a forward-slash path relative to the workspace root"));
if raw.is_empty() {
return Err(reject("empty"));
}
if raw.contains('\\') {
return Err(reject("backslash"));
}
if raw.starts_with('/') {
return Err(reject("absolute"));
}
if raw.contains(':') {
return Err(reject("drive, scheme or stream prefix"));
}
for c in raw.split('/') {
if c.is_empty() || c == "." || c == ".." {
return Err(reject("empty, `.` or `..` component"));
}
if c.ends_with(['.', ' ']) || c.chars().any(char::is_control) {
return Err(reject("component ends in a dot or space, or has control characters"));
}
let stem = c.split('.').next().unwrap_or(c).to_ascii_uppercase();
let device = matches!(stem.as_str(), "CON" | "PRN" | "AUX" | "NUL" | "CONIN$" | "CONOUT$")
|| (stem.len() == 4 && (stem.starts_with("COM") || stem.starts_with("LPT")) && stem.ends_with(|ch: char| ch.is_ascii_digit()));
if device {
return Err(reject("reserved device name"));
}
}
Ok(PathBuf::from(raw))
}
fn denied(authority: &str) -> AutomationError {
bad(format!("file access is not granted: no {authority} root (start the server with --{authority}-root <dir>)"))
}
fn file_error(op: &str, path: &str, e: std::io::Error) -> AutomationError {
AutomationError::Io(format!("{op} `{path}` failed: {e}"))
}
/// Engine commands that take host paths (`file.open`, `file.exportTextures`, `resource.import`,
/// `material.save`, …) would bypass the workspace: automation clients use the workspace-scoped
/// methods instead. Any command given a `path` or `dir` is refused, and every `file.*` command
/// but `file.close` and `file.removeUnused` (`file.save` even without `path`: a headless session's path is
/// workspace-relative, not a host path; `file.reimportMesh` without `path` re-reads the
/// embedded mesh).
pub fn authorize_command(id: &str, params: &Value) -> Result<(), AutomationError> {
let has_path = ["path", "dir"].iter().any(|k| params.get(k).is_some_and(|v| !v.is_null()));
let ok = match id {
"file.close" | "file.removeUnused" => true,
"file.reimportMesh" => !has_path,
_ => !id.starts_with("file.") && !has_path,
};
if ok {
Ok(())
} else {
Err(bad(format!(
"`{id}` with host paths is disabled for automation; use project_open, project_save, mesh_import, resource_import, material_save, material_load or textures_export"
)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn roots(name: &str) -> (PathBuf, PathBuf, AuthorizedWorkspace) {
let base = std::env::temp_dir().join(format!("tc-ws-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (inside, outside) = (base.join("inside"), base.join("outside"));
std::fs::create_dir_all(&inside).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let ws = AuthorizedWorkspace::new(Some(&inside), Some(&inside)).unwrap();
(inside, outside, ws)
}
#[test]
fn reads_and_writes_stay_in_the_root() {
let (inside, _, ws) = roots("valid");
std::fs::write(inside.join("a.txt"), b"canary").unwrap();
assert_eq!(ws.read("a.txt").unwrap(), b"canary");
ws.create_dir_all("out/deep").unwrap();
ws.write("out/deep/b.txt", b"one").unwrap();
ws.write("out/deep/b.txt", b"two").unwrap();
assert_eq!(std::fs::read(inside.join("out/deep/b.txt")).unwrap(), b"two");
let leftovers = std::fs::read_dir(inside.join("out/deep")).unwrap().count();
assert_eq!(leftovers, 1, "no temporary files left behind");
assert!(ws.write("missing/c.txt", b"x").is_err(), "parent must exist");
}
#[test]
fn escapes_and_malformed_paths_are_rejected() {
let (_, outside, ws) = roots("reject");
let abs = outside.join("x.txt").display().to_string();
for p in ["", "/abs", "../x", "a/../../x", "a\\b", "C:/x", "a//b", "./a", "a:b", "NUL", "con.txt", "x/COM1.log", "dot.", abs.as_str()] {
assert!(ws.read(p).is_err(), "read accepted {p:?}");
assert!(ws.write(p, b"x").is_err(), "write accepted {p:?}");
assert!(ws.create_dir_all(p).is_err(), "mkdir accepted {p:?}");
}
}
#[test]
fn authorities_are_separate_and_fail_closed() {
let (inside, _, _) = roots("separate");
std::fs::write(inside.join("r.txt"), b"r").unwrap();
let ro = AuthorizedWorkspace::new(Some(&inside), None).unwrap();
assert!(ro.read("r.txt").is_ok());
assert!(ro.write("w.txt", b"x").is_err());
let none = AuthorizedWorkspace::default();
assert!(none.read("r.txt").is_err());
}
#[cfg(unix)]
#[test]
fn symlink_escape_is_rejected() {
let (inside, outside, ws) = roots("symlink");
std::fs::write(outside.join("secret.txt"), b"s").unwrap();
std::os::unix::fs::symlink(&outside, inside.join("link")).unwrap();
assert!(ws.read("link/secret.txt").is_err());
assert!(ws.write("link/new.txt", b"x").is_err());
assert!(!outside.join("new.txt").exists());
}
#[cfg(windows)]
#[test]
fn junction_escape_is_rejected() {
let (inside, outside, ws) = roots("junction");
std::fs::write(outside.join("secret.txt"), b"s").unwrap();
let link = inside.join("junction");
let made = std::process::Command::new("cmd.exe").args(["/D", "/C", "mklink", "/J"]).arg(&link).arg(&outside).output();
if !made.is_ok_and(|o| o.status.success()) {
eprintln!("skipping: cannot create a junction");
return;
}
assert!(ws.read("junction/secret.txt").is_err());
assert!(ws.write("junction/new.txt", b"x").is_err());
assert!(!outside.join("new.txt").exists());
let _ = std::fs::remove_dir(link);
}
#[test]
fn path_commands_are_denied() {
for id in ["file.open", "file.new", "file.save", "file.saveAs", "file.saveCopy", "file.exportTextures"] {
assert!(authorize_command(id, &json!({})).is_err(), "{id}");
}
for id in ["resource.import", "material.save", "material.load", "anything.new"] {
assert!(authorize_command(id, &json!({"path": "/etc/x"})).is_err(), "{id}");
assert!(authorize_command(id, &json!({"dir": "/etc"})).is_err(), "{id}");
}
assert!(authorize_command("file.reimportMesh", &json!({"path": "/etc/x.obj"})).is_err());
assert!(authorize_command("file.reimportMesh", &json!({})).is_ok());
assert!(authorize_command("file.close", &json!({})).is_ok());
assert!(authorize_command("layer.add.fill", &json!({"color": "#ff0000", "path": null})).is_ok());
}
/// Every registry command documenting a host path must be classified (fails when a new
/// path-taking command is added without an automation policy).
#[test]
fn registry_path_params_are_classified() {
let probe = json!({"path": "/outside/probe", "dir": "/outside", "mesh": "/outside/m.obj"});
let open: Vec<&str> = texturecraft_engine::command_specs()
.iter()
.filter(|c| c.params.contains("path") || c.params.contains("{dir"))
.filter(|c| authorize_command(c.id, &probe).is_ok())
.map(|c| c.id)
.collect();
assert!(open.is_empty(), "path-taking commands need an automation policy: {open:?}");
}
}
+377
View File
@@ -0,0 +1,377 @@
//! Acceptance: an agent completes realistic texturing tasks over MCP, checked only through MCP
//! results (plus the exported files on disk), and the server holds its security line.
use base64::Engine as _;
use rmcp::model::{CallToolRequestParams, CallToolResult, ClientConfig};
use rmcp::service::RunningService;
use rmcp::{ClientHandler, RoleClient, ServiceExt};
use serde_json::{Value, json};
use texturecraft_automation::{AuthorizedWorkspace, BridgeClient, Filesystem, Headless, TexturecraftMcp, rpc};
#[derive(Clone, Default)]
struct Client;
impl ClientHandler for Client {
fn get_info(&self) -> ClientConfig {
ClientConfig::default()
}
}
type Conn = RunningService<RoleClient, Client>;
type Server = tokio::task::JoinHandle<()>;
async fn connect(fs: Filesystem) -> (Conn, Server) {
let (s, c) = tokio::io::duplex(1 << 22);
let session = texturecraft_engine::Session::new_project("t", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
let server = tokio::spawn(async move {
if let Ok(running) = TexturecraftMcp::headless(Headless::new(session, fs)).serve(s).await {
let _ = running.waiting().await;
}
});
(Client.serve(c).await.expect("client init"), server)
}
/// Close the client and wait for the server, so its directory handles are released before the
/// test removes the folder (Windows refuses otherwise).
async fn shutdown(c: Conn, server: Server) {
c.cancel().await.unwrap();
server.await.unwrap();
}
fn tmp(name: &str) -> std::path::PathBuf {
let d = std::env::temp_dir().join(format!("tc-agent-{}-{name}", std::process::id()));
let _ = std::fs::remove_dir_all(&d);
std::fs::create_dir_all(&d).unwrap();
d
}
fn workspace(root: &std::path::Path) -> Filesystem {
Filesystem::Workspace(AuthorizedWorkspace::new(Some(root), Some(root)).unwrap())
}
fn text(r: &CallToolResult) -> String {
r.content.iter().filter_map(|c| c.as_text()).map(|t| t.text.clone()).collect::<Vec<_>>().join("\n")
}
async fn call(c: &Conn, name: &str, args: Value) -> Result<CallToolResult, rmcp::ServiceError> {
let mut p = CallToolRequestParams::new(name.to_owned());
if let Value::Object(m) = args {
p = p.with_arguments(m);
}
c.call_tool(p).await
}
/// Call a tool and parse its JSON result, failing the test on a tool error.
async fn tool(c: &Conn, name: &str, args: Value) -> Value {
let r = call(c, name, args).await.expect("transport");
assert_ne!(r.is_error, Some(true), "{name} failed: {}", text(&r));
serde_json::from_str(&text(&r)).unwrap_or(Value::String(text(&r)))
}
/// The tool's error text (the test fails if the tool succeeded).
async fn tool_err(c: &Conn, name: &str, args: Value) -> String {
match call(c, name, args).await {
Ok(r) => {
assert_eq!(r.is_error, Some(true), "{name} should fail: {}", text(&r));
text(&r)
}
Err(e) => e.to_string(),
}
}
async fn run(c: &Conn, id: &str, params: Value) -> Value {
tool(c, "command_run", json!({"id": id, "params": params})).await
}
async fn inspect(c: &Conn) -> Value {
tool(c, "session_inspect", json!({})).await
}
fn top(s: &Value) -> &Value {
&s["layers"][0]
}
/// Painted tiles of a paint layer's base color.
fn painted(layer: &Value) -> u64 {
layer["painted"].as_array().into_iter().flatten().filter(|p| p["channel"] == "baseColor").map(|p| p["tiles"].as_u64().unwrap()).sum()
}
/// Sort `painted` lists by channel: their order follows a hash map in the engine.
fn canon(v: &mut Value) {
match v {
Value::Object(m) => {
if let Some(Value::Array(p)) = m.get_mut("painted") {
p.sort_by(|a, b| a["channel"].as_str().cmp(&b["channel"].as_str()));
}
m.values_mut().for_each(canon);
}
Value::Array(a) => a.iter_mut().for_each(canon),
_ => {}
}
}
#[tokio::test(flavor = "multi_thread")]
async fn agent_completes_texturing_tasks() {
let dir = tmp("tasks");
let (c, server) = connect(workspace(&dir)).await;
// 1. New project on a built-in mesh.
let s = tool(&c, "project_new", json!({"mesh": "sphere", "resolution": 256, "name": "Agent"})).await;
assert_eq!(s["project"], "Agent");
assert!(s["mesh"]["triangles"].as_u64().unwrap() > 1000, "task 1: {}", s["mesh"]);
assert_eq!(s["textureSets"][0]["resolution"], 256);
assert_eq!(top(&s)["kind"], "paint");
// 2. Fill layer with a color and roughness.
run(&c, "layer.add.fill", json!({"color": [0.2, 0.4, 0.6], "roughness": 0.2})).await;
let s = inspect(&c).await;
let fill = &top(&s)["fill"]["sources"];
assert_eq!(top(&s)["kind"], "fill", "task 2: {}", top(&s));
assert!((fill["roughness"]["uniform"][0].as_f64().unwrap() - 0.2).abs() < 1e-6, "task 2: {fill}");
assert!((fill["baseColor"]["uniform"][2].as_f64().unwrap() - 0.6).abs() < 1e-6, "task 2: {fill}");
// 3. Bake, then a black mask with an edge-wear generator.
tool(&c, "bake", json!({"resolution": 128})).await;
run(&c, "mask.add.black", json!({})).await;
run(&c, "effect.add.generator", json!({"generator": "edgeWear", "level": 0.4})).await;
let s = inspect(&c).await;
assert!(!s["textureSets"][0]["baked"]["maps"].as_array().unwrap().is_empty(), "task 3: {}", s["textureSets"]);
let mask = &top(&s)["mask"];
assert_eq!(mask["background"], "black", "task 3: {mask}");
assert_eq!(mask["effects"][0]["kind"], "Generator", "task 3: {mask}");
assert_eq!(mask["effects"][0]["generator"]["type"], "EdgeWear", "task 3: {mask}");
assert!((mask["effects"][0]["generator"]["level"].as_f64().unwrap() - 0.4).abs() < 1e-6);
// 4. Paint a red stroke across the middle of the view on a new paint layer.
run(&c, "layer.add.paint", json!({"name": "Ink"})).await;
let r = tool(&c, "paint_stroke", json!({"points": [[600, 400], [680, 400]], "color": [1, 0, 0], "roughness": 0.9, "size": 10})).await;
assert!(r["stamps"].as_u64().unwrap() > 1, "task 4: {r}");
let s = inspect(&c).await;
assert_eq!(top(&s)["name"], "Ink");
let tiles = painted(top(&s));
assert!(tiles > 0, "task 4: {}", top(&s));
// 5. Undo and redo the stroke.
run(&c, "edit.undo", json!({})).await;
assert_eq!(painted(top(&inspect(&c).await)), 0, "task 5: undo");
run(&c, "edit.redo", json!({})).await;
assert_eq!(painted(top(&inspect(&c).await)), tiles, "task 5: redo");
// 6. A smart material lands as a folder of layers.
run(&c, "material.apply", json!({"material": "iron_rusted"})).await;
let s = inspect(&c).await;
assert_eq!(top(&s)["kind"], "group", "task 6: {}", top(&s));
assert_eq!(top(&s)["name"], "Iron Rusted");
assert!(!top(&s)["children"].as_array().unwrap().is_empty());
// 7. Export with the glTF preset.
let r = tool(&c, "textures_export", json!({"dir": "tex", "preset": "glTF PBR Metal Roughness"})).await;
let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f.as_str().unwrap()).collect();
assert!(files.iter().any(|f| f.contains("BaseColor")), "task 7: {r}");
assert!(files.iter().any(|f| f.contains("OcclusionRoughnessMetallic")), "task 7: {r}");
for f in &files {
assert!(std::fs::metadata(dir.join(f)).unwrap().len() > 100, "task 7: {f}");
}
std::fs::create_dir_all(dir.join("lib")).unwrap();
// 11. Import an image resource and use it as a fill layer (kept by save/reopen below).
image::RgbaImage::from_fn(32, 32, |x, y| image::Rgba([(x * 8) as u8, (y * 8) as u8, 90, 255])).save(dir.join("grunge.png")).unwrap();
let r = tool(&c, "resource_import", json!({"path": "grunge.png"})).await;
let name = r["name"].as_str().unwrap().to_string();
run(&c, "layer.add.image", json!({"name": name})).await;
let s = inspect(&c).await;
// The selected layer is the material's folder, so the new layer goes inside it.
let layer = &top(&s)["children"][0];
assert_eq!(layer["fill"]["sources"]["baseColor"]["image"], name.as_str(), "task 11: {layer}");
// 12. Save the rust folder as a smart material file and load it back as a new folder.
let rust = top(&s)["id"].clone();
let saved = tool(&c, "material_save", json!({"path": "lib/rust", "layer": rust, "name": "My Rust"})).await;
assert_eq!(saved["path"], "lib/rust.tcmat", "task 12: parent folders must exist: {saved}");
let loaded = tool(&c, "material_load", json!({"path": "lib/rust.tcmat"})).await["layer"].clone();
// Added above the selection: inside the selected folder.
let s = inspect(&c).await;
let copy = top(&s)["children"].as_array().unwrap().iter().find(|l| l["id"] == loaded).cloned().unwrap_or_default();
assert_eq!(copy["name"], "My Rust", "task 12: {}", top(&s));
assert_eq!(copy["kind"], "group", "task 12: {copy}");
// 8. Save, reopen and compare.
let before = inspect(&c).await;
let saved = tool(&c, "project_save", json!({"path": "agent"})).await;
assert_eq!(saved["path"], "agent.tcraft");
tool(&c, "project_new", json!({"mesh": "cube", "resolution": 128})).await;
let after = tool(&c, "project_open", json!({"path": "agent.tcraft"})).await;
let (mut before, mut after) = (before, after);
canon(&mut before);
canon(&mut after);
for k in ["project", "mesh", "textureSets", "layers"] {
assert_eq!(before[k], after[k], "task 8: `{k}` differs after reopening");
}
assert_eq!(after["path"], "agent.tcraft");
assert_eq!(after["modified"], false);
// 9. Render a PNG (skipped without a GPU adapter).
match call(&c, "viewport_render", json!({"width": 320, "height": 200, "yaw": 30})).await.unwrap() {
r if r.is_error == Some(true) => {
assert!(text(&r).contains("cannot render"), "task 9: {}", text(&r));
eprintln!("skipping render: {}", text(&r));
}
r => {
let img = r.content.iter().find_map(|c| c.as_image()).expect("image content");
assert_eq!(img.mime_type, "image/png");
let png = base64::engine::general_purpose::STANDARD.decode(&img.data).unwrap();
let px = image::load_from_memory(&png).unwrap().into_rgba8();
assert_eq!(px.dimensions(), (320, 200));
assert_ne!(px.get_pixel(160, 100), px.get_pixel(2, 2), "task 9: the mesh differs from the background");
}
}
// 10. A batch stops at the failing step and says which.
let err = tool_err(&c, "command_batch", json!({"steps": [{"id": "layer.add.paint"}, {"id": "no.such.command"}, {"id": "layer.add.paint"}]})).await;
let v: Value = serde_json::from_str(&err).unwrap();
assert_eq!(v["completed"], 1, "task 10: {v}");
assert_eq!(v["failed"]["index"], 1, "task 10: {v}");
shutdown(c, server).await;
std::fs::remove_dir_all(&dir).unwrap();
}
const TOOLS: [&str; 19] = [
"resource_import",
"material_save",
"material_load",
"session_inspect",
"command_list",
"command_run",
"command_batch",
"project_new",
"project_open",
"project_save",
"mesh_import",
"textures_export",
"bake",
"paint_stroke",
"viewport_render",
"viewport_screenshot",
"ui_screenshot",
"ui_inspect",
"ui_menu_invoke",
];
#[tokio::test(flavor = "multi_thread")]
async fn paths_outside_the_workspace_are_rejected() {
let base = tmp("security");
let (root, outside) = (base.join("root"), base.join("outside"));
std::fs::create_dir_all(&root).unwrap();
std::fs::create_dir_all(&outside).unwrap();
let (c, server) = connect(workspace(&root)).await;
tool(&c, "project_save", json!({"path": "ok.tcraft"})).await;
std::fs::copy(root.join("ok.tcraft"), outside.join("secret.tcraft")).unwrap();
let abs = outside.join("secret.tcraft").display().to_string();
for path in ["../outside/secret.tcraft", abs.as_str(), "C:/secret.tcraft", "/etc/passwd", "a/../../outside/secret.tcraft", "a\\..\\x.tcraft"] {
tool_err(&c, "project_open", json!({"path": path})).await;
tool_err(&c, "mesh_import", json!({"path": path})).await;
tool_err(&c, "resource_import", json!({"path": path})).await;
tool_err(&c, "material_load", json!({"path": path})).await;
tool_err(&c, "material_save", json!({"path": path})).await;
tool_err(&c, "project_save", json!({"path": path})).await;
}
let e = tool_err(&c, "textures_export", json!({"dir": "../outside/tex"})).await;
assert!(e.contains("rejected"), "{e}");
assert!(!outside.join("tex").exists());
for (id, p) in [
("file.open", json!({"path": abs})),
("file.saveAs", json!({"path": abs})),
("file.save", json!({})),
("file.exportTextures", json!({"dir": "x"})),
("resource.import", json!({"path": abs})),
("material.save", json!({"path": abs})),
] {
let e = tool_err(&c, "command_run", json!({"id": id, "params": p})).await;
assert!(e.contains("disabled for automation"), "{id}: {e}");
}
shutdown(c, server).await;
// Without roots there is no file access at all.
let (c, server) = connect(Filesystem::Denied).await;
assert!(tool_err(&c, "project_save", json!({"path": "x.tcraft"})).await.contains("not granted"));
assert!(tool_err(&c, "project_open", json!({"path": "x.tcraft"})).await.contains("not granted"));
shutdown(c, server).await;
std::fs::remove_dir_all(&base).unwrap();
}
#[tokio::test(flavor = "multi_thread")]
async fn every_tool_rejects_junk_without_panicking() {
let (c, server) = connect(Filesystem::Denied).await;
let listed: Vec<String> = c.list_all_tools().await.unwrap().into_iter().map(|t| t.name.to_string()).collect();
for t in TOOLS {
assert!(listed.iter().any(|l| l == t), "missing tool {t}");
}
let wrong_types = json!({
"id": 7, "params": "x", "filter": 3, "steps": "x", "mesh": 1, "resolution": "big", "name": [], "path": 5, "dir": false,
"preset": 1, "ts": "nope", "format": 1, "padding": 2, "size": -1, "maps": "x", "points": "x", "viewport": 1, "color": "nope",
"roughness": "x", "metallic": "x", "height": "x", "hardness": "x", "view": 5, "width": -5, "yaw": "x", "pitch": "x"
});
let hostile = json!({
"id": "no.such", "params": {"layer": 1e300}, "filter": "\u{0}", "steps": [{"id": "x"}], "mesh": "../../etc", "resolution": 3, "name": "",
"path": "../../x", "dir": "../x", "preset": "nope", "ts": 99, "format": "zzz", "padding": "?", "size": 3, "maps": ["nope"], "points": [],
"viewport": [0, 0], "color": "#zzzzzz", "roughness": 1e30, "metallic": -1e30, "height": 1e30, "hardness": 1e30, "view": "4d",
"width": 99999, "yaw": 1e30, "pitch": -1e30
});
for (n, junk) in [Value::Null, wrong_types, hostile].into_iter().enumerate() {
for t in &listed {
// No arguments means defaults for these (a real project, a real bake): not junk.
if n == 0 && ["project_new", "bake", "viewport_render"].contains(&t.as_str()) {
continue;
}
let may_succeed = t == "session_inspect" || (t == "command_list" && n != 1);
let r = call(&c, t, junk.clone()).await;
let failed = r.as_ref().map_or(true, |r| r.is_error == Some(true));
assert!(failed || may_succeed, "{t} accepted junk #{n}: {:?}", r.map(|r| text(&r)));
}
}
// Still serving.
assert!(inspect(&c).await["layers"].is_array());
shutdown(c, server).await;
}
/// Bridge mode against a control-protocol server (the headless one speaks the app's protocol).
#[tokio::test(flavor = "multi_thread")]
async fn bridge_mode_forwards_to_a_control_server() {
let session = texturecraft_engine::Session::new_project("t", texturecraft_engine::geom::primitives::cube(2.0), "builtin:cube", None, 128).unwrap();
let h = std::sync::Arc::new(std::sync::Mutex::new(Headless::new(session, Filesystem::Denied)));
let token = "bridge-test-token-0123456789".to_string();
let (tx, rx) = std::sync::mpsc::channel();
let t = token.clone();
std::thread::spawn(move || rpc::serve_tcp(0, h, t, |a| tx.send(a.port()).unwrap()));
let port = rx.recv().unwrap();
let (s, c) = tokio::io::duplex(1 << 20);
let server = tokio::spawn(async move {
if let Ok(running) = TexturecraftMcp::bridge(BridgeClient::new(port, token)).serve(s).await {
let _ = running.waiting().await;
}
});
let c = Client.serve(c).await.unwrap();
run(&c, "layer.add.fill", json!({"roughness": 0.7})).await;
run(&c, "layer.add.paint", json!({})).await;
tool(&c, "paint_stroke", json!({"points": [[640, 400]], "color": "#ff0000"})).await;
let s = inspect(&c).await;
assert_eq!(s["layers"][1]["kind"], "fill");
assert!(painted(&s["layers"][0]) > 0, "{}", s["layers"][0]);
let b = tool(&c, "command_batch", json!({"steps": [{"id": "layer.add.paint"}, {"id": "edit.undo"}]})).await;
assert_eq!(b["completed"], 2);
assert!(tool_err(&c, "command_run", json!({"id": "file.open", "params": {"path": "/etc/passwd"}})).await.contains("disabled"));
assert!(tool_err(&c, "project_open", json!({"path": "x.tcraft"})).await.contains("headless mode only"));
assert!(tool_err(&c, "ui_inspect", json!({})).await.contains("running app"));
shutdown(c, server).await;
let (s, c) = tokio::io::duplex(1 << 20);
let server = tokio::spawn(async move {
if let Ok(running) = TexturecraftMcp::bridge(BridgeClient::new(port, "wrong-token-0123456789".into())).serve(s).await {
let _ = running.waiting().await;
}
});
let c = Client.serve(c).await.unwrap();
assert!(tool_err(&c, "session_inspect", json!({})).await.contains("authentication failed"));
shutdown(c, server).await;
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "texturecraft-bake"
description = "TextureCraft mesh-map baking: high-poly transfer (cage, match by name) of normal, height, AO, bent normals, curvature, thickness, ID, opacity, color, position and world-space maps"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
texturecraft-core = { workspace = true }
texturecraft-geom = { workspace = true }
texturecraft-texel = { workspace = true }
rayon = { workspace = true }
thiserror = { workspace = true }
+22
View File
@@ -0,0 +1,22 @@
# texturecraft-bake
CPU mesh-map baker: `bake(&BakeRequest, &Progress) -> BakeOutput` turns one texture set's UV layout into float maps (0..1, rows top → bottom), supersampled, padded and deterministic. All requested maps are evaluated in one pass per texel (rayon over rows, no per-texel allocation).
With a high poly (`BakeRequest::high`, every high-definition mesh appended into one), each low-poly sample casts one ray from the cage (`BakeRequest::cage`, same triangles as the low poly) or from `max_frontal` in front of the surface back through it to `max_rear` behind (both relative to the bounding-box diagonal), along normals averaged over hard edges when `average_normals` is on. With `BakeMatch::ByMeshName`, a low-poly part only sees high-poly parts of the same name once `low_suffix` / `high_suffix` are removed (`wheel_low` ↔ `wheel_high`, case-insensitive). Every map but position and world-space direction then reads the high-poly surface that ray found (AO, thickness and bent normals cast against the high poly).
| Map | Meaning | Range |
| --- | --- | --- |
| Ambient occlusion | How open the surface is to the sky (cosine-weighted rays, distance falloff) | 0 occluded … 1 open |
| Bent normals | Mean unoccluded direction of the AO rays, world space | packed ·0.5+0.5 |
| Thickness | Mean distance through the mesh along inward rays, relative to the max distance | 0 thin … 1 thick |
| Curvature | Mean curvature of the position-welded mesh, or (`curvature_from_normal`) the divergence of the baked normal map | 0 concave … 0.5 flat … 1 convex |
| Normal | Tangent-space normal from the high poly (OpenGL, +Y up); flat without one | packed ·0.5+0.5 |
| Height | High-poly offset along the ray, scaled by frontal + rear distance | 0 rear … 0.5 surface … 1 front |
| World normal | Shading normal in world space | packed ·0.5+0.5 |
| Position | Position inside the low-poly bounding box, per axis | 0 … 1 |
| ID | A distinct hue per mesh part (submesh) | RGB 0 … 1 |
| Opacity | 1 where the high poly was found (times its vertex alpha), 0 where the ray missed | 0 … 1 |
| Color map | The high poly's vertex colors (white without) | RGB 0 … 1 |
| World space direction | Facing ratio towards `direction` | 0 away … 0.5 perpendicular … 1 facing |
Uncovered texels beyond the padding get `BakedMap::neutral` values. Benchmark (2K, the 7 default maps, per-map breakdown): `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench`.
+236
View File
@@ -0,0 +1,236 @@
//! # texturecraft-bake
//!
//! CPU mesh-map baking. [`bake`] rasterizes one texture set's UV layout with a supersampled
//! [`UvGBuffer`], evaluates every requested [`BakedMap`] per sample in one pass (rayon over rows,
//! BVH ray casts for the high-poly transfer, AO, bent normals and thickness), box-downsamples,
//! and pads the UV islands with [`DilationMap`]. With a high poly, every map but position and
//! world-space direction reads the high-poly surface found along the cage / frontal-rear ray.
//! Sampling is deterministic, so the same request always gives the same pixels.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
mod maps;
#[cfg(test)]
mod tests;
use std::collections::BTreeMap;
use std::sync::atomic::{AtomicBool, AtomicU32, AtomicU64, Ordering::Relaxed};
use rayon::prelude::*;
use texturecraft_core::{BakeSettings, BakedMap};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Bvh, Mesh, UvGBuffer};
use texturecraft_texel::DilationMap;
/// Largest accepted output resolution (per axis).
pub const MAX_RESOLUTION: u32 = 8192;
/// Largest accepted ray count per texel (AO, thickness).
pub const MAX_RAYS: u32 = 4096;
/// Supersampled texels rasterized at once: bounds the G-buffer at ~200 MB for any resolution × AA.
const STRIP_TEXELS: usize = 1 << 24;
/// Shared progress / cancellation flag of a running bake.
#[derive(Debug, Default)]
pub struct Progress {
/// Basis points, 0..=10_000 (all requested maps done).
pub done: AtomicU32,
pub cancel: AtomicBool,
}
impl Progress {
pub fn new() -> Self {
Self::default()
}
/// Completed fraction, 0..=1.
pub fn fraction(&self) -> f32 {
self.done.load(Relaxed).min(10_000) as f32 / 10_000.0
}
/// Ask the bake to stop; it returns [`BakeError::Cancelled`] at the next row.
pub fn cancel(&self) {
self.cancel.store(true, Relaxed);
}
}
/// A high-poly source mesh (all high-definition meshes appended into one).
#[derive(Clone, Copy, Debug)]
pub struct HighPoly<'a> {
pub mesh: &'a Mesh,
pub bvh: &'a Bvh,
}
/// One texture set to bake.
#[derive(Clone, Copy, Debug)]
pub struct BakeRequest<'a> {
pub mesh: &'a Mesh,
/// BVH of the whole low-poly mesh: every material occludes.
pub bvh: &'a Bvh,
pub material: usize,
pub settings: &'a BakeSettings,
pub high: Option<HighPoly<'a>>,
/// Cage: the low poly inflated (same triangles); transfer rays start on it.
pub cage: Option<&'a Mesh>,
}
/// Baked maps: row-major `resolution × resolution`, `BakedMap::components()` floats per texel,
/// rows top → bottom (y = v·H, as [`UvGBuffer`]).
#[derive(Clone, Debug, PartialEq)]
pub struct BakeOutput {
pub resolution: u32,
pub maps: BTreeMap<BakedMap, Vec<f32>>,
}
#[derive(Debug, thiserror::Error)]
pub enum BakeError {
#[error("bake cancelled")]
Cancelled,
#[error("invalid bake request: {0}")]
Invalid(String),
}
fn validate(req: &BakeRequest) -> Result<(), BakeError> {
let s = req.settings;
let invalid = |m: String| Err(BakeError::Invalid(m));
if s.resolution == 0 || s.resolution > MAX_RESOLUTION {
return invalid(format!("resolution {} is not in 1..={MAX_RESOLUTION}", s.resolution));
}
if ![1, 2, 4, 8].contains(&s.antialiasing) {
return invalid(format!("antialiasing {} is not 1, 2, 4 or 8", s.antialiasing));
}
if s.rays == 0 || s.rays > MAX_RAYS {
return invalid(format!("ray count {} is not in 1..={MAX_RAYS}", s.rays));
}
if !(s.max_distance.is_finite() && s.max_distance > 0.0) {
return invalid(format!("max distance {} must be positive", s.max_distance));
}
if !s.curvature_strength.is_finite() {
return invalid("curvature strength is not finite".into());
}
if !(s.direction.iter().all(|c| c.is_finite()) && s.direction.iter().any(|c| *c != 0.0)) {
return invalid(format!("direction {:?} must be finite and non-zero", s.direction));
}
if !(s.max_frontal.is_finite() && s.max_frontal >= 0.0 && s.max_rear.is_finite() && s.max_rear >= 0.0) {
return invalid(format!("frontal/rear distances {}/{} must be finite and ≥ 0", s.max_frontal, s.max_rear));
}
req.mesh.validate().map_err(|e| BakeError::Invalid(e.to_string()))?;
if req.material >= req.mesh.materials.len().max(1) {
return invalid(format!("material {} out of range ({} materials)", req.material, req.mesh.materials.len()));
}
if let Some(h) = &req.high {
h.mesh.validate().map_err(|e| BakeError::Invalid(format!("high poly: {e}")))?;
}
if let Some(c) = req.cage {
c.validate().map_err(|e| BakeError::Invalid(format!("cage: {e}")))?;
if c.indices.len() != req.mesh.indices.len() {
return invalid(format!("the cage has {} triangles, the low poly {}", c.triangle_count(), req.mesh.triangle_count()));
}
}
Ok(())
}
/// `vec![value; n]` that reports allocation failure instead of aborting.
fn alloc<T: Clone>(n: usize, value: T) -> Result<Vec<T>, BakeError> {
let mut v = Vec::new();
v.try_reserve_exact(n).map_err(|_| BakeError::Invalid(format!("out of memory allocating {n} texels")))?;
v.resize(n, value);
Ok(v)
}
/// Bake the maps in `req.settings.maps` for one material of the low-poly mesh.
pub fn bake(req: &BakeRequest, progress: &Progress) -> Result<BakeOutput, BakeError> {
bake_in_strips(req, progress, STRIP_TEXELS)
}
fn bake_in_strips(req: &BakeRequest, progress: &Progress, strip_texels: usize) -> Result<BakeOutput, BakeError> {
validate(req)?;
let s = req.settings;
let (res, aa) = (s.resolution as usize, s.antialiasing as usize);
let ctx = maps::Ctx::new(req)?;
progress.done.store(0, Relaxed);
// Curvature from the normal map needs the normal map: baked alongside when not requested.
let from_normal = s.curvature_from_normal && s.maps.contains(&BakedMap::Curvature);
let mut maps: Vec<BakedMap> = s.maps.iter().copied().collect();
if from_normal && !maps.contains(&BakedMap::Normal) {
maps.push(BakedMap::Normal);
}
let mut bufs = maps.iter().map(|m| alloc(res * res * m.components(), 0.0f32)).collect::<Result<Vec<_>, _>>()?;
let mut covered = alloc(res * res, false)?;
let total = res.max(1) as u64;
let rows_done = AtomicU64::new(0);
let strip_err = || BakeError::Invalid("strip out of range".into());
// Rasterize in horizontal strips of the supersampled image: a strip's G-buffer is built from
// UVs shifted so that y = v*H - strip_top, which keeps memory bounded at 8K x 8 AA.
let sw = res * aa;
let strip_rows = (strip_texels / (sw * aa)).max(1).min(res);
let mut strip_mesh = Mesh { indices: req.mesh.indices.clone(), submeshes: req.mesh.submeshes.clone(), ..Mesh::default() };
for y0 in (0..res).step_by(strip_rows) {
let rows = strip_rows.min(res - y0);
let (sy0, sh) = (y0 * aa, rows * aa);
strip_mesh.uvs = req.mesh.uvs.iter().map(|uv| Vec2::new(uv.x, (uv.y * sw as f32 - sy0 as f32) / sh as f32)).collect();
let g = UvGBuffer::new(&strip_mesh, req.material, sw as u32, sh as u32);
let subsamples = |r: usize, x: usize| (0..aa * aa).map(move |k| (r * aa + k / aa) * sw + x * aa + k % aa);
// Per output row: its coverage and its slice of every map.
let cov = covered.get_mut(y0 * res..(y0 + rows) * res).ok_or_else(strip_err)?;
let mut out_rows: Vec<(&mut [bool], Vec<&mut [f32]>)> = cov.chunks_mut(res).map(|c| (c, Vec::with_capacity(maps.len()))).collect();
for (m, data) in maps.iter().zip(bufs.iter_mut()) {
let comps = m.components();
let strip = data.get_mut(y0 * res * comps..(y0 + rows) * res * comps).ok_or_else(strip_err)?;
for ((_, row), chunk) in out_rows.iter_mut().zip(strip.chunks_mut(res * comps)) {
row.push(chunk);
}
}
out_rows.par_iter_mut().enumerate().try_for_each(|(r, (cov, row))| {
if progress.cancel.load(Relaxed) {
return Err(BakeError::Cancelled);
}
let mut sample = [[0.0f32; 3]; BakedMap::ALL.len()];
for x in 0..res {
let mut acc = [[0.0f32; 3]; BakedMap::ALL.len()];
let mut n = 0u32;
for i in subsamples(r, x) {
let (Some(surf), Some(&bary)) = (g.surface(req.mesh, i), g.bary.get(i)) else { continue };
// Seed by the global supersample index so strips don't change the noise.
ctx.evaluate(&maps, &surf, bary, (sy0 * sw + i) as u64, &mut sample);
for (a, v) in acc.iter_mut().zip(&sample) {
a.iter_mut().zip(v).for_each(|(a, v)| *a += v);
}
n += 1;
}
if let Some(c) = cov.get_mut(x) {
*c = n > 0;
}
for ((m, dst), a) in maps.iter().zip(row.iter_mut()).zip(&acc) {
let comps = m.components();
let mean = a.map(|a| a / n.max(1) as f32);
let v = if n == 0 || mean.iter().any(|v| !v.is_finite()) { m.neutral() } else { mean };
if let Some(d) = dst.get_mut(x * comps..(x + 1) * comps) {
d.iter_mut().zip(v).for_each(|(d, v)| *d = v);
}
}
}
let d = rows_done.fetch_add(1, Relaxed) + 1;
progress.done.fetch_max((d.saturating_mul(10_000) / total).min(10_000) as u32, Relaxed);
Ok(())
})?;
}
let mut out: BTreeMap<BakedMap, Vec<f32>> = maps.into_iter().zip(bufs).collect();
if from_normal {
let normal = if s.maps.contains(&BakedMap::Normal) { out.get(&BakedMap::Normal).cloned() } else { out.remove(&BakedMap::Normal) };
if let (Some(normal), Some(curv)) = (normal, out.get_mut(&BakedMap::Curvature)) {
maps::curvature_from_normal(&normal, &covered, res, s.curvature_strength, curv);
}
}
if s.dilation > 0 {
let pad = DilationMap::new(&covered, s.resolution, s.resolution, Some(s.dilation));
for (m, data) in out.iter_mut() {
pad.apply(data, m.components());
}
}
progress.done.store(10_000, Relaxed);
Ok(BakeOutput { resolution: s.resolution, maps: out })
}
+356
View File
@@ -0,0 +1,356 @@
//! Per-sample evaluation of every baked map.
use std::collections::HashMap;
use std::f32::consts::TAU;
use std::ops::{Add, Mul};
use texturecraft_core::{BakeMatch, BakeSettings, BakedMap};
use texturecraft_geom::glam::{Vec3, Vec4};
use texturecraft_geom::{Bvh, Mesh, Surface, surface_at};
use crate::{BakeError, BakeRequest};
/// Triangles that belong to no submesh (never matched by name).
const NO_KEY: u32 = u32::MAX;
/// A mesh the bakers sample: the low poly, or the high poly detail is transferred from.
struct Source<'a> {
mesh: &'a Mesh,
bvh: &'a Bvh,
/// Per-vertex curvature offset from 0.5 (empty unless mesh curvature is baked).
curvature: Vec<f32>,
/// Submesh (part) index of each triangle.
part: Vec<u32>,
/// Match key of each triangle ([`BakeMatch::ByMeshName`] only, else empty).
key: Vec<u32>,
}
impl<'a> Source<'a> {
fn new(mesh: &'a Mesh, bvh: &'a Bvh, s: &BakeSettings, diag: f32, suffix: &str, keys: &mut HashMap<String, u32>) -> Source<'a> {
let mesh_curvature = s.maps.contains(&BakedMap::Curvature) && !s.curvature_from_normal;
let tris = mesh.triangle_count();
let mut part = vec![NO_KEY; tris];
for (i, sm) in mesh.submeshes.iter().enumerate() {
let (a, b) = ((sm.start / 3) as usize, (sm.start.saturating_add(sm.count) / 3) as usize);
part.get_mut(a.min(b)..b.min(tris)).unwrap_or_default().fill(i as u32);
}
let key = match s.matching {
BakeMatch::Always => Vec::new(),
BakeMatch::ByMeshName => {
let ids: Vec<u32> = mesh.submeshes.iter().map(|sm| match_key(&sm.name, suffix, keys)).collect();
part.iter().map(|p| ids.get(*p as usize).copied().unwrap_or(NO_KEY)).collect()
}
};
Source { mesh, bvh, curvature: if mesh_curvature { vertex_curvature(mesh, diag, s.curvature_strength) } else { Vec::new() }, part, key }
}
fn curvature(&self, s: &Surface, bary: [f32; 2]) -> f32 {
(0.5 + interpolate(self.mesh, &self.curvature, s.tri, bary).unwrap_or(0.0)).clamp(0.0, 1.0)
}
fn color(&self, s: &Surface, bary: [f32; 2]) -> Vec4 {
interpolate(self.mesh, &self.mesh.colors, s.tri, bary).unwrap_or(Vec4::ONE)
}
}
/// The part name without its low / high suffix (case-insensitive), as a shared id.
fn match_key(name: &str, suffix: &str, keys: &mut HashMap<String, u32>) -> u32 {
let name = name.trim().to_lowercase();
let suffix = suffix.trim().to_lowercase();
let base = name.strip_suffix(suffix.as_str()).filter(|_| !suffix.is_empty()).unwrap_or(&name).to_string();
let next = keys.len() as u32;
*keys.entry(base).or_insert(next)
}
/// Barycentric interpolation of a per-vertex attribute over triangle `tri`.
fn interpolate<T: Copy + Mul<f32, Output = T> + Add<Output = T>>(mesh: &Mesh, v: &[T], tri: u32, [b1, b2]: [f32; 2]) -> Option<T> {
let [a, b, c] = mesh.tri(tri as usize)?;
Some(*v.get(a)? * (1.0 - b1 - b2) + *v.get(b)? * b1 + *v.get(c)? * b2)
}
/// The high-poly surface found for a low-poly sample, and where along the ray.
struct Transfer {
surf: Surface,
bary: [f32; 2],
/// Hit distance from the ray origin, and the origin's distance in front of the low poly.
t: f32,
front: f32,
}
/// Everything a sample needs, computed once per bake.
pub(crate) struct Ctx<'a> {
low: Source<'a>,
high: Option<Source<'a>>,
cage: Option<&'a Mesh>,
/// Normals averaged over coincident vertices (rays don't split at hard edges); empty when off.
ray_normals: Vec<Vec3>,
lo: Vec3,
extent: Vec3,
/// Ray offset off the surface.
eps: f32,
/// AO / thickness ray length.
dmax: f32,
frontal: f32,
rear: f32,
rays: u32,
direction: Vec3,
curvature_from_normal: bool,
occlusion: bool,
}
impl<'a> Ctx<'a> {
pub(crate) fn new(req: &BakeRequest<'a>) -> Result<Ctx<'a>, BakeError> {
let s = req.settings;
let (lo, hi) = req.mesh.bounds();
let diag = (hi - lo).length().max(1e-6);
if !diag.is_finite() {
return Err(BakeError::Invalid("mesh bounds are too large".into()));
}
let mut keys = HashMap::new();
let low = Source::new(req.mesh, req.bvh, s, diag, &s.low_suffix, &mut keys);
let high = req.high.map(|h| Source::new(h.mesh, h.bvh, s, diag, &s.high_suffix, &mut keys));
let ray_normals = match s.average_normals && high.is_some() {
true => {
let (weld, _, nrm) = welded(req.mesh, diag);
weld.iter().map(|w| nrm.get(*w as usize).copied().unwrap_or(Vec3::Y)).collect()
}
false => Vec::new(),
};
Ok(Ctx {
low,
high,
cage: req.cage,
ray_normals,
lo,
extent: hi - lo,
eps: 1e-4 * diag,
dmax: s.max_distance * diag,
frontal: s.max_frontal * diag,
rear: s.max_rear * diag,
rays: s.rays,
direction: Vec3::from(s.direction).try_normalize().unwrap_or(Vec3::Y),
curvature_from_normal: s.curvature_from_normal,
occlusion: s.maps.contains(&BakedMap::AmbientOcclusion) || s.maps.contains(&BakedMap::BentNormal),
})
}
/// Every map of `maps` at one low-poly surface sample, into `out` (scalars fill all three).
pub(crate) fn evaluate(&self, maps: &[BakedMap], s: &Surface, bary: [f32; 2], seed: u64, out: &mut [[f32; 3]]) {
let transfer = self.high.as_ref().and_then(|h| self.transfer(h, s, bary));
// The surface the bakers read: the high poly where a ray found it, else the low poly.
let (src, surf, sb) = match (&self.high, &transfer) {
(Some(h), Some(tr)) => (h, &tr.surf, tr.bary),
_ => (&self.low, s, bary),
};
let missed = self.high.is_some() && transfer.is_none();
let (ao, bent) = if self.occlusion { self.occlusion(src, surf, seed) } else { (1.0, surf.nrm) };
for (&map, o) in maps.iter().zip(out.iter_mut()) {
*o = match map {
BakedMap::AmbientOcclusion => [ao; 3],
BakedMap::BentNormal => pack(bent),
BakedMap::Thickness => [self.thickness(src, surf, seed); 3],
BakedMap::Curvature if self.curvature_from_normal => [0.5; 3],
BakedMap::Curvature => [src.curvature(surf, sb); 3],
BakedMap::WorldNormal => pack(surf.nrm),
BakedMap::Position => ((surf.pos - self.lo) / self.extent.max(Vec3::splat(1e-20))).clamp(Vec3::ZERO, Vec3::ONE).to_array(),
BakedMap::Id => material_color(src.part.get(surf.tri as usize).copied().unwrap_or(0) as usize),
BakedMap::Normal => transfer.as_ref().map_or(map.neutral(), |tr| tangent_normal(s, tr.surf.nrm)),
BakedMap::Height => [transfer.as_ref().map_or(0.5, |tr| (0.5 + (tr.front - tr.t) / (tr.front + self.rear)).clamp(0.0, 1.0)); 3],
BakedMap::Opacity if missed => [0.0; 3],
BakedMap::Opacity => [src.color(surf, sb).w; 3],
BakedMap::ColorMap if missed => map.neutral(),
BakedMap::ColorMap => src.color(surf, sb).truncate().to_array(),
BakedMap::WorldDirection => [surf.nrm.dot(self.direction) * 0.5 + 0.5; 3],
};
}
}
/// Cast from the cage (or `frontal` in front of the low poly) back through it to `rear`
/// behind, and take the closest high-poly surface (of the matching part).
fn transfer(&self, high: &Source, s: &Surface, bary: [f32; 2]) -> Option<Transfer> {
let n = interpolate(self.low.mesh, &self.ray_normals, s.tri, bary).and_then(Vec3::try_normalize).unwrap_or(s.nrm);
let cage = self.cage.and_then(|c| interpolate(c, &c.positions, s.tri, bary)).map(|c| s.pos - c).filter(|v| v.length() > self.eps);
let (o, d, front) = match cage {
Some(v) => (s.pos - v, v.normalize(), v.length()),
None => (s.pos + n * self.frontal, -n, self.frontal),
};
let tmax = front + self.rear;
let hit = match self.low.key.get(s.tri as usize) {
Some(&k) => high.bvh.closest_filtered(o, d, tmax, &|t| k != NO_KEY && high.key.get(t as usize) == Some(&k))?,
None => high.bvh.closest(o, d, tmax)?,
};
let surf = surface_at(high.mesh, hit.tri, hit.u, hit.v)?;
Some(Transfer { surf, bary: [hit.u, hit.v], t: hit.t, front })
}
/// Geometric normal flipped to the side of the shading normal.
fn geo(s: &Surface) -> Vec3 {
if s.geo_nrm.dot(s.nrm) < 0.0 { -s.geo_nrm } else { s.geo_nrm }
}
/// Call `f` with cosine-weighted directions around `axis` (Hammersley points with a
/// per-sample Cranley–Patterson rotation), skipping those below the plane of `geo`.
fn directions(&self, axis: Vec3, geo: Vec3, seed: u64, mut f: impl FnMut(Vec3)) {
let h = splitmix64(seed);
let (r1, r2) = ((h >> 40) as f32 / (1u64 << 24) as f32, ((h >> 16) & 0xff_ffff) as f32 / (1u64 << 24) as f32);
let (t, b) = axis.any_orthonormal_pair();
for i in 0..self.rays {
let u1 = (i as f32 / self.rays as f32 + r1).fract();
let u2 = (i.reverse_bits() as f32 / 4_294_967_296.0 + r2).fract();
let (phi, r) = (TAU * u1, u2.sqrt());
let d = t * (r * phi.cos()) + b * (r * phi.sin()) + axis * (1.0 - u2).max(0.0).sqrt();
if d.dot(geo) > 0.0 {
f(d);
}
}
}
/// Ambient occlusion (1 = open, 0 = fully occluded) and the bent normal (mean unoccluded
/// direction), from one set of rays.
fn occlusion(&self, src: &Source, s: &Surface, seed: u64) -> (f32, Vec3) {
let geo = Self::geo(s);
let o = s.pos + geo * self.eps;
let (mut occ, mut bent, mut n) = (0.0f32, Vec3::ZERO, 0u32);
self.directions(s.nrm, geo, seed, |d| {
let v = src.bvh.closest(o, d, self.dmax).map_or(0.0, |h| 1.0 - (h.t / self.dmax).powi(2));
occ += v;
bent += d * (1.0 - v);
n += 1;
});
let ao = if n == 0 { 1.0 } else { (1.0 - occ / n as f32).clamp(0.0, 1.0) };
(ao, bent.try_normalize().unwrap_or(s.nrm))
}
/// Mean distance through the mesh along inward rays, relative to the max distance (1 = thick).
fn thickness(&self, src: &Source, s: &Surface, seed: u64) -> f32 {
let geo = Self::geo(s);
let o = s.pos - geo * self.eps;
let (mut sum, mut n) = (0.0f32, 0u32);
self.directions(-s.nrm, -geo, seed, |d| {
sum += src.bvh.closest(o, d, self.dmax).map_or(self.dmax, |h| h.t);
n += 1;
});
if n == 0 { 1.0 } else { (sum / n as f32 / self.dmax).clamp(0.0, 1.0) }
}
}
/// A unit vector packed to 0..1.
fn pack(v: Vec3) -> [f32; 3] {
(v * 0.5 + 0.5).clamp(Vec3::ZERO, Vec3::ONE).to_array()
}
/// `n` in the tangent space of low-poly sample `s` (OpenGL: +Y up the image), packed to 0..1.
fn tangent_normal(s: &Surface, n: Vec3) -> [f32; 3] {
let z = s.nrm;
let t = (s.tangent.truncate() - z * z.dot(s.tangent.truncate())).try_normalize().unwrap_or_else(|| z.any_orthonormal_vector());
let b = z.cross(t) * s.tangent.w;
pack(Vec3::new(t.dot(n), b.dot(n), z.dot(n)))
}
/// Curvature from a baked tangent-space normal map: the divergence of its XY over `radius`
/// texels (convex = above 0.5). Writes covered texels of `out` (one float per texel).
pub(crate) fn curvature_from_normal(normal: &[f32], covered: &[bool], res: usize, strength: f32, out: &mut [f32]) {
use rayon::prelude::*;
let r = (res / 512).max(1);
let n = |x: usize, y: usize, c: usize, fallback: f32| match covered.get(y * res + x) {
Some(true) => normal.get((y * res + x) * 3 + c).copied().unwrap_or(fallback),
_ => fallback,
};
out.par_chunks_mut(res).enumerate().for_each(|(y, row)| {
for (x, v) in row.iter_mut().enumerate() {
if covered.get(y * res + x) != Some(&true) {
continue;
}
let (cx, cy) = (n(x, y, 0, 0.5), n(x, y, 1, 0.5));
let (l, r_) = (n(x.saturating_sub(r), y, 0, cx), if x + r < res { n(x + r, y, 0, cx) } else { cx });
let (u, d) = (n(x, y.saturating_sub(r), 1, cy), if y + r < res { n(x, y + r, 1, cy) } else { cy });
// Image rows run down while +Y (OpenGL) points up: convex bumps tilt +Y above.
*v = (0.5 + strength * ((r_ - l) + (u - d))).clamp(0.0, 1.0);
}
});
}
/// Position-welded copy of `mesh` (UV seams and hard edges share neighbours): the weld id of
/// every vertex, welded positions and their averaged normals.
fn welded(mesh: &Mesh, diag: f32) -> (Vec<u32>, Vec<Vec3>, Vec<Vec3>) {
let q = diag * 1e-5;
let mut ids: HashMap<[i64; 3], u32> = HashMap::new();
let (mut pos, mut nrm) = (Vec::new(), Vec::<Vec3>::new());
let weld: Vec<u32> = mesh
.positions
.iter()
.zip(&mesh.normals)
.map(|(p, n)| {
let key = [p.x, p.y, p.z].map(|c| (c / q).round() as i64);
let id = *ids.entry(key).or_insert_with(|| {
pos.push(*p);
nrm.push(Vec3::ZERO);
(pos.len() - 1) as u32
});
if let Some(acc) = nrm.get_mut(id as usize) {
*acc += *n;
}
id
})
.collect();
let nrm = nrm.into_iter().map(|n| n.try_normalize().unwrap_or(Vec3::ZERO)).collect();
(weld, pos, nrm)
}
/// Per-vertex curvature offset `−k · avg_edge · strength`, where `k` is the mean of
/// `n·(p_j − p_i)/|p_j − p_i|²` over the 1-ring of the welded mesh. Convex edges give a
/// positive offset.
fn vertex_curvature(mesh: &Mesh, diag: f32, strength: f32) -> Vec<f32> {
let q = diag * 1e-5;
let (weld, pos, nrm) = welded(mesh, diag);
let (mut ksum, mut kcnt) = (vec![0.0f32; pos.len()], vec![0u32; pos.len()]);
let (mut edge_sum, mut edge_cnt) = (0.0f64, 0u64);
for t in mesh.indices.chunks_exact(3) {
for (a, b) in [(0, 1), (1, 2), (2, 0), (1, 0), (2, 1), (0, 2)] {
let (Some(&wa), Some(&wb)) = (t.get(a).and_then(|v| weld.get(*v as usize)), t.get(b).and_then(|v| weld.get(*v as usize))) else { continue };
let (Some(pa), Some(pb), Some(na)) = (pos.get(wa as usize), pos.get(wb as usize), nrm.get(wa as usize)) else { continue };
let d = *pb - *pa;
let l2 = d.length_squared();
if wa == wb || l2 <= q * q {
continue;
}
if let (Some(k), Some(c)) = (ksum.get_mut(wa as usize), kcnt.get_mut(wa as usize)) {
*k += na.dot(d) / l2;
*c += 1;
}
edge_sum += f64::from(l2.sqrt());
edge_cnt += 1;
}
}
let scale = (edge_sum / edge_cnt.max(1) as f64) as f32 * strength;
weld.iter()
.map(|w| {
let i = *w as usize;
let k = ksum.get(i).copied().unwrap_or(0.0) / kcnt.get(i).copied().unwrap_or(0).max(1) as f32;
if k.is_finite() { -k * scale } else { 0.0 }
})
.collect()
}
/// A well-separated hue per part (golden-ratio steps around the HSV wheel).
fn material_color(part: usize) -> [f32; 3] {
let h = ((part as f64 * 0.618_033_988_75 + 0.05).fract() * 6.0) as f32;
let (s, v) = (0.7f32, 0.95f32);
let f = h.fract();
let (p, q, t) = (v * (1.0 - s), v * (1.0 - s * f), v * (1.0 - s * (1.0 - f)));
match h as u32 {
0 => [v, t, p],
1 => [q, v, p],
2 => [p, v, t],
3 => [p, q, v],
4 => [t, p, v],
_ => [v, p, q],
}
}
fn splitmix64(x: u64) -> u64 {
let mut z = x.wrapping_add(0x9e37_79b9_7f4a_7c15);
z = (z ^ (z >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
z = (z ^ (z >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
z ^ (z >> 31)
}
+423
View File
@@ -0,0 +1,423 @@
use std::sync::atomic::Ordering::Relaxed;
use texturecraft_core::BakeMatch;
use texturecraft_geom::glam::{Vec2, Vec3, Vec4};
use texturecraft_geom::primitives;
use super::*;
fn settings(res: u32, maps: &[BakedMap]) -> BakeSettings {
BakeSettings { resolution: res, dilation: 0, rays: 64, maps: maps.iter().copied().collect(), ..BakeSettings::default() }
}
fn run(mesh: &Mesh, s: &BakeSettings) -> Result<BakeOutput, BakeError> {
let bvh = Bvh::new(mesh);
bake(&BakeRequest { mesh, bvh: &bvh, material: 0, settings: s, high: None, cage: None }, &Progress::new())
}
/// Values of `map` (first component) at texels the UV layout covers, with their surface positions.
fn covered_values(mesh: &Mesh, out: &BakeOutput, map: BakedMap) -> Vec<(Vec3, f32)> {
let res = out.resolution;
let g = UvGBuffer::new(mesh, 0, res, res);
let data = &out.maps[&map];
(0..(res * res) as usize).filter_map(|i| g.surface(mesh, i).map(|s| (s.pos, data[i * map.components()]))).collect()
}
fn mean(v: impl Iterator<Item = f32>) -> f32 {
let (s, n) = v.fold((0.0, 0), |(s, n), x| (s + x, n + 1));
assert!(n > 0, "no samples");
s / n as f32
}
fn quad() -> Mesh {
Mesh::from_parts(
vec![Vec3::new(-1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(-1.0, 0.0, 1.0)],
Some(vec![Vec3::Y; 4]),
vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(0.0, 1.0)],
vec![0, 2, 1, 0, 3, 2],
"Quad",
)
.unwrap()
}
#[test]
fn open_quad_is_unoccluded() {
let m = quad();
let out = run(&m, &settings(32, &[BakedMap::AmbientOcclusion])).unwrap();
let ao = covered_values(&m, &out, BakedMap::AmbientOcclusion);
assert!(ao.iter().all(|(_, v)| *v > 0.999), "{:?}", ao.iter().map(|v| v.1).fold(1.0f32, f32::min));
}
#[test]
fn inside_of_a_closed_box_is_occluded() {
let mut m = primitives::cube(2.0);
for t in m.indices.chunks_exact_mut(3) {
t.swap(1, 2);
}
for n in &mut m.normals {
*n = -*n;
}
m.compute_tangents();
let s = BakeSettings { max_distance: 4.0, ..settings(48, &[BakedMap::AmbientOcclusion]) };
let out = run(&m, &s).unwrap();
let ao = mean(covered_values(&m, &out, BakedMap::AmbientOcclusion).into_iter().map(|v| v.1));
assert!(ao < 0.3, "{ao}");
}
#[test]
fn thin_slab_is_thinner_than_a_block() {
let thick = |m: &Mesh| mean(covered_values(m, &run(m, &settings(48, &[BakedMap::Thickness])).unwrap(), BakedMap::Thickness).into_iter().map(|v| v.1));
let slab = thick(&primitives::rounded_box(Vec3::new(1.0, 0.05, 1.0), 0.0));
let block = thick(&primitives::cube(2.0));
assert!(slab < 0.4 && block > 0.6, "slab {slab}, block {block}");
}
#[test]
fn sphere_curvature_is_nearly_constant() {
let m = primitives::sphere(1.0, 64, 32);
let out = run(&m, &settings(64, &[BakedMap::Curvature])).unwrap();
let c: Vec<f32> = covered_values(&m, &out, BakedMap::Curvature).into_iter().map(|v| v.1).collect();
let (lo, hi) = c.iter().fold((1.0f32, 0.0f32), |(lo, hi), v| (lo.min(*v), hi.max(*v)));
assert!(lo >= 0.5 && hi < 0.6 && hi - lo < 0.03, "{lo}..{hi}");
}
/// Bevel / edge texels (two coordinates near the half extent) are convex-bright; face centres
/// stay mid-grey.
fn check_box_curvature(m: &Mesh, edge: f32) {
let s = BakeSettings { dilation: 4, ..settings(128, &[BakedMap::Curvature]) };
let c = covered_values(m, &run(m, &s).unwrap(), BakedMap::Curvature);
let near = |p: Vec3, t: f32| p.abs().to_array().iter().filter(|c| **c > t).count();
let edges: Vec<f32> = c.iter().filter(|(p, _)| near(*p, edge) >= 2).map(|v| v.1).collect();
let faces: Vec<f32> = c.iter().filter(|(p, _)| near(*p, 0.5) == 1).map(|v| v.1).collect();
assert!(!edges.is_empty() && !faces.is_empty());
let min_edge = edges.iter().copied().fold(1.0, f32::min);
assert!(min_edge > 0.55, "edge min {min_edge}");
assert!(faces.iter().all(|v| (0.45..=0.55).contains(v)), "face {:?}", faces.iter().copied().fold((1.0f32, 0.0f32), |(a, b), v| (a.min(v), b.max(v))));
}
#[test]
fn rounded_box_bevels_are_convex() {
check_box_curvature(&primitives::rounded_box(Vec3::ONE, 0.15), 0.9);
}
#[test]
fn cube_edges_are_convex() {
check_box_curvature(&primitives::cube(2.0), 0.97);
}
#[test]
fn two_runs_are_identical_and_sized() {
let m = primitives::material_ball();
let s = BakeSettings { antialiasing: 2, dilation: 2, rays: 8, maps: BakedMap::ALL.into_iter().collect(), ..settings(40, &[]) };
let a = run(&m, &s).unwrap();
let b = run(&m, &s).unwrap();
assert_eq!(a, b);
assert_eq!(a.maps.len(), BakedMap::ALL.len());
for (map, data) in &a.maps {
assert_eq!(data.len(), 40 * 40 * map.components(), "{map:?}");
assert!(data.iter().all(|v| v.is_finite() && (0.0..=1.0).contains(v)), "{map:?}");
}
}
#[test]
fn strips_match_a_single_pass() {
let m = primitives::material_ball();
let bvh = Bvh::new(&m);
let s = BakeSettings { antialiasing: 2, rays: 4, maps: BakedMap::ALL.into_iter().collect(), ..settings(64, &[]) };
let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None };
let whole = bake(&req, &Progress::new()).unwrap();
// 128 × 2 supersampled texels per strip = 1 output row: 64 strips.
let strips = bake_in_strips(&req, &Progress::new(), 128 * 2).unwrap();
for (map, a) in &whole.maps {
let b = &strips.maps[map];
let off = a.iter().zip(b).filter(|(a, b)| (*a - *b).abs() > 1e-3).count();
assert!(off * 200 < a.len(), "{map:?}: {off} of {} differ", a.len());
}
}
#[test]
fn cancel_and_progress() {
let m = primitives::sphere(1.0, 16, 8);
let bvh = Bvh::new(&m);
let s = settings(16, &[BakedMap::AmbientOcclusion, BakedMap::Position]);
let req = BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None };
let p = Progress::new();
p.cancel();
assert!(matches!(bake(&req, &p), Err(BakeError::Cancelled)));
let p = Progress::new();
bake(&req, &p).unwrap();
assert_eq!(p.done.load(Relaxed), 10_000);
assert_eq!(p.fraction(), 1.0);
}
#[test]
fn invalid_requests_are_errors() {
let m = quad();
let ok = settings(8, &[BakedMap::AmbientOcclusion]);
let bad = [
BakeSettings { resolution: 0, ..ok.clone() },
BakeSettings { resolution: 8193, ..ok.clone() },
BakeSettings { antialiasing: 3, ..ok.clone() },
BakeSettings { antialiasing: 0, ..ok.clone() },
BakeSettings { rays: 0, ..ok.clone() },
BakeSettings { max_distance: f32::NAN, ..ok.clone() },
BakeSettings { max_distance: 0.0, ..ok.clone() },
BakeSettings { max_rear: -1.0, ..ok.clone() },
BakeSettings { curvature_strength: f32::INFINITY, ..ok.clone() },
];
for s in &bad {
assert!(matches!(run(&m, s), Err(BakeError::Invalid(_))), "{s:?}");
}
let bvh = Bvh::new(&m);
let req = |mesh: &Mesh, material| bake(&BakeRequest { mesh, bvh: &bvh, material, settings: &ok, high: None, cage: None }, &Progress::new());
assert!(matches!(req(&m, 1), Err(BakeError::Invalid(_))));
let mut broken = m.clone();
broken.indices[0] = 99;
assert!(matches!(req(&broken, 0), Err(BakeError::Invalid(_))));
let mut nan = m.clone();
nan.positions[0].x = f32::NAN;
assert!(matches!(req(&nan, 0), Err(BakeError::Invalid(_))));
// An empty mesh bakes to neutral values.
let empty = Mesh { materials: vec!["m".into()], ..Mesh::default() };
let out = req(&empty, 0).unwrap();
assert!(out.maps[&BakedMap::AmbientOcclusion].iter().all(|v| *v == 1.0));
}
#[test]
fn neutral_values_and_padding() {
// The quad covers only the left half of UV space.
let mut m = quad();
for uv in &mut m.uvs {
uv.x *= 0.5;
}
let maps = [BakedMap::AmbientOcclusion, BakedMap::Curvature, BakedMap::Thickness, BakedMap::Normal, BakedMap::Position];
let out = run(&m, &BakeSettings { dilation: 2, ..settings(16, &maps) }).unwrap();
let pos = &out.maps[&BakedMap::Position];
let at = |x: usize, y: usize| &pos[(y * 16 + x) * 3..(y * 16 + x) * 3 + 3];
assert_eq!(at(9, 5)[0], at(7, 5)[0], "padded texel copies a texel of the last covered column");
assert_eq!(at(12, 5), [0.0, 0.0, 0.0], "beyond the padding");
assert_eq!(out.maps[&BakedMap::AmbientOcclusion][5 * 16 + 12], 1.0);
assert_eq!(out.maps[&BakedMap::Curvature][5 * 16 + 12], 0.5);
assert_eq!(out.maps[&BakedMap::Thickness][5 * 16 + 12], 1.0);
assert_eq!(&out.maps[&BakedMap::Normal][(5 * 16 + 12) * 3..(5 * 16 + 12) * 3 + 3], [0.5, 0.5, 1.0]);
}
#[test]
fn normal_and_height_transfer_from_a_high_poly() {
let low = quad();
let mut high = quad();
for p in &mut high.positions {
p.y += 0.005;
}
let tilt = Vec3::new(0.3, 1.0, 0.0).normalize();
high.normals = vec![tilt; 4];
high.compute_tangents();
let (lb, hb) = (Bvh::new(&low), Bvh::new(&high));
let s = settings(16, &[BakedMap::Normal, BakedMap::Height]);
let out =
bake(&BakeRequest { mesh: &low, bvh: &lb, material: 0, settings: &s, high: Some(HighPoly { mesh: &high, bvh: &hb }), cage: None }, &Progress::new())
.unwrap();
let i = 8 * 16 + 8;
let n = &out.maps[&BakedMap::Normal][i * 3..i * 3 + 3];
// Tangent = +X (u), bitangent = −Z (up the image), normal = +Y.
assert!((n[0] - (0.5 + 0.5 * tilt.x)).abs() < 1e-3 && (n[1] - 0.5).abs() < 1e-3 && (n[2] - (0.5 + 0.5 * tilt.y)).abs() < 1e-3, "{n:?}");
let diag = 8.0f32.sqrt();
let expected = 0.5 + 0.005 / (0.02 * diag);
assert!((out.maps[&BakedMap::Height][i] - expected).abs() < 1e-3, "{}", out.maps[&BakedMap::Height][i]);
// Without a high poly both maps are flat.
let flat = run(&low, &s).unwrap();
assert_eq!(&flat.maps[&BakedMap::Normal][i * 3..i * 3 + 3], [0.5, 0.5, 1.0]);
assert_eq!(flat.maps[&BakedMap::Height][i], 0.5);
}
fn transfer(low: &Mesh, high: &Mesh, cage: Option<&Mesh>, s: &BakeSettings) -> Result<BakeOutput, BakeError> {
let (lb, hb) = (Bvh::new(low), Bvh::new(high));
bake(&BakeRequest { mesh: low, bvh: &lb, material: 0, settings: s, high: Some(HighPoly { mesh: high, bvh: &hb }), cage }, &Progress::new())
}
/// Texel (x, y) of a `res`² bake of [`quad`] sits over world (2u − 1, 0, 2v − 1).
fn quad_texel(res: u32, x: f32, z: f32) -> usize {
let t = |c: f32| (((c + 1.0) * 0.5 * res as f32) as usize).min(res as usize - 1);
t(z) * res as usize + t(x)
}
/// [`quad`]'s footprint with a smooth bump `h · exp(−r²/σ²)`.
fn bumped(h: f32, sigma: f32) -> Mesh {
let mut m = primitives::plane(2.0, 128);
for p in &mut m.positions {
p.y = h * (-(p.x * p.x + p.z * p.z) / (sigma * sigma)).exp();
}
m.compute_normals();
m.compute_tangents();
m
}
#[test]
fn bump_tilts_the_baked_normal() {
let (h, sigma) = (0.1f32, 0.4f32);
let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, ..settings(64, &[BakedMap::Normal, BakedMap::Height]) };
let out = transfer(&quad(), &bumped(h, sigma), None, &s).unwrap();
let normal = &out.maps[&BakedMap::Normal];
for (x, z) in [(0.3f32, 0.0f32), (-0.3, 0.0), (0.0, 0.3), (0.0, -0.3), (0.25, 0.25)] {
let i = quad_texel(64, x, z);
// Analytic normal of the bump at the texel centre.
let (cx, cz) = (((i % 64) as f32 + 0.5) / 32.0 - 1.0, ((i / 64) as f32 + 0.5) / 32.0 - 1.0);
let f = h * (-(cx * cx + cz * cz) / (sigma * sigma)).exp();
let (dx, dz) = (-2.0 * cx / (sigma * sigma) * f, -2.0 * cz / (sigma * sigma) * f);
let n = Vec3::new(-dx, 1.0, -dz).normalize();
// Tangent = +X, bitangent = −Z, normal = +Y.
let expected = [0.5 + 0.5 * n.x, 0.5 - 0.5 * n.z, 0.5 + 0.5 * n.y];
let got = &normal[i * 3..i * 3 + 3];
assert!(got.iter().zip(expected).all(|(g, e)| (g - e).abs() < 0.02), "at {x},{z}: {got:?} vs {expected:?}");
assert!((got[0] - 0.5) * x >= 0.0 && (got[1] - 0.5) * -z >= 0.0, "tilts away from the bump centre at {x},{z}: {got:?}");
}
let height = &out.maps[&BakedMap::Height];
assert!(height[quad_texel(64, 0.0, 0.0)] > height[quad_texel(64, 0.6, 0.6)] + 0.2, "the bump top is higher");
}
#[test]
fn curvature_from_the_normal_map_sees_the_bump() {
let s = BakeSettings { max_frontal: 0.06, max_rear: 0.02, curvature_from_normal: true, ..settings(64, &[BakedMap::Curvature]) };
let out = transfer(&quad(), &bumped(0.1, 0.4), None, &s).unwrap();
assert!(!out.maps.contains_key(&BakedMap::Normal), "the helper normal map is not returned");
let c = &out.maps[&BakedMap::Curvature];
assert!(c[quad_texel(64, 0.0, 0.0)] > 0.55, "convex top {}", c[quad_texel(64, 0.0, 0.0)]);
assert!((c[quad_texel(64, 0.9, 0.9)] - 0.5).abs() < 0.02, "flat corner {}", c[quad_texel(64, 0.9, 0.9)]);
}
/// Two unit boxes 0.2 apart: "A" (material 0, centre x = −0.6) and "B" (material 1, x = +0.6).
fn two_boxes(suffix: &str, colors: Option<[Vec4; 2]>) -> Mesh {
let part = |name: &str, x: f32, color: Option<Vec4>| {
let mut b = primitives::cube(1.0);
b.positions.iter_mut().for_each(|p| p.x += x);
b.submeshes[0].name = format!("{name}{suffix}");
b.colors = color.map(|c| vec![c; b.positions.len()]).unwrap_or_default();
b
};
let mut m = part("A", -0.6, colors.map(|c| c[0]));
m.append(&part("B", 0.6, colors.map(|c| c[1])));
m
}
#[test]
fn match_by_mesh_name_pairs_the_right_parts() {
let (red, blue) = (Vec4::new(1.0, 0.0, 0.0, 1.0), Vec4::new(0.0, 0.0, 1.0, 1.0));
let (low, high) = (two_boxes("_low", None), two_boxes("_HIGH", Some([red, blue])));
// Rays start 1.3 in front of A's +X face: beyond B, so B's high poly is hit first unless
// parts are matched by name.
let s = BakeSettings { max_frontal: 0.5, ..settings(64, &[BakedMap::ColorMap]) };
let face = |s: &BakeSettings| {
let out = transfer(&low, &high, None, s).unwrap();
covered_values(&low, &out, BakedMap::ColorMap)
.into_iter()
.filter(|(p, _)| p.x > -0.105 && p.y.abs() < 0.4 && p.z.abs() < 0.4)
.map(|v| v.1)
.collect::<Vec<f32>>()
};
let always = face(&s);
assert!(!always.is_empty() && always.iter().all(|r| *r < 0.01), "always: B's (blue) high poly occludes A's face");
let by_name = face(&BakeSettings { matching: BakeMatch::ByMeshName, ..s.clone() });
assert!(by_name.iter().all(|r| *r > 0.99), "by name: A's face gets A's red");
// Parts without a counterpart get nothing.
let lonely = BakeSettings { matching: BakeMatch::ByMeshName, low_suffix: "_none".into(), ..s };
assert!(face(&lonely).iter().all(|r| *r == 0.0));
}
#[test]
fn bent_normals_point_away_from_occluders() {
// A floor (material 0) with a wall standing at x = +1, facing −X (material 1).
let mut m = quad();
let wall = Mesh::from_parts(
vec![Vec3::new(1.0, 0.0, -1.0), Vec3::new(1.0, 0.0, 1.0), Vec3::new(1.0, 2.0, 1.0), Vec3::new(1.0, 2.0, -1.0)],
Some(vec![-Vec3::X; 4]),
vec![Vec2::ZERO, Vec2::X, Vec2::ONE, Vec2::Y],
vec![0, 2, 1, 0, 3, 2],
"Wall",
)
.unwrap();
m.append(&wall);
let s = BakeSettings { max_distance: 2.0, ..settings(32, &[BakedMap::BentNormal, BakedMap::AmbientOcclusion]) };
let out = run(&m, &s).unwrap();
let bent = &out.maps[&BakedMap::BentNormal];
let ao = covered_values(&m, &out, BakedMap::AmbientOcclusion);
let g = UvGBuffer::new(&m, 0, 32, 32);
let near: Vec<&[f32]> = (0..32 * 32).filter(|i| g.surface(&m, *i).is_some_and(|s| s.pos.x > 0.6)).map(|i| &bent[i * 3..i * 3 + 3]).collect();
let far: Vec<&[f32]> = (0..32 * 32).filter(|i| g.surface(&m, *i).is_some_and(|s| s.pos.x < -0.6)).map(|i| &bent[i * 3..i * 3 + 3]).collect();
let mean_x = |v: &[&[f32]]| mean(v.iter().map(|b| b[0] * 2.0 - 1.0));
assert!(mean_x(&near) < -0.15, "near the wall the bent normal leans away from it: {}", mean_x(&near));
assert!(mean_x(&near) < mean_x(&far), "{} vs {}", mean_x(&near), mean_x(&far));
assert!(near.iter().all(|b| b[1] > 0.6), "still points up");
let ao_near = mean(ao.iter().filter(|(p, _)| p.x > 0.6).map(|v| v.1));
assert!(ao_near < mean(ao.iter().filter(|(p, _)| p.x < -0.6).map(|v| v.1)));
}
#[test]
fn opacity_and_color_transfer_where_the_high_poly_is() {
// The high poly covers x < 0 only, colored green.
let mut high = quad();
high.positions.iter_mut().for_each(|p| p.x = p.x.min(0.0));
high.colors = vec![Vec4::new(0.0, 1.0, 0.0, 0.5); 4];
let out = transfer(&quad(), &high, None, &settings(32, &[BakedMap::Opacity, BakedMap::ColorMap])).unwrap();
let (op, col) = (&out.maps[&BakedMap::Opacity], &out.maps[&BakedMap::ColorMap]);
let (left, right) = (quad_texel(32, -0.5, 0.0), quad_texel(32, 0.5, 0.0));
assert_eq!((op[left], op[right]), (0.5, 0.0), "vertex alpha where covered, 0 where missed");
assert_eq!(&col[left * 3..left * 3 + 3], [0.0, 1.0, 0.0]);
assert_eq!(&col[right * 3..right * 3 + 3], BakedMap::ColorMap.neutral());
// Without a high poly the low poly covers itself (white, opaque).
let own = run(&quad(), &settings(32, &[BakedMap::Opacity, BakedMap::ColorMap])).unwrap();
assert_eq!((own.maps[&BakedMap::Opacity][right], own.maps[&BakedMap::ColorMap][right * 3]), (1.0, 1.0));
}
#[test]
fn ray_distances_and_the_cage_limit_hits() {
let low = quad();
let mut high = quad();
high.positions.iter_mut().for_each(|p| p.y += 0.2);
let diag = 8.0f32.sqrt();
let opacity = |s: &BakeSettings, cage: Option<&Mesh>| transfer(&low, &high, cage, s).map(|o| o.maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)]);
let near = settings(16, &[BakedMap::Opacity]);
assert_eq!(opacity(&near, None).unwrap(), 0.0, "0.2 above is beyond the default frontal distance");
assert_eq!(opacity(&BakeSettings { max_frontal: 0.25 / diag, ..near.clone() }, None).unwrap(), 1.0);
// The rear distance only reaches below the surface.
let mut below = high.clone();
below.positions.iter_mut().for_each(|p| p.y -= 0.4);
let rear = |r: f32| transfer(&low, &below, None, &BakeSettings { max_rear: r, ..near.clone() }).unwrap().maps[&BakedMap::Opacity][quad_texel(16, 0.0, 0.0)];
assert_eq!((rear(0.1 / diag), rear(0.25 / diag)), (0.0, 1.0));
// A cage 0.3 above the low poly starts the rays above the high poly.
let mut cage = low.clone();
cage.positions.iter_mut().for_each(|p| p.y += 0.3);
assert_eq!(opacity(&near, Some(&cage)).unwrap(), 1.0);
// A cage 0.1 above starts below it.
cage.positions.iter_mut().for_each(|p| p.y -= 0.2);
assert_eq!(opacity(&near, Some(&cage)).unwrap(), 0.0);
// The cage must have the low poly's triangles.
assert!(matches!(opacity(&near, Some(&primitives::cube(1.0))), Err(BakeError::Invalid(_))));
}
#[test]
fn world_space_direction_is_a_facing_ratio() {
let m = quad();
let at =
|d: [f32; 3]| run(&m, &BakeSettings { direction: d, ..settings(8, &[BakedMap::WorldDirection]) }).map(|o| o.maps[&BakedMap::WorldDirection][4 * 8 + 4]);
assert_eq!(at([0.0, 2.0, 0.0]).unwrap(), 1.0);
assert_eq!(at([1.0, 0.0, 0.0]).unwrap(), 0.5);
assert_eq!(at([0.0, -1.0, 0.0]).unwrap(), 0.0);
assert!(matches!(at([0.0; 3]), Err(BakeError::Invalid(_))));
}
/// `cargo test -p texturecraft-bake --release -- --ignored --nocapture bench`
#[test]
#[ignore]
fn bench_material_ball_2k() {
let m = primitives::material_ball();
let bvh = Bvh::new(&m);
let all = BakeSettings { resolution: 2048, ..BakeSettings::default() };
for maps in
[vec![BakedMap::Position], vec![BakedMap::AmbientOcclusion], vec![BakedMap::Thickness], vec![BakedMap::Curvature], all.maps.iter().copied().collect()]
{
let s = BakeSettings { maps: maps.into_iter().collect(), ..all.clone() };
let t = std::time::Instant::now();
let out = bake(&BakeRequest { mesh: &m, bvh: &bvh, material: 0, settings: &s, high: None, cage: None }, &Progress::new()).unwrap();
println!("material ball, material 0, {}² × {:?}, {} rays: {:.2?}", out.resolution, out.maps.keys(), s.rays, t.elapsed());
}
}
+16
View File
@@ -0,0 +1,16 @@
[package]
name = "texturecraft-compose"
description = "TextureCraft layer-stack compositor (CPU reference), patterns, UV padding, display conversion"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
texturecraft-core = { workspace = true }
texturecraft-texel = { workspace = true }
texturecraft-geom = { workspace = true }
rayon = { workspace = true }
half = { workspace = true }
+222
View File
@@ -0,0 +1,222 @@
//! A per-tile cache of the composited stack below one "hot" layer (the layer being painted or
//! edited), so recompositing a tile only evaluates that layer and the layers above it. The
//! cache is keyed by everything the cached part reads; any change to it empties the cache, so
//! results are always identical to a full evaluation.
use std::collections::{BTreeSet, HashMap, VecDeque};
use std::sync::Arc;
use texturecraft_core::{BakedMap, Channel, Layer, LayerId, LayerKind, Project, TextureSet};
use texturecraft_texel::TileImage;
use crate::eval::{Inputs, PaintTarget};
use crate::store::{BakedMaps, ImageStore, PixelStore};
/// Default byte budget of a [`BelowCache`].
pub const BELOW_BUDGET: usize = 256 << 20;
/// See the module docs. One per texture set.
#[derive(Debug)]
pub struct BelowCache {
hot: Option<LayerId>,
key: Option<StackKey>,
tiles: HashMap<(u32, u32), Vec<f32>>,
/// Insertion order, oldest first (eviction beyond the budget).
order: VecDeque<(u32, u32)>,
bytes: usize,
/// Byte budget; the oldest tiles are dropped beyond it.
pub budget: usize,
/// Tiles of the whole pass a caller splits into several composites (0: each composite is a
/// pass). A pass larger than the cache records only what fits.
pub pass: usize,
}
impl Default for BelowCache {
fn default() -> Self {
BelowCache { hot: None, key: None, tiles: HashMap::new(), order: VecDeque::new(), bytes: 0, budget: BELOW_BUDGET, pass: 0 }
}
}
/// Everything compositing `roots` of a texture set reads: equal keys composite identically.
/// Pixels are compared by tile identity (copy-on-write), so building and comparing keys is cheap.
#[derive(Debug, PartialEq)]
pub struct StackKey {
/// The texture set without its name, description, stack and bake settings.
set: TextureSet,
roots: Vec<LayerId>,
/// The layers drawn, without names and other display-only fields.
layers: Vec<Layer>,
pixels: Vec<(LayerId, Option<Channel>, Shared)>,
baked: (u32, Vec<(BakedMap, usize)>),
images: Vec<(String, usize)>,
}
impl StackKey {
/// The key of `roots` (layers of texture set `ts`, bottom → top) and their effects.
pub fn new(project: &Project, pixels: &PixelStore, baked: &BakedMaps, images: &ImageStore, ts: usize, roots: &[LayerId]) -> Option<StackKey> {
let mut set = project.texture_set(ts).ok()?.clone();
set.name.clear();
set.description.clear();
set.stack.clear();
set.bake = Default::default();
let tree = project.render_tree(roots);
let effects: BTreeSet<LayerId> = tree.iter().filter_map(|id| project.layers.get(id)).flat_map(effect_ids).collect();
let pixels = tree
.iter()
.chain(&effects)
.flat_map(|id| {
let layer = Channel::ALL.into_iter().filter_map(move |c| pixels.layer(*id, c).map(|img| (*id, Some(c), Shared(img.clone()))));
layer.chain(pixels.masks.get(id).map(|img| (*id, None, Shared(img.clone()))))
})
.collect();
let mut images: Vec<(String, usize)> = images.iter().map(|(n, i)| (n.clone(), Arc::as_ptr(i) as usize)).collect();
images.sort();
Some(StackKey {
set,
roots: roots.to_vec(),
layers: tree.iter().filter_map(|id| project.layers.get(id)).map(render_view).collect(),
pixels,
baked: (baked.resolution, baked.maps.iter().map(|(m, d)| (*m, Arc::as_ptr(d) as usize)).collect()),
images,
})
}
}
/// An image compared by tile identity: holding the clone keeps its tiles alive, and a tile
/// rewritten since is a different allocation (copy-on-write), so pointer equality means the
/// same pixels without reading them.
#[derive(Debug)]
struct Shared(TileImage);
impl PartialEq for Shared {
fn eq(&self, other: &Self) -> bool {
let (a, b) = (&self.0, &other.0);
a.width() == b.width()
&& a.height() == b.height()
&& a.comps() == b.comps()
&& (0..a.tiles_y()).all(|ty| {
(0..a.tiles_x()).all(|tx| match (a.tile_handle(tx, ty), b.tile_handle(tx, ty)) {
(None, None) => true,
(Some(x), Some(y)) => Arc::ptr_eq(x, y),
_ => false,
})
})
}
}
/// Ids of a layer's mask and content effects.
fn effect_ids(l: &Layer) -> impl Iterator<Item = LayerId> + '_ {
l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()).map(|e| e.id)
}
/// A layer as far as compositing is concerned (names, color tags and folding don't matter).
fn render_view(l: &Layer) -> Layer {
let mut l = l.clone();
l.name.clear();
l.color_tag = None;
if let LayerKind::Group { collapsed, .. } = &mut l.kind {
*collapsed = false;
}
l
}
impl BelowCache {
/// Cache the stack below `hot` from now on (a different layer empties the cache).
pub fn set_hot(&mut self, hot: Option<LayerId>) {
if self.hot != hot {
self.hot = hot;
self.clear();
}
}
pub fn clear(&mut self) {
self.tiles.clear();
self.order.clear();
self.bytes = 0;
self.key = None;
}
pub fn bytes(&self) -> usize {
self.bytes
}
pub fn len(&self) -> usize {
self.tiles.len()
}
pub fn is_empty(&self) -> bool {
self.tiles.is_empty()
}
pub(crate) fn tile(&self, t: (u32, u32)) -> Option<&[f32]> {
self.tiles.get(&t).map(Vec::as_slice)
}
pub(crate) fn insert(&mut self, t: (u32, u32), data: Vec<f32>) {
let size = data.len() * std::mem::size_of::<f32>();
if size > self.budget {
return;
}
while self.bytes + size > self.budget {
let Some(old) = self.order.pop_front() else { break };
if let Some(d) = self.tiles.remove(&old) {
self.bytes = self.bytes.saturating_sub(d.len() * std::mem::size_of::<f32>());
}
}
if let Some(d) = self.tiles.insert(t, data) {
self.bytes = self.bytes.saturating_sub(d.len() * std::mem::size_of::<f32>());
} else {
self.order.push_back(t);
}
self.bytes += size;
}
/// Where the stack splits for `inp`: layers of the texture set's top level before the
/// returned index are served from the cache. None when the hot layer is not drawn in the set
/// or the cached part could change (it reads anchors or holds the live stroke). Empties the
/// cache when what the cached part reads changed.
pub(crate) fn prepare(&mut self, inp: &Inputs) -> Option<usize> {
let hot = self.hot?;
let p = inp.project;
let set = p.texture_set(inp.ts).ok()?;
let split = set.stack.iter().position(|id| p.render_tree(&[*id]).contains(&hot))?;
let below = set.stack.get(..split)?;
// Anchors carry values across the split.
if p.render_tree(&set.stack).iter().any(|id| p.layers.get(id).is_some_and(Layer::reads_anchor)) {
return None;
}
if let Some(pv) = inp.preview {
let (PaintTarget::Layer(t) | PaintTarget::Mask(t)) = pv.target;
let tree = p.render_tree(below);
if tree.contains(&t) || tree.iter().filter_map(|id| p.layers.get(id)).flat_map(effect_ids).any(|e| e == t) {
return None;
}
}
let key = StackKey::new(p, inp.pixels, inp.baked, inp.images, inp.ts, below)?;
if self.key.as_ref() != Some(&key) {
self.clear();
self.key = Some(key);
}
Some(split)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn insert_keeps_to_the_budget_dropping_the_oldest() {
let mut c = BelowCache { budget: 3 * 16, ..BelowCache::default() };
for i in 0..5 {
c.insert((i, 0), vec![0.0; 4]);
}
assert_eq!(c.len(), 3);
assert_eq!(c.bytes(), 48);
assert!(c.tile((0, 0)).is_none() && c.tile((4, 0)).is_some());
c.insert((9, 9), vec![0.0; 100]);
assert!(c.tile((9, 9)).is_none(), "bigger than the whole budget");
c.set_hot(Some(LayerId(3)));
assert!(c.is_empty() && c.bytes() == 0);
}
}
+166
View File
@@ -0,0 +1,166 @@
//! Conversion of composited tiles to the texture formats the viewport samples.
use texturecraft_core::{BakedMap, Channel};
use texturecraft_texel::{TILE, TILE_AREA, srgb_lut};
use crate::eval::Composite;
use crate::store::BakedMaps;
/// One of the textures the viewport shader samples.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum DisplayKind {
/// sRGB8: base color, alpha = opacity.
BaseColor,
/// RGBA8 linear: ambient occlusion (channel × baked), roughness (1 − glossiness when the set
/// has a Glossiness channel), metallic, specular level.
Orm,
/// RGBA8: painted tangent-space normal.
Normal,
/// RGBA16F: height in r, the linear Specular (F0) color in gba.
Height,
/// sRGB8: emissive color.
Emissive,
}
impl DisplayKind {
pub const ALL: [DisplayKind; 5] = [DisplayKind::BaseColor, DisplayKind::Orm, DisplayKind::Normal, DisplayKind::Height, DisplayKind::Emissive];
/// Bytes per texel of the upload format.
pub fn bytes_per_texel(self) -> usize {
if self == DisplayKind::Height { 8 } else { 4 }
}
/// Display textures affected by a channel.
pub fn of_channel(c: Channel) -> DisplayKind {
match c {
Channel::BaseColor | Channel::Opacity => DisplayKind::BaseColor,
Channel::Normal => DisplayKind::Normal,
Channel::Height | Channel::Specular => DisplayKind::Height,
Channel::Emissive => DisplayKind::Emissive,
_ => DisplayKind::Orm,
}
}
}
fn u8_of(v: u16) -> u8 {
(v >> 8) as u8
}
/// Tile bytes (`TILE × TILE`, row-major) for `kind` from the composite, or None when the tile is
/// absent in every source (the GPU texture keeps its cleared default).
pub fn tile_bytes(comp: &Composite, baked: &BakedMaps, kind: DisplayKind, tx: u32, ty: u32) -> Vec<u8> {
let bpt = kind.bytes_per_texel();
let mut out = vec![0u8; TILE_AREA * bpt];
let lut = srgb_lut();
let get = |c: Channel| comp.channels.get(&c).and_then(|img| img.tile(tx, ty));
let res = comp.resolution;
let default16 = |c: Channel| texturecraft_texel::to_u16(c.default_value()[0]);
match kind {
DisplayKind::BaseColor | DisplayKind::Emissive => {
let (c, alpha) = if kind == DisplayKind::BaseColor { (Channel::BaseColor, get(Channel::Opacity)) } else { (Channel::Emissive, None) };
let src = get(c);
let d = c.default_value().map(|v| (texturecraft_texel::linear_to_srgb(v) * 255.0 + 0.5) as u8);
for i in 0..TILE_AREA {
let px = &mut out[i * 4..i * 4 + 4];
match src {
Some(s) => {
for k in 0..3 {
px[k] = lut[(s.get(i * 3 + k).copied().unwrap_or(0) >> 4) as usize];
}
}
None => px[..3].copy_from_slice(&d),
}
px[3] = alpha.map(|a| u8_of(a.get(i).copied().unwrap_or(65535))).unwrap_or(255);
}
}
DisplayKind::Orm => {
let (ao, m, s) = (get(Channel::AmbientOcclusion), get(Channel::Metallic), get(Channel::SpecularLevel));
// Specular/glossiness sets: the viewport shades roughness = 1 − glossiness.
let gloss = comp.channels.contains_key(&Channel::Glossiness);
let (r, r_default) = if gloss { (get(Channel::Glossiness), default16(Channel::Glossiness)) } else { (get(Channel::Roughness), default16(Channel::Roughness)) };
for i in 0..TILE_AREA {
let (x, y) = (tx * TILE + (i as u32 % TILE), ty * TILE + (i as u32 / TILE));
let baked_ao = baked.scalar(BakedMap::AmbientOcclusion, x, y, res).unwrap_or(1.0);
let ch_ao = ao.and_then(|a| a.get(i)).map(|v| *v as f32 / 65535.0).unwrap_or(1.0);
let px = &mut out[i * 4..i * 4 + 4];
px[0] = ((baked_ao * ch_ao).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
let v = r.and_then(|t| t.get(i).copied()).unwrap_or(r_default);
px[1] = u8_of(if gloss { 65535 - v } else { v });
px[2] = u8_of(m.and_then(|t| t.get(i).copied()).unwrap_or(0));
px[3] = u8_of(s.and_then(|t| t.get(i).copied()).unwrap_or(default16(Channel::SpecularLevel)));
}
}
DisplayKind::Normal => {
let n = get(Channel::Normal);
for i in 0..TILE_AREA {
let px = &mut out[i * 4..i * 4 + 4];
match n {
Some(t) => {
for (k, d) in px.iter_mut().take(3).enumerate() {
*d = u8_of(t.get(i * 3 + k).copied().unwrap_or(0));
}
}
None => px[..3].copy_from_slice(&[128, 128, 255]),
}
px[3] = 255;
}
}
DisplayKind::Height => {
let (h, spec) = (get(Channel::Height), get(Channel::Specular));
let spec_default = Channel::Specular.default_value();
for i in 0..TILE_AREA {
let v = h.and_then(|t| t.get(i)).map(|v| texturecraft_texel::from_u16_signed(*v)).unwrap_or(0.0);
let f0 = |k: usize| spec.and_then(|t| t.get(i * 3 + k)).map(|v| *v as f32 / 65535.0).unwrap_or(spec_default[k]);
for (k, c) in [v, f0(0), f0(1), f0(2)].into_iter().enumerate() {
out[i * 8 + k * 2..i * 8 + k * 2 + 2].copy_from_slice(&half::f16::from_f32(c).to_le_bytes());
}
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
use texturecraft_texel::to_u16;
#[test]
fn base_color_uses_srgb_and_opacity() {
let mut comp = Composite::new(&[Channel::BaseColor, Channel::Opacity], 64);
comp.channels.get_mut(&Channel::BaseColor).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]);
comp.channels.get_mut(&Channel::Opacity).unwrap().set(0, 0, &[to_u16(0.5)]);
let b = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::BaseColor, 0, 0);
assert_eq!(b[0], 255);
assert!((b[1] as i32 - 188).abs() <= 1, "{}", b[1]);
assert_eq!(b[2], 0);
assert!((b[3] as i32 - 127).abs() <= 1);
}
#[test]
fn missing_channels_fall_back_to_defaults() {
let comp = Composite::new(&[], 64);
let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0);
assert_eq!(&orm[..4], &[255, 128, 0, 128]);
let n = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Normal, 0, 0);
assert_eq!(&n[..4], &[128, 128, 255, 255]);
let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0);
assert_eq!(h.len(), TILE_AREA * 8);
assert_eq!(half::f16::from_le_bytes([h[2], h[3]]).to_f32(), half::f16::from_f32(0.04).to_f32(), "default F0");
}
#[test]
fn glossiness_shows_as_roughness_and_specular_rides_in_height() {
let mut comp = Composite::new(&[Channel::Glossiness, Channel::Specular], 64);
comp.channels.get_mut(&Channel::Glossiness).unwrap().set(0, 0, &[to_u16(0.8)]);
comp.channels.get_mut(&Channel::Specular).unwrap().set(0, 0, &[to_u16(1.0), to_u16(0.5), 0]);
let orm = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Orm, 0, 0);
assert!((orm[1] as i32 - 51).abs() <= 1, "roughness = 1 - 0.8, got {}", orm[1]);
let h = tile_bytes(&comp, &BakedMaps::default(), DisplayKind::Height, 0, 0);
let at = |k: usize| half::f16::from_le_bytes([h[k * 2], h[k * 2 + 1]]).to_f32();
assert_eq!(at(0), 0.0);
assert!((at(1) - 1.0).abs() < 1e-3 && (at(2) - 0.5).abs() < 1e-3 && at(3) == 0.0);
assert_eq!(DisplayKind::of_channel(Channel::Specular), DisplayKind::Height);
assert_eq!(DisplayKind::of_channel(Channel::Glossiness), DisplayKind::Orm);
}
}
File diff suppressed because it is too large. Load diff
+19
View File
@@ -0,0 +1,19 @@
//! # texturecraft-compose
//!
//! The CPU layer-stack evaluator: [`eval::composite_tiles`] turns a texture set's layers, masks,
//! fills and painted pixels into one image per channel, tile by tile in parallel, including the
//! live preview of a stroke being drawn. [`display`] converts composited tiles into the texture
//! formats the viewport samples; [`pattern`] evaluates procedurals through projections.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod below;
pub mod display;
pub mod eval;
pub mod pattern;
pub mod store;
pub use below::{BelowCache, StackKey};
pub use display::{DisplayKind, tile_bytes};
pub use eval::{Composite, Inputs, PaintTarget, Stencil, StrokePreview, all_tiles, composite_tiles, composite_tiles_cached, covered_tiles, flatten_layer, mask_image, pad_tiles};
pub use store::{BakedMaps, ImageRes, ImageStore, PixelStore};
+298
View File
@@ -0,0 +1,298 @@
//! Procedural patterns and projections.
use texturecraft_core::{Procedural, ProceduralKind, Projection};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_texel::noise;
/// Where a texel is, for pattern evaluation.
#[derive(Clone, Copy, Debug)]
pub struct Coords {
pub uv: Vec2,
/// World position divided by the scene radius (scale-independent).
pub pos: Vec3,
pub nrm: Vec3,
}
/// Raw pattern value at a 3D point, 0..1.
fn raw(kind: ProceduralKind, p: Vec3, seed: u32) -> f32 {
let a = p.to_array();
match kind {
ProceduralKind::Clouds => noise::fbm(a, 6, seed, noise::value),
ProceduralKind::Perlin => noise::fbm(a, 4, seed, noise::perlin),
ProceduralKind::Noise => noise::value((p * 16.0).to_array(), seed),
ProceduralKind::Cells => noise::worley(a, seed),
ProceduralKind::Grunge => {
let n = noise::fbm(a, 6, seed, noise::perlin) * 0.7 + noise::fbm((p * 3.7).to_array(), 3, seed ^ 0x55, noise::value) * 0.3;
((n - 0.45) * 4.0 + 0.5).clamp(0.0, 1.0)
}
ProceduralKind::Scratches => {
// Long thin streaks: noise stretched along one axis, sharpened to lines.
let q = Vec3::new(p.x * 0.15, p.y * 6.0, p.z * 6.0);
let n = noise::perlin(q.to_array(), seed);
let line = 1.0 - ((n - 0.5).abs() * 40.0).min(1.0);
let gate = noise::value((p * 0.8).to_array(), seed ^ 0x99);
line * ((gate - 0.45) * 4.0).clamp(0.0, 1.0)
}
ProceduralKind::Checker => {
let c = p.floor();
if (c.x + c.y + c.z).rem_euclid(2.0) < 1.0 { 1.0 } else { 0.0 }
}
ProceduralKind::Stripes => {
let t = p.x.rem_euclid(1.0);
if t < 0.5 { 1.0 } else { 0.0 }
}
ProceduralKind::Gradient => p.x.rem_euclid(1.0),
ProceduralKind::Wood => {
// Rings across Y (warped by low-frequency noise), latewood darkening sharply before
// each ring boundary; fine fibers stretched along X.
let warp = noise::fbm([p.x * 0.18, p.y * 0.6, p.z], 3, seed, noise::perlin);
let t = ((p.y + (warp - 0.5) * 0.9) * 5.0).rem_euclid(1.0);
let ring = 1.0 - smoothstep(0.45, 1.0, t);
let fiber = noise::value([p.x * 2.0, p.y * 40.0, p.z], seed ^ 0x3C);
let tone = noise::fbm([p.x * 0.6, p.y * 3.0, p.z], 2, seed ^ 0x71, noise::value);
(ring * 0.6 + fiber * 0.25 + tone * 0.15).clamp(0.0, 1.0)
}
ProceduralKind::Bricks => {
// Bricks 1 × 0.5 in running bond; per-brick tone in the top 15 % so low/high map to
// mortar/brick colors without washing the bricks out.
let row = (p.y * 2.0).floor();
let x = p.x + if (row as i32).rem_euclid(2) == 1 { 0.5 } else { 0.0 };
let (col, fx, fy) = (x.floor(), x.rem_euclid(1.0), (p.y * 2.0).rem_euclid(1.0));
let d = fx.min(1.0 - fx).min(fy.min(1.0 - fy) * 0.5);
let tone = noise::cell_hash(col as i32, row as i32, 0, seed) * 0.6 + noise::value((p * 9.0).to_array(), seed) * 0.4;
smoothstep(0.02, 0.045, d) * (0.85 + 0.15 * tone)
}
ProceduralKind::Tiles => {
let (c, f) = (p.floor(), p - p.floor());
let d = f.x.min(1.0 - f.x).min(f.y.min(1.0 - f.y));
smoothstep(0.015, 0.035, d) * (0.9 + 0.1 * noise::cell_hash(c.x as i32, c.y as i32, 0, seed))
}
ProceduralKind::Weave => {
// Plain weave: in each cell the thread on top alternates (warp along X, weft along Y);
// the top thread shows its round cross-section, bulging mid-span.
let c = (p * 2.0).floor();
let f = p * 2.0 - c;
let pi = std::f32::consts::PI;
let warp_on_top = (c.x as i32 + c.y as i32).rem_euclid(2) == 0;
let (across, along) = if warp_on_top { (f.y, f.x) } else { (f.x, f.y) };
let thread = (pi * across).sin().max(0.0).sqrt() * (0.8 + 0.2 * (pi * along).sin());
let fiber = noise::value([p.x * 40.0, p.y * 40.0, p.z], seed);
(thread * (0.88 + 0.12 * fiber)).clamp(0.0, 1.0)
}
ProceduralKind::Leather => {
let w = noise::perlin((p * 0.7).to_array(), seed ^ 0x2D) - 0.5;
let (f1, f2, _) = noise::cellular([p.x + w * 0.4, p.y - w * 0.4, p.z], seed);
let crease = smoothstep(0.0, 0.16, f2 - f1);
let pebble = 1.0 - f1 * 0.5;
let fine = noise::value((p * 7.0).to_array(), seed ^ 0x13);
(crease * pebble * (0.85 + 0.15 * fine)).clamp(0.0, 1.0)
}
ProceduralKind::Hammered => {
let dent = |q: Vec3, s: u32| {
let (f1, _, _) = noise::cellular(q.to_array(), s);
(f1 * 1.25).min(1.0).powi(2)
};
(dent(p, seed) * 0.75 + dent(p * 2.3 + Vec3::splat(5.1), seed ^ 0x5A) * 0.25).clamp(0.0, 1.0)
}
ProceduralKind::Brushed => {
let a = noise::value([p.x * 1.5, p.y * 60.0, p.z], seed);
let b = noise::value([p.x * 0.4, p.y * 18.0, p.z], seed ^ 0x77);
(a * 0.6 + b * 0.4).clamp(0.0, 1.0)
}
ProceduralKind::Marble => {
let turb = noise::fbm(a, 5, seed, noise::perlin);
let veins = ((p.x + p.y * 0.5) * 2.5 + turb * 9.0).sin().abs().powf(0.3);
let cloud = noise::fbm((p * 2.0).to_array(), 3, seed ^ 0x19, noise::value);
(veins * 0.85 + cloud * 0.15).clamp(0.0, 1.0)
}
ProceduralKind::Voronoi => noise::cellular(a, seed).2,
ProceduralKind::Streaks => {
// Drips: thin columns along Y, each segment starting at a random height and fading
// as it runs down (Y is up), over two offset column grids.
let drip = |x: f32, salt: u32| {
let cx = x * 6.0;
let col = cx.floor() as i32;
let h = |k: i32| noise::cell_hash(col, k, salt as i32, seed);
let width = 0.08 + 0.25 * h(0);
let across = 1.0 - smoothstep(width * 0.3, width, (cx - cx.floor() - 0.5 - (h(1) - 0.5) * 0.5).abs());
let yy = p.y * (0.35 + 0.4 * h(2)) + h(3) * 7.0;
let t = yy - yy.floor();
let on = if noise::cell_hash(col, yy.floor() as i32, 3 + salt as i32, seed) > 0.5 { 1.0 } else { 0.0 };
across * on * t.powf(1.6) * (1.0 - smoothstep(0.9, 1.0, t))
};
let fine = noise::value([p.x * 37.0, p.y * 1.3, p.z], seed ^ 0x2B);
(drip(p.x, 0).max(drip(p.x + 0.37, 1) * 0.8) * (0.6 + 0.4 * fine)).clamp(0.0, 1.0)
}
ProceduralKind::Smudges => {
// Sparse elliptical prints with concentric ridges, over soft greasy smudges.
let w = noise::perlin((p * 1.3).to_array(), seed ^ 0x61) - 0.5;
let q = Vec3::new(p.x * 1.15 + w * 0.3, p.y * 0.85 + w * 0.3, p.z);
let (f1, _, id) = noise::cellular(q.to_array(), seed);
let print = (1.0 - smoothstep(0.18 + 0.1 * id, 0.3 + 0.12 * id, f1)) * if id > 0.4 { 1.0 } else { 0.0 };
let ridges = 0.5 + 0.5 * (f1 * 190.0 + w * 12.0).sin();
let smudge = ((noise::fbm((p * 1.7).to_array(), 4, seed ^ 0x33, noise::value) - 0.55) * 3.0).clamp(0.0, 1.0);
(print * ridges * 0.9 + smudge * 0.4).clamp(0.0, 1.0)
}
ProceduralKind::Pores => {
let (f1, _, _) = noise::cellular(a, seed);
let (g1, _, _) = noise::cellular((p * 2.7 + Vec3::splat(13.0)).to_array(), seed ^ 0x6B);
smoothstep(0.08, 0.16, f1).min(smoothstep(0.06, 0.12, g1))
}
ProceduralKind::Chips => {
let (f1, _, _) = noise::cellular((p * 2.0).to_array(), seed ^ 0x45);
let n = noise::fbm(a, 5, seed, noise::perlin) + (f1 - 0.5) * 0.25;
smoothstep(0.55, 0.58, n)
}
}
}
fn smoothstep(e0: f32, e1: f32, x: f32) -> f32 {
let t = ((x - e0) / (e1 - e0)).clamp(0.0, 1.0);
t * t * (3.0 - 2.0 * t)
}
fn shape(pr: &Procedural, v: f32) -> f32 {
let v = ((v - 0.5) * pr.contrast.max(0.0) + 0.5 + pr.balance).clamp(0.0, 1.0);
if pr.invert { 1.0 - v } else { v }
}
/// Evaluate a procedural through a projection.
pub fn procedural(pr: &Procedural, proj: &Projection, c: &Coords) -> f32 {
let s = pr.scale.max(1e-4);
let v = match proj {
Projection::Uv { scale, rotation, offset } => {
let (sn, cs) = rotation.to_radians().sin_cos();
let uv = Vec2::new(c.uv.x * cs - c.uv.y * sn, c.uv.x * sn + c.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset);
// 2D patterns sample a slice of the 3D pattern.
raw(pr.kind, (uv * s).extend(0.0), pr.seed)
}
Projection::Triplanar { scale, sharpness, offset } => {
let p = c.pos * *scale * s + Vec3::from(*offset);
let w = c.nrm.abs().powf(sharpness.max(1.0));
let w = w / (w.x + w.y + w.z).max(1e-6);
raw(pr.kind, Vec3::new(p.z, p.y, 0.0), pr.seed) * w.x
+ raw(pr.kind, Vec3::new(p.x, p.z, 0.0), pr.seed) * w.y
+ raw(pr.kind, Vec3::new(p.x, p.y, 0.0), pr.seed) * w.z
}
Projection::Planar { scale, axis, offset } => {
let p = c.pos * *scale * s + Vec3::from(*offset);
let q = match axis {
0 => Vec3::new(p.z, p.y, 0.0),
1 => Vec3::new(p.x, p.z, 0.0),
_ => Vec3::new(p.x, p.y, 0.0),
};
raw(pr.kind, q, pr.seed)
}
Projection::Spherical { scale } => {
let d = c.pos.try_normalize().unwrap_or(Vec3::Y);
let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5;
let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
raw(pr.kind, Vec3::new(u * 4.0, v * 2.0, 0.0) * *scale * s, pr.seed)
}
Projection::Cylindrical { scale, axis } => {
let p = c.pos;
let (a, h, b) = match axis {
0 => (p.y, p.x, p.z),
2 => (p.x, p.z, p.y),
_ => (p.x, p.y, p.z),
};
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
raw(pr.kind, Vec3::new(u * 4.0, h, 0.0) * *scale * s, pr.seed)
}
};
shape(pr, v)
}
/// Texture coordinates (and blend weights) at which an image is sampled for a projection
/// (unused slots weigh 0; no allocation per texel).
pub fn image_samples(proj: &Projection, c: &Coords) -> [(Vec2, f32); 3] {
let one = |uv: Vec2| [(uv, 1.0), (Vec2::ZERO, 0.0), (Vec2::ZERO, 0.0)];
match proj {
Projection::Uv { scale, rotation, offset } => {
let (sn, cs) = rotation.to_radians().sin_cos();
let uv = Vec2::new(c.uv.x * cs - c.uv.y * sn, c.uv.x * sn + c.uv.y * cs) * Vec2::from(*scale) + Vec2::from(*offset);
one(uv)
}
Projection::Triplanar { scale, sharpness, offset } => {
let p = c.pos * *scale + Vec3::from(*offset);
let w = c.nrm.abs().powf(sharpness.max(1.0));
let w = w / (w.x + w.y + w.z).max(1e-6);
[(Vec2::new(p.z, -p.y), w.x), (Vec2::new(p.x, p.z), w.y), (Vec2::new(p.x, -p.y), w.z)]
}
Projection::Planar { scale, axis, offset } => {
let p = c.pos * *scale + Vec3::from(*offset);
let q = match axis {
0 => Vec2::new(p.z, -p.y),
1 => Vec2::new(p.x, p.z),
_ => Vec2::new(p.x, -p.y),
};
one(q * 0.5 + Vec2::splat(0.5))
}
Projection::Spherical { scale } => {
let d = c.pos.try_normalize().unwrap_or(Vec3::Y);
let u = d.z.atan2(d.x) / std::f32::consts::TAU + 0.5;
let v = d.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI;
one(Vec2::new(u, v) * *scale)
}
Projection::Cylindrical { scale, axis } => {
let p = c.pos;
let (a, h, b) = match axis {
0 => (p.y, p.x, p.z),
2 => (p.x, p.z, p.y),
_ => (p.x, p.y, p.z),
};
let u = b.atan2(a) / std::f32::consts::TAU + 0.5;
one(Vec2::new(u, 0.5 - h * 0.5) * *scale)
}
}
}
/// World-space noise used by generators (seamless across UV islands).
pub fn world_noise(pos: Vec3, scale: f32, seed: u32) -> f32 {
noise::fbm((pos * scale.max(1e-3)).to_array(), 4, seed, noise::perlin)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_pattern_and_projection_stays_in_range() {
let projs = [
Projection::default(),
Projection::Triplanar { scale: 1.0, sharpness: 4.0, offset: [0.0; 3] },
Projection::Planar { scale: 1.0, axis: 1, offset: [0.0; 3] },
Projection::Spherical { scale: 1.0 },
Projection::Cylindrical { scale: 1.0, axis: 1 },
];
for k in ProceduralKind::ALL {
let pr = Procedural::new(k);
for proj in &projs {
for i in 0..50 {
let t = i as f32 * 0.13;
let c = Coords {
uv: Vec2::new(t.fract(), (t * 0.7).fract()),
pos: Vec3::new(t.sin(), t.cos(), t * 0.1),
nrm: Vec3::new(0.3, 0.9, 0.1).normalize(),
};
let v = procedural(&pr, proj, &c);
assert!((0.0..=1.0).contains(&v), "{k:?} {proj:?} {v}");
}
}
}
}
#[test]
fn every_pattern_varies() {
for k in ProceduralKind::ALL {
let pr = Procedural::new(k);
let (mut lo, mut hi) = (f32::MAX, f32::MIN);
for i in 0..4096 {
let uv = Vec2::new((i % 64) as f32 / 64.0, (i / 64) as f32 / 64.0);
let v = procedural(&pr, &Projection::default(), &Coords { uv, pos: Vec3::ZERO, nrm: Vec3::Y });
(lo, hi) = (lo.min(v), hi.max(v));
}
assert!(hi - lo > 0.3, "{k:?} is flat: {lo}..{hi}");
}
}
}
+120
View File
@@ -0,0 +1,120 @@
//! Pixel data owned by a document: painted layer channels, painted mask effects and baked mesh
//! maps. Everything is copy-on-write, so cloning the store for undo is cheap.
use std::collections::{BTreeMap, HashMap};
use texturecraft_core::{BakedMap, Channel, ChannelKind, LayerId};
use texturecraft_texel::{TileImage, from_u16, from_u16_signed};
/// Painted data of one paint layer channel: premultiplied value(s) plus coverage, u16 per
/// component (height stored signed).
#[derive(Clone, Debug, Default)]
pub struct PixelStore {
/// (paint layer or content paint effect, channel) → texels.
pub layers: HashMap<(LayerId, Channel), TileImage>,
/// Paint effect of a mask → (premultiplied value, coverage).
pub masks: HashMap<LayerId, TileImage>,
}
impl PixelStore {
pub fn layer(&self, id: LayerId, c: Channel) -> Option<&TileImage> {
self.layers.get(&(id, c))
}
/// The image for `(id, c)` at `res`, created empty if missing or of another size.
pub fn layer_mut(&mut self, id: LayerId, c: Channel, res: u32) -> &mut TileImage {
let img = self.layers.entry((id, c)).or_insert_with(|| TileImage::new(res, res, c.components() + 1));
if img.width() != res {
*img = TileImage::new(res, res, c.components() + 1);
}
img
}
pub fn mask_mut(&mut self, id: LayerId, res: u32) -> &mut TileImage {
let img = self.masks.entry(id).or_insert_with(|| TileImage::new(res, res, 2));
if img.width() != res {
*img = TileImage::new(res, res, 2);
}
img
}
/// Drop pixels of layers that no longer exist.
pub fn retain(&mut self, alive: impl Fn(LayerId) -> bool) {
self.layers.retain(|(id, _), _| alive(*id));
self.masks.retain(|id, _| alive(*id));
}
pub fn bytes(&self) -> usize {
self.layers.values().chain(self.masks.values()).map(TileImage::bytes).sum()
}
}
/// Decode a stored component of channel kind `kind` to its float value.
#[inline]
pub fn decode(kind: ChannelKind, v: u16) -> f32 {
if kind == ChannelKind::Signed { from_u16_signed(v) } else { from_u16(v) }
}
/// Baked mesh maps of one texture set (dense, row-major, `components()` floats per texel).
#[derive(Clone, Debug, Default, PartialEq)]
pub struct BakedMaps {
pub resolution: u32,
pub maps: BTreeMap<BakedMap, std::sync::Arc<Vec<f32>>>,
}
impl BakedMaps {
/// Sample map `m` at texel (x, y) of an image `res` wide (nearest texel of the bake).
pub fn sample(&self, m: BakedMap, x: u32, y: u32, res: u32) -> Option<[f32; 3]> {
let data = self.maps.get(&m)?;
let r = self.resolution.max(1) as u64;
let (bx, by) = ((x as u64 * r / res.max(1) as u64).min(r - 1), (y as u64 * r / res.max(1) as u64).min(r - 1));
let comps = m.components();
let i = ((by * r + bx) as usize) * comps;
let s = data.get(i..i + comps)?;
Some(if comps == 3 { [s[0], s[1], s[2]] } else { [s[0]; 3] })
}
pub fn scalar(&self, m: BakedMap, x: u32, y: u32, res: u32) -> Option<f32> {
self.sample(m, x, y, res).map(|v| v[0])
}
}
/// A decoded image resource sampled by fills (values in the file's encoding; see `srgb`).
#[derive(Clone, Debug, PartialEq)]
pub struct ImageRes {
pub width: u32,
pub height: u32,
pub rgba: Vec<[f32; 4]>,
/// 8/16-bit images are sRGB-encoded; color channels linearize them.
pub srgb: bool,
}
/// Image resources by name.
pub type ImageStore = HashMap<String, std::sync::Arc<ImageRes>>;
impl ImageRes {
fn texel(&self, x: i64, y: i64) -> [f32; 4] {
let (w, h) = (self.width.max(1) as i64, self.height.max(1) as i64);
let i = (y.rem_euclid(h) * w + x.rem_euclid(w)) as usize;
self.rgba.get(i).copied().unwrap_or([0.0; 4])
}
/// Bilinear sample with wrap-around (texture coordinates, v down).
pub fn sample(&self, u: f32, v: f32) -> [f32; 4] {
if !u.is_finite() || !v.is_finite() {
return [0.0; 4];
}
let fx = u * self.width as f32 - 0.5;
let fy = v * self.height as f32 - 0.5;
let (x0, y0) = (fx.floor() as i64, fy.floor() as i64);
let (tx, ty) = (fx - fx.floor(), fy - fy.floor());
let (a, b, c, d) = (self.texel(x0, y0), self.texel(x0 + 1, y0), self.texel(x0, y0 + 1), self.texel(x0 + 1, y0 + 1));
let mut out = [0.0; 4];
for k in 0..4 {
let top = a[k] + (b[k] - a[k]) * tx;
let bot = c[k] + (d[k] - c[k]) * tx;
out[k] = top + (bot - top) * ty;
}
out
}
}
+201
View File
@@ -0,0 +1,201 @@
//! The below-stack cache and blocked compositing give exactly the unoptimized result; instance
//! layers draw their source; masks combine with height.
use texturecraft_compose::{BelowCache, Composite, Inputs, PixelStore, all_tiles, composite_tiles, composite_tiles_cached};
use texturecraft_core::{
BlendMode, Channel, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Mask, MaskBackground, Procedural,
ProceduralKind, Project, Projection, Source, TextureSet,
};
use texturecraft_geom::{Mesh, UvGBuffer, primitives};
use texturecraft_texel::{TILE, to_u16};
const RES: u32 = 256;
struct Fixture {
project: Project,
mesh: Mesh,
gbuf: UvGBuffer,
pixels: PixelStore,
}
fn fixture() -> Fixture {
let mesh = primitives::sphere(1.0, 32, 16);
let gbuf = UvGBuffer::new(&mesh, 0, RES, RES);
let mut project = Project::new("t", "builtin:sphere");
project.texture_sets.push(TextureSet::new("A", 0, RES));
project.texture_sets.push(TextureSet::new("B", 0, RES));
Fixture { project, mesh, gbuf, pixels: PixelStore::default() }
}
fn procedural(kind: ProceduralKind, low: f32, high: f32) -> Source {
Source::Procedural { pattern: Procedural::new(kind), low: [low; 3], high: [high; 3] }
}
fn add(f: &mut Fixture, ts: usize, kind: LayerKind, mask: Option<Mask>) -> LayerId {
let id = f.project.alloc_id();
let mut l = Layer::new(id, "l", kind, &Channel::DEFAULT_SET);
l.mask = mask;
f.project.insert_layer(ts, l, None, false).unwrap()
}
fn fill(sources: &[(Channel, Source)]) -> LayerKind {
let mut f = Fill::default();
f.sources = sources.iter().cloned().collect();
LayerKind::Fill(f)
}
fn effect(f: &mut Fixture, kind: EffectKind) -> Effect {
Effect::new(f.project.alloc_id(), kind)
}
/// Procedural fills, a generator mask with a blur, a folder, painted pixels; returns the top
/// paint layer.
fn heavy_stack(f: &mut Fixture) -> LayerId {
add(
f,
0,
fill(&[(Channel::BaseColor, procedural(ProceduralKind::Clouds, 0.1, 0.9)), (Channel::Height, procedural(ProceduralKind::Cells, -0.3, 0.3))]),
None,
);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(f, EffectKind::Generator(Generator::new(GeneratorKind::Position))));
mask.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 40.0 })));
add(f, 0, fill(&[(Channel::Roughness, procedural(ProceduralKind::Grunge, 0.0, 1.0))]), Some(mask));
let group = add(f, 0, LayerKind::Group { children: vec![], collapsed: false }, None);
for b in f.project.layer_mut(group).unwrap().channels.values_mut() {
b.mode = BlendMode::Passthrough;
}
let inner = f.project.alloc_id();
let l = Layer::new(inner, "inner", fill(&[(Channel::Metallic, procedural(ProceduralKind::Scratches, 0.0, 1.0))]), &Channel::DEFAULT_SET);
f.project.insert_layer(0, l, Some(group), true).unwrap();
let mut blurred = Mask::new(MaskBackground::Black);
blurred.effects.push(effect(f, EffectKind::Fill { source: procedural(ProceduralKind::Checker, 0.0, 1.0), projection: Projection::default() }));
blurred.effects.push(effect(f, EffectKind::Filter(Filter::Blur { radius: 24.0 })));
let top = add(f, 0, LayerKind::Paint, Some(blurred));
let img = f.pixels.layer_mut(top, Channel::BaseColor, RES);
for y in 40..200 {
for x in 30..220 {
img.set(x, y, &[to_u16(0.4), to_u16(0.1), 0, to_u16(0.5)]);
}
}
top
}
fn inputs<'a>(f: &'a Fixture, ts: usize, images: &'a texturecraft_compose::ImageStore, baked: &'a texturecraft_compose::BakedMaps) -> Inputs<'a> {
Inputs { project: &f.project, ts, mesh: &f.mesh, gbuf: &f.gbuf, pixels: &f.pixels, baked, preview: None, images, bounds: f.mesh.bounds() }
}
fn run(f: &Fixture, ts: usize, tiles: &[(u32, u32)], below: Option<&mut BelowCache>) -> Composite {
let (images, baked) = (Default::default(), Default::default());
let mut out = Composite::new(&f.project.texture_sets[ts].channel_list(), RES);
composite_tiles_cached(&inputs(f, ts, &images, &baked), &mut out, tiles, below);
out
}
fn reference(f: &Fixture, ts: usize) -> Composite {
let (images, baked) = (Default::default(), Default::default());
let mut out = Composite::new(&f.project.texture_sets[ts].channel_list(), RES);
composite_tiles(&inputs(f, ts, &images, &baked), &mut out, &all_tiles(RES));
out
}
#[test]
fn below_cache_and_blocks_match_the_full_composite_exactly() {
let mut f = fixture();
let top = heavy_stack(&mut f);
let want = reference(&f, 0);
// Tile by tile (each its own block and neighbourhood region) gives the same bits.
let mut one_by_one = Composite::new(&f.project.texture_sets[0].channel_list(), RES);
let (images, baked) = (Default::default(), Default::default());
for t in all_tiles(RES) {
composite_tiles(&inputs(&f, 0, &images, &baked), &mut one_by_one, &[t]);
}
assert!(one_by_one == want, "per-tile composites differ from one pass");
let mut cache = BelowCache::default();
cache.set_hot(Some(top));
let half: Vec<(u32, u32)> = all_tiles(RES).into_iter().filter(|t| (t.0 + t.1) % 2 == 0).collect();
// Cold, half warm and fully warm caches.
let mut out = run(&f, 0, &half, Some(&mut cache));
assert!(!cache.is_empty(), "the stack below the hot layer is cached");
composite_tiles_cached(&inputs(&f, 0, &images, &baked), &mut out, &all_tiles(RES), Some(&mut cache));
assert!(out == want, "a partly cached composite differs");
let warm = run(&f, 0, &all_tiles(RES), Some(&mut cache));
assert!(warm == want, "a cached composite differs");
// Painting the hot layer keeps the cache; editing below it empties it.
f.pixels.layer_mut(top, Channel::BaseColor, RES).set(5, 5, &[to_u16(1.0), 0, 0, to_u16(1.0)]);
let n = cache.len();
assert!(run(&f, 0, &all_tiles(RES), Some(&mut cache)) == reference(&f, 0));
assert_eq!(cache.len(), n);
let low = f.project.texture_sets[0].stack[0];
if let LayerKind::Fill(fl) = &mut f.project.layer_mut(low).unwrap().kind {
fl.sources.insert(Channel::Roughness, Source::Uniform([0.9; 3]));
}
assert!(run(&f, 0, &all_tiles(RES), Some(&mut cache)) == reference(&f, 0), "a stale cache was used");
// A hot layer inside a folder caches below the folder.
let group = f.project.texture_sets[0].stack[2];
let inner = f.project.layer(group).unwrap().children()[0];
cache.set_hot(Some(inner));
run(&f, 0, &all_tiles(RES), Some(&mut cache));
assert!(!cache.is_empty());
assert!(run(&f, 0, &all_tiles(RES), Some(&mut cache)) == reference(&f, 0));
}
#[test]
fn instances_draw_their_source_across_texture_sets() {
let mut f = fixture();
let top = heavy_stack(&mut f);
// Set B instances every top-level layer of set A: same composite.
for id in f.project.texture_sets[0].stack.clone() {
add(&mut f, 1, LayerKind::Instance { source: id }, None);
}
let a = reference(&f, 0);
assert!(reference(&f, 1).channels == a.channels, "instances draw like their sources");
// An edit to the source shows in the instance.
f.pixels.layer_mut(top, Channel::BaseColor, RES).set(100, 100, &[to_u16(1.0), 0, 0, to_u16(1.0)]);
let (a, b) = (reference(&f, 0), reference(&f, 1));
assert!(b.channels == a.channels);
// The instance's own mask overrides the source's.
let inst = *f.project.texture_sets[1].stack.last().unwrap();
f.project.layer_mut(inst).unwrap().mask = Some(Mask::new(MaskBackground::Black));
let b = reference(&f, 1);
let (x, y) = (100, 100);
assert!((a.value(Channel::BaseColor, x, y)[0] - b.value(Channel::BaseColor, x, y)[0]).abs() > 0.1);
// A hidden instance or a missing source draws nothing.
let mut g = fixture();
let src = add(&mut g, 0, fill(&[(Channel::Roughness, Source::Uniform([0.9; 3]))]), None);
let inst = add(&mut g, 1, LayerKind::Instance { source: src }, None);
assert!((reference(&g, 1).value(Channel::Roughness, 128, 128)[0] - 0.9).abs() < 1e-3);
g.project.layer_mut(inst).unwrap().visible = false;
assert!((reference(&g, 1).value(Channel::Roughness, 128, 128)[0] - 0.5).abs() < 1e-3);
g.project.layer_mut(inst).unwrap().visible = true;
g.project.layers.remove(&src);
assert!((reference(&g, 1).value(Channel::Roughness, 128, 128)[0] - 0.5).abs() < 1e-3);
}
#[test]
fn mask_with_height_follows_the_layer_height() {
let mut f = fixture();
// A white layer over the default gray, half masked, its height falling from 0.25 (left) to
// -0.25 (right).
let mut ramp = Procedural::new(ProceduralKind::Gradient);
ramp.scale = 1.0;
let height = Source::Procedural { pattern: ramp, low: [0.25; 3], high: [-0.25; 3] };
let id = add(&mut f, 0, fill(&[(Channel::BaseColor, Source::Uniform([1.0; 3])), (Channel::Height, height)]), None);
let mut mask = Mask::new(MaskBackground::Black);
mask.effects.push(effect(&mut f, EffectKind::Fill { source: Source::Uniform([0.5; 3]), projection: Projection::default() }));
f.project.layer_mut(id).unwrap().mask = Some(mask);
let plain = reference(&f, 0);
f.project.layer_mut(id).unwrap().height_mask = HeightMask { enabled: true, contrast: 1.0, offset: 0.0 };
let hm = reference(&f, 0);
let row = TILE * 2;
let (left, right) = (16, RES - 16);
let v = |c: &Composite, x| c.value(Channel::BaseColor, x, row)[0];
assert!((v(&plain, left) - 0.75).abs() < 0.01 && (v(&plain, right) - 0.75).abs() < 0.01, "plain mask: 50 % white over gray");
assert!(v(&hm, left) > 0.84, "high parts show first: {}", v(&hm, left));
assert!(v(&hm, right) < 0.66, "low parts later: {}", v(&hm, right));
// Without a mask there is nothing to combine.
f.project.layer_mut(id).unwrap().mask.as_mut().unwrap().enabled = false;
assert!((v(&reference(&f, 0), left) - 1.0).abs() < 1e-3);
}
+14
View File
@@ -0,0 +1,14 @@
[package]
name = "texturecraft-core"
description = "TextureCraft document model: projects, texture sets, channels, layers, masks, effects and blend math"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+441
View File
@@ -0,0 +1,441 @@
//! Per-channel blend modes and their CPU reference math (straight values, linear space).
//!
//! `a` is the value below (the stack so far), `b` the layer's value. The compositor mixes the
//! result back over `a` by `coverage × opacity × mask`.
use serde::{Deserialize, Serialize};
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Default)]
pub enum BlendMode {
#[default]
Normal,
Passthrough,
Disable,
Replace,
Multiply,
Divide,
InverseDivide,
Darken,
Lighten,
LinearDodge,
Subtract,
InverseSubtract,
Difference,
Exclusion,
SignedAddition,
Overlay,
Screen,
LinearBurn,
ColorBurn,
ColorDodge,
SoftLight,
HardLight,
VividLight,
LinearLight,
PinLight,
Tint,
Saturation,
Color,
Value,
NormalMapCombine,
NormalMapDetail,
NormalMapInverseDetail,
}
impl BlendMode {
/// Every mode in menu order; `None` entries are the separators between menu groups.
pub const MENU: [Option<BlendMode>; 39] = [
Some(BlendMode::Normal),
Some(BlendMode::Passthrough),
Some(BlendMode::Disable),
Some(BlendMode::Replace),
None,
Some(BlendMode::Multiply),
Some(BlendMode::Divide),
Some(BlendMode::InverseDivide),
Some(BlendMode::Darken),
Some(BlendMode::Lighten),
None,
Some(BlendMode::LinearDodge),
Some(BlendMode::Subtract),
Some(BlendMode::InverseSubtract),
Some(BlendMode::Difference),
Some(BlendMode::Exclusion),
Some(BlendMode::SignedAddition),
None,
Some(BlendMode::Overlay),
Some(BlendMode::Screen),
Some(BlendMode::LinearBurn),
Some(BlendMode::ColorBurn),
Some(BlendMode::ColorDodge),
None,
Some(BlendMode::SoftLight),
Some(BlendMode::HardLight),
Some(BlendMode::VividLight),
Some(BlendMode::LinearLight),
Some(BlendMode::PinLight),
None,
Some(BlendMode::Tint),
Some(BlendMode::Saturation),
Some(BlendMode::Color),
Some(BlendMode::Value),
None,
Some(BlendMode::NormalMapCombine),
Some(BlendMode::NormalMapDetail),
Some(BlendMode::NormalMapInverseDetail),
None,
];
pub fn all() -> impl Iterator<Item = BlendMode> {
BlendMode::MENU.into_iter().flatten()
}
pub fn label(self) -> &'static str {
match self {
BlendMode::Normal => "Normal",
BlendMode::Passthrough => "Passthrough",
BlendMode::Disable => "Disable",
BlendMode::Replace => "Replace",
BlendMode::Multiply => "Multiply",
BlendMode::Divide => "Divide",
BlendMode::InverseDivide => "Inverse divide",
BlendMode::Darken => "Darken (Min)",
BlendMode::Lighten => "Lighten (Max)",
BlendMode::LinearDodge => "Linear dodge (Add)",
BlendMode::Subtract => "Subtract",
BlendMode::InverseSubtract => "Inverse Subtract",
BlendMode::Difference => "Difference",
BlendMode::Exclusion => "Exclusion",
BlendMode::SignedAddition => "Signed addition (AddSub)",
BlendMode::Overlay => "Overlay",
BlendMode::Screen => "Screen",
BlendMode::LinearBurn => "Linear burn",
BlendMode::ColorBurn => "Color burn",
BlendMode::ColorDodge => "Color dodge",
BlendMode::SoftLight => "Soft light",
BlendMode::HardLight => "Hard light",
BlendMode::VividLight => "Vivid light",
BlendMode::LinearLight => "Linear light",
BlendMode::PinLight => "Pin light",
BlendMode::Tint => "Tint",
BlendMode::Saturation => "Saturation",
BlendMode::Color => "Color",
BlendMode::Value => "Value",
BlendMode::NormalMapCombine => "Normal map combine",
BlendMode::NormalMapDetail => "Normal map detail",
BlendMode::NormalMapInverseDetail => "Normal map inverse detail",
}
}
/// Four-letter abbreviation shown in the compact layer row ("Norm", "Mult", …).
pub fn short(self) -> &'static str {
match self {
BlendMode::Normal => "Norm",
BlendMode::Passthrough => "Pass",
BlendMode::Disable => "Dis",
BlendMode::Replace => "Repl",
BlendMode::Multiply => "Mult",
BlendMode::Divide => "Div",
BlendMode::InverseDivide => "IDiv",
BlendMode::Darken => "Dark",
BlendMode::Lighten => "Ligh",
BlendMode::LinearDodge => "Add",
BlendMode::Subtract => "Sub",
BlendMode::InverseSubtract => "ISub",
BlendMode::Difference => "Diff",
BlendMode::Exclusion => "Excl",
BlendMode::SignedAddition => "AdSb",
BlendMode::Overlay => "Over",
BlendMode::Screen => "Scrn",
BlendMode::LinearBurn => "LBrn",
BlendMode::ColorBurn => "CBrn",
BlendMode::ColorDodge => "CDdg",
BlendMode::SoftLight => "SftL",
BlendMode::HardLight => "HrdL",
BlendMode::VividLight => "VivL",
BlendMode::LinearLight => "LinL",
BlendMode::PinLight => "PinL",
BlendMode::Tint => "Tint",
BlendMode::Saturation => "Sat",
BlendMode::Color => "Colr",
BlendMode::Value => "Val",
BlendMode::NormalMapCombine => "NmCb",
BlendMode::NormalMapDetail => "NmDt",
BlendMode::NormalMapInverseDetail => "NmID",
}
}
/// Parse a label, short label or variant name (case-insensitive; punctuation ignored).
pub fn parse(s: &str) -> Option<BlendMode> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', '(', ')'], "");
let want = norm(s);
BlendMode::all().find(|m| norm(m.label()) == want || norm(m.short()) == want || norm(&format!("{m:?}")) == want)
}
/// Modes that need all three components at once.
pub fn is_non_separable(self) -> bool {
matches!(
self,
BlendMode::Tint
| BlendMode::Saturation
| BlendMode::Color
| BlendMode::Value
| BlendMode::NormalMapCombine
| BlendMode::NormalMapDetail
| BlendMode::NormalMapInverseDetail
)
}
}
fn color_burn(a: f32, b: f32) -> f32 {
if a >= 1.0 {
1.0
} else if b <= 0.0 {
0.0
} else {
1.0 - ((1.0 - a) / b).min(1.0)
}
}
fn color_dodge(a: f32, b: f32) -> f32 {
if a <= 0.0 {
0.0
} else if b >= 1.0 {
1.0
} else {
(a / (1.0 - b)).min(1.0)
}
}
fn soft_light(a: f32, b: f32) -> f32 {
let (a, b) = (a.clamp(0.0, 1.0), b.clamp(0.0, 1.0));
if b <= 0.5 {
return a - (1.0 - 2.0 * b) * a * (1.0 - a);
}
let d = if a <= 0.25 { ((16.0 * a - 12.0) * a + 4.0) * a } else { a.sqrt() };
a + (2.0 * b - 1.0) * (d - a)
}
fn overlay(a: f32, b: f32) -> f32 {
if a < 0.5 { 2.0 * a * b } else { 1.0 - 2.0 * (1.0 - a) * (1.0 - b) }
}
/// One component of a separable blend. Non-separable modes fall back to `Normal`.
pub fn blend1(mode: BlendMode, a: f32, b: f32) -> f32 {
match mode {
BlendMode::Normal | BlendMode::Passthrough | BlendMode::Replace => b,
BlendMode::Disable => a,
BlendMode::Multiply => a * b,
BlendMode::Divide => a / b.max(1e-6),
BlendMode::InverseDivide => b / a.max(1e-6),
BlendMode::Darken => a.min(b),
BlendMode::Lighten => a.max(b),
BlendMode::LinearDodge => a + b,
BlendMode::Subtract => a - b,
BlendMode::InverseSubtract => b - a,
BlendMode::Difference => (a - b).abs(),
BlendMode::Exclusion => a + b - 2.0 * a * b,
BlendMode::SignedAddition | BlendMode::LinearLight => a + 2.0 * b - 1.0,
BlendMode::Overlay => overlay(a, b),
BlendMode::Screen => 1.0 - (1.0 - a) * (1.0 - b),
BlendMode::LinearBurn => a + b - 1.0,
BlendMode::ColorBurn => color_burn(a, b),
BlendMode::ColorDodge => color_dodge(a, b),
BlendMode::SoftLight => soft_light(a, b),
BlendMode::HardLight => overlay(b, a),
BlendMode::VividLight => {
if b < 0.5 {
color_burn(a, 2.0 * b)
} else {
color_dodge(a, 2.0 * (b - 0.5))
}
}
BlendMode::PinLight => {
if b < 0.5 {
a.min(2.0 * b)
} else {
a.max(2.0 * b - 1.0)
}
}
BlendMode::Tint
| BlendMode::Saturation
| BlendMode::Color
| BlendMode::Value
| BlendMode::NormalMapCombine
| BlendMode::NormalMapDetail
| BlendMode::NormalMapInverseDetail => b,
}
}
/// Luminance of a color (the W3C non-separable blend weights).
pub fn lum(c: [f32; 3]) -> f32 {
0.3 * c[0] + 0.59 * c[1] + 0.11 * c[2]
}
fn clip_color(c: [f32; 3]) -> [f32; 3] {
let l = lum(c);
let n = c[0].min(c[1]).min(c[2]);
let x = c[0].max(c[1]).max(c[2]);
let mut out = c;
if n < 0.0 && l - n > 1e-6 {
out = out.map(|v| l + (v - l) * l / (l - n));
}
if x > 1.0 && x - l > 1e-6 {
out = out.map(|v| l + (v - l) * (1.0 - l) / (x - l));
}
out
}
fn set_lum(c: [f32; 3], l: f32) -> [f32; 3] {
let d = l - lum(c);
clip_color(c.map(|v| v + d))
}
fn sat(c: [f32; 3]) -> f32 {
c[0].max(c[1]).max(c[2]) - c[0].min(c[1]).min(c[2])
}
fn set_sat(c: [f32; 3], s: f32) -> [f32; 3] {
let mx = c[0].max(c[1]).max(c[2]);
let mn = c[0].min(c[1]).min(c[2]);
if mx - mn <= 1e-6 {
return [0.0; 3];
}
c.map(|v| (v - mn) * s / (mx - mn))
}
fn unpack(n: [f32; 3]) -> [f32; 3] {
n.map(|v| v * 2.0 - 1.0)
}
fn pack(n: [f32; 3]) -> [f32; 3] {
let len = (n[0] * n[0] + n[1] * n[1] + n[2] * n[2]).sqrt().max(1e-6);
n.map(|v| v / len * 0.5 + 0.5)
}
/// Reoriented normal mapping (Barré-Brisebois & Hill): `detail` re-oriented onto `base`.
fn rnm(base: [f32; 3], detail: [f32; 3]) -> [f32; 3] {
let t = unpack(base);
let t = [t[0], t[1], t[2] + 1.0];
let u = unpack(detail);
let u = [-u[0], -u[1], u[2]];
let d = t[0] * u[0] + t[1] * u[1] + t[2] * u[2];
pack([t[0] * d - u[0] * t[2], t[1] * d - u[1] * t[2], t[2] * d - u[2] * t[2]])
}
/// A three-component blend, including the non-separable modes.
pub fn blend3(mode: BlendMode, a: [f32; 3], b: [f32; 3]) -> [f32; 3] {
match mode {
BlendMode::Color => set_lum(b, lum(a)),
BlendMode::Saturation => set_lum(set_sat(a, sat(b)), lum(a)),
BlendMode::Value => {
let va = a[0].max(a[1]).max(a[2]);
let vb = b[0].max(b[1]).max(b[2]);
if va <= 1e-6 { [vb; 3] } else { a.map(|v| v * vb / va) }
}
BlendMode::Tint => {
let l = lum(a);
b.map(|v| v * l)
}
BlendMode::NormalMapCombine => {
let (na, nb) = (unpack(a), unpack(b));
pack([na[0] + nb[0], na[1] + nb[1], na[2] * nb[2]])
}
BlendMode::NormalMapDetail => rnm(a, b),
BlendMode::NormalMapInverseDetail => rnm(b, a),
_ => [blend1(mode, a[0], b[0]), blend1(mode, a[1], b[1]), blend1(mode, a[2], b[2])],
}
}
/// Mix `blended` over `a` by weight `w` (coverage × opacity × mask).
pub fn mix3(a: [f32; 3], blended: [f32; 3], w: f32) -> [f32; 3] {
[a[0] + (blended[0] - a[0]) * w, a[1] + (blended[1] - a[1]) * w, a[2] + (blended[2] - a[2]) * w]
}
#[cfg(test)]
mod tests {
use super::*;
const AS: [f32; 4] = [0.0, 0.25, 0.5, 1.0];
const BS: [f32; 4] = [0.0, 0.3, 0.7, 1.0];
fn close(a: f32, b: f32) -> bool {
(a - b).abs() < 1e-5
}
#[test]
fn separable_modes_match_hand_computed_values() {
for a in AS {
for b in BS {
assert!(close(blend1(BlendMode::Normal, a, b), b));
assert!(close(blend1(BlendMode::Disable, a, b), a));
assert!(close(blend1(BlendMode::Multiply, a, b), a * b));
assert!(close(blend1(BlendMode::Screen, a, b), 1.0 - (1.0 - a) * (1.0 - b)));
assert!(close(blend1(BlendMode::LinearDodge, a, b), a + b));
assert!(close(blend1(BlendMode::Subtract, a, b), a - b));
assert!(close(blend1(BlendMode::Darken, a, b), a.min(b)));
assert!(close(blend1(BlendMode::Lighten, a, b), a.max(b)));
assert!(close(blend1(BlendMode::Difference, a, b), (a - b).abs()));
assert!(close(blend1(BlendMode::Exclusion, a, b), a + b - 2.0 * a * b));
}
}
assert!(close(blend1(BlendMode::Overlay, 0.25, 0.3), 2.0 * 0.25 * 0.3));
assert!(close(blend1(BlendMode::Overlay, 0.5, 0.7), 1.0 - 2.0 * 0.5 * 0.3));
assert!(close(blend1(BlendMode::HardLight, 0.7, 0.25), 2.0 * 0.25 * 0.7));
}
#[test]
fn soft_light_matches_w3c() {
assert!(close(blend1(BlendMode::SoftLight, 0.25, 0.3), 0.25 - 0.4 * 0.25 * 0.75));
let d = ((16.0 * 0.25 - 12.0) * 0.25 + 4.0) * 0.25;
assert!(close(blend1(BlendMode::SoftLight, 0.25, 0.7), 0.25 + 0.4 * (d - 0.25)));
assert!(close(blend1(BlendMode::SoftLight, 0.5, 0.7), 0.5 + 0.4 * (0.5f32.sqrt() - 0.5)));
}
#[test]
fn burns_and_dodges_handle_edges() {
assert!(close(blend1(BlendMode::ColorBurn, 1.0, 0.0), 1.0));
assert!(close(blend1(BlendMode::ColorBurn, 0.5, 0.0), 0.0));
assert!(close(blend1(BlendMode::ColorDodge, 0.0, 1.0), 0.0));
assert!(close(blend1(BlendMode::ColorDodge, 0.5, 1.0), 1.0));
assert!(close(blend1(BlendMode::ColorDodge, 0.25, 0.5), 0.5));
for m in BlendMode::all() {
for a in AS {
for b in BS {
assert!(blend1(m, a, b).is_finite(), "{m:?} {a} {b}");
assert!(blend3(m, [a; 3], [b; 3]).iter().all(|v| v.is_finite()), "{m:?}");
}
}
}
}
#[test]
fn color_keeps_lower_luminance() {
let a = [0.2, 0.4, 0.6];
let out = blend3(BlendMode::Color, a, [1.0, 0.0, 0.0]);
assert!(close(lum(out), lum(a)));
}
#[test]
fn flat_normal_detail_is_identity() {
let flat = [0.5, 0.5, 1.0];
let n = pack([0.3, -0.2, 0.9]);
for m in [BlendMode::NormalMapDetail, BlendMode::NormalMapCombine] {
let out = blend3(m, n, flat);
for i in 0..3 {
assert!((out[i] - n[i]).abs() < 1e-4, "{m:?} {out:?} {n:?}");
}
}
}
#[test]
fn menu_lists_each_mode_once_and_parse_round_trips() {
let all: Vec<_> = BlendMode::all().collect();
assert_eq!(all.len(), 32);
for m in &all {
assert_eq!(all.iter().filter(|x| *x == m).count(), 1);
assert_eq!(BlendMode::parse(m.label()), Some(*m));
assert_eq!(BlendMode::parse(&format!("{m:?}")), Some(*m));
}
}
}
+206
View File
@@ -0,0 +1,206 @@
//! Material channels of a texture set.
use serde::{Deserialize, Serialize};
/// A material channel. Order is the display order in the UI.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum Channel {
BaseColor,
Metallic,
Roughness,
Normal,
Height,
Emissive,
Opacity,
AmbientOcclusion,
SpecularLevel,
/// Specular/glossiness workflow: the F0 color.
Specular,
/// Specular/glossiness workflow: 1 − roughness.
Glossiness,
}
/// How a channel's values are stored and interpreted.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChannelKind {
/// Linear RGB color, displayed and exported sRGB-encoded.
Color,
/// Tangent-space normal packed into 0..1 (`n * 0.5 + 0.5`).
NormalMap,
/// A 0..1 scalar.
Scalar,
/// A signed scalar (height).
Signed,
}
impl Channel {
pub const ALL: [Channel; 11] = [
Channel::BaseColor,
Channel::Metallic,
Channel::Roughness,
Channel::Normal,
Channel::Height,
Channel::Emissive,
Channel::Opacity,
Channel::AmbientOcclusion,
Channel::SpecularLevel,
Channel::Specular,
Channel::Glossiness,
];
/// The channels of the default "PBR - Metallic Roughness" template.
pub const DEFAULT_SET: [Channel; 5] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Normal, Channel::Height];
pub fn kind(self) -> ChannelKind {
match self {
Channel::BaseColor | Channel::Emissive | Channel::Specular => ChannelKind::Color,
Channel::Normal => ChannelKind::NormalMap,
Channel::Height => ChannelKind::Signed,
_ => ChannelKind::Scalar,
}
}
/// Value components (without coverage): 3 for colors and normals, 1 for scalars.
pub fn components(self) -> usize {
match self.kind() {
ChannelKind::Color | ChannelKind::NormalMap => 3,
ChannelKind::Scalar | ChannelKind::Signed => 1,
}
}
/// The value a texel has when no layer covers it.
pub fn default_value(self) -> [f32; 3] {
match self {
Channel::BaseColor => [0.5, 0.5, 0.5],
Channel::Metallic | Channel::Height | Channel::Emissive => [0.0; 3],
Channel::Roughness => [0.5; 3],
Channel::Normal => [0.5, 0.5, 1.0],
Channel::Opacity | Channel::AmbientOcclusion => [1.0; 3],
Channel::SpecularLevel | Channel::Glossiness => [0.5; 3],
// F0 of a common dielectric (4 %).
Channel::Specular => [0.04; 3],
}
}
pub fn label(self) -> &'static str {
match self {
Channel::BaseColor => "Base color",
Channel::Metallic => "Metallic",
Channel::Roughness => "Roughness",
Channel::Normal => "Normal",
Channel::Height => "Height",
Channel::Emissive => "Emissive",
Channel::Opacity => "Opacity",
Channel::AmbientOcclusion => "Ambient occlusion",
Channel::SpecularLevel => "Specular level",
Channel::Specular => "Specular",
Channel::Glossiness => "Glossiness",
}
}
/// Short label used on material channel toggle buttons.
pub fn short(self) -> &'static str {
match self {
Channel::BaseColor => "color",
Channel::Metallic => "metal",
Channel::Roughness => "rough",
Channel::Normal => "nrm",
Channel::Height => "height",
Channel::Emissive => "emiss",
Channel::Opacity => "op",
Channel::AmbientOcclusion => "ao",
Channel::SpecularLevel => "spec",
Channel::Specular => "specular",
Channel::Glossiness => "gloss",
}
}
/// Stable machine id (commands, export templates, file names).
pub fn id(self) -> &'static str {
match self {
Channel::BaseColor => "baseColor",
Channel::Metallic => "metallic",
Channel::Roughness => "roughness",
Channel::Normal => "normal",
Channel::Height => "height",
Channel::Emissive => "emissive",
Channel::Opacity => "opacity",
Channel::AmbientOcclusion => "ambientOcclusion",
Channel::SpecularLevel => "specularLevel",
Channel::Specular => "specular",
Channel::Glossiness => "glossiness",
}
}
/// Parse an id, label or short label (case-insensitive, spaces/underscores ignored).
pub fn parse(s: &str) -> Option<Channel> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], "");
let want = norm(s);
Channel::ALL.into_iter().find(|c| norm(c.id()) == want || norm(c.label()) == want || norm(c.short()) == want || norm(&format!("{c:?}")) == want)
}
pub fn index(self) -> usize {
Channel::ALL.iter().position(|c| *c == self).unwrap_or(0)
}
}
/// Storage format of a channel in a texture set (what export and the UI report).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum ChannelFormat {
Srgb8,
L8,
Rgb8,
L16,
Rgb16,
L16F,
Rgb16F,
L32F,
Rgb32F,
}
impl ChannelFormat {
pub fn default_for(c: Channel) -> ChannelFormat {
match c.kind() {
ChannelKind::Color => ChannelFormat::Srgb8,
ChannelKind::NormalMap => ChannelFormat::Rgb16F,
ChannelKind::Scalar => ChannelFormat::L8,
ChannelKind::Signed => ChannelFormat::L16F,
}
}
pub fn label(self) -> &'static str {
match self {
ChannelFormat::Srgb8 => "sRGB8",
ChannelFormat::L8 => "L8",
ChannelFormat::Rgb8 => "RGB8",
ChannelFormat::L16 => "L16",
ChannelFormat::Rgb16 => "RGB16",
ChannelFormat::L16F => "L16F",
ChannelFormat::Rgb16F => "RGB16F",
ChannelFormat::L32F => "L32F",
ChannelFormat::Rgb32F => "RGB32F",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parse_accepts_ids_labels_and_shorts() {
for c in Channel::ALL {
assert_eq!(Channel::parse(c.id()), Some(c));
assert_eq!(Channel::parse(c.label()), Some(c));
assert_eq!(Channel::parse(c.short()), Some(c));
}
assert_eq!(Channel::parse("base color"), Some(Channel::BaseColor));
assert_eq!(Channel::parse("nope"), None);
}
#[test]
fn index_matches_all_order() {
for (i, c) in Channel::ALL.iter().enumerate() {
assert_eq!(c.index(), i);
}
}
}
+716
View File
@@ -0,0 +1,716 @@
//! Layers, masks, effects and fill sources.
use std::collections::BTreeMap;
use serde::{Deserialize, Serialize};
use crate::{BlendMode, Channel};
/// Id of a layer or effect (one id space per project).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub struct LayerId(pub u64);
/// Blend mode and opacity of one channel of a layer. A channel missing from
/// [`Layer::channels`] is disabled for that layer.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct ChannelBlend {
pub mode: BlendMode,
pub opacity: f32,
}
impl Default for ChannelBlend {
fn default() -> Self {
ChannelBlend { mode: BlendMode::Normal, opacity: 1.0 }
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Layer {
pub id: LayerId,
pub name: String,
pub visible: bool,
pub kind: LayerKind,
pub channels: BTreeMap<Channel, ChannelBlend>,
#[serde(default)]
pub mask: Option<Mask>,
/// Effects applied to the layer's content, bottom → top.
#[serde(default)]
pub content_effects: Vec<Effect>,
/// Painter-style color tag (0..8), shown as a stripe on the layer row.
#[serde(default)]
pub color_tag: Option<u8>,
/// Combine the mask with the layer's height ("mask with height").
#[serde(default)]
pub height_mask: HeightMask,
}
/// Mask with height: partial mask values follow the layer's own height, so a transition
/// reveals the high parts first. With mask `m` and the layer's height `h` (−1..1):
/// `m' = saturate(m + contrast · 4m(1 − m) · (h + offset))`. Fully hidden (0) and fully shown
/// (1) texels are unchanged, as is everything where the layer has no height.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct HeightMask {
pub enabled: bool,
/// How strongly the height pushes the mask (0 = plain mask), 0..64.
pub contrast: f32,
/// Added to the height before it pushes the mask, −1..1.
pub offset: f32,
}
impl Default for HeightMask {
fn default() -> Self {
HeightMask { enabled: false, contrast: 1.0, offset: 0.0 }
}
}
impl HeightMask {
/// The mask `m` combined with height `h` (see [`HeightMask`]).
pub fn apply(&self, m: f32, h: f32) -> f32 {
if !self.enabled || !h.is_finite() {
return m;
}
(m + self.contrast * 4.0 * m * (1.0 - m) * (h + self.offset)).clamp(0.0, 1.0)
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum LayerKind {
/// Painted pixels, stored per channel by the engine under the layer id.
Paint,
/// A procedural or uniform material applied everywhere (shaped by the mask).
Fill(Fill),
/// A folder of layers, bottom → top.
Group { children: Vec<LayerId>, collapsed: bool },
/// A linked instance of `source` (possibly in another texture set): renders the source's
/// content, content effects and channel blending, and its mask unless the instance has its
/// own. Edits to the source show in every instance.
Instance { source: LayerId },
}
impl LayerKind {
pub fn name(&self) -> &'static str {
match self {
LayerKind::Paint => "paint",
LayerKind::Fill(_) => "fill",
LayerKind::Group { .. } => "group",
LayerKind::Instance { .. } => "instance",
}
}
}
impl Layer {
/// A layer with every channel of `channels` enabled at Normal/100%.
pub fn new(id: LayerId, name: impl Into<String>, kind: LayerKind, channels: &[Channel]) -> Layer {
Layer {
id,
name: name.into(),
visible: true,
kind,
channels: channels.iter().map(|c| (*c, ChannelBlend::default())).collect(),
mask: None,
content_effects: Vec::new(),
color_tag: None,
height_mask: HeightMask::default(),
}
}
pub fn is_group(&self) -> bool {
matches!(self.kind, LayerKind::Group { .. })
}
pub fn children(&self) -> &[LayerId] {
match &self.kind {
LayerKind::Group { children, .. } => children,
_ => &[],
}
}
pub fn blend(&self, c: Channel) -> Option<ChannelBlend> {
self.channels.get(&c).copied()
}
/// The layer this one instances, if it is an instance.
pub fn instance_source(&self) -> Option<LayerId> {
match self.kind {
LayerKind::Instance { source } => Some(source),
_ => None,
}
}
}
/// Where a texture or procedural is sampled from on the surface.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Projection {
/// Texture coordinates of the mesh.
Uv { scale: [f32; 2], rotation: f32, offset: [f32; 2] },
/// World-space box projection blended by the normal.
Triplanar { scale: f32, sharpness: f32, offset: [f32; 3] },
/// World-space planar projection along an axis (0 = X, 1 = Y, 2 = Z).
Planar { scale: f32, axis: u8, offset: [f32; 3] },
/// Spherical projection around the mesh center.
Spherical { scale: f32 },
/// Cylindrical projection around an axis.
Cylindrical { scale: f32, axis: u8 },
}
impl Default for Projection {
fn default() -> Self {
Projection::Uv { scale: [1.0, 1.0], rotation: 0.0, offset: [0.0, 0.0] }
}
}
impl Projection {
pub fn label(&self) -> &'static str {
match self {
Projection::Uv { .. } => "UV projection",
Projection::Triplanar { .. } => "Tri-planar projection",
Projection::Planar { .. } => "Planar projection",
Projection::Spherical { .. } => "Spherical projection",
Projection::Cylindrical { .. } => "Cylindrical projection",
}
}
}
/// Procedural patterns available to fills, generators and masks.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum ProceduralKind {
/// Smooth fractal value noise.
Clouds,
/// Gradient (Perlin-style) noise.
Perlin,
/// Fine high-frequency noise.
Noise,
/// Worley / cellular noise.
Cells,
/// Blotchy grunge: thresholded multi-scale noise.
Grunge,
/// Thin random scratches.
Scratches,
/// Checkerboard.
Checker,
/// Stripes.
Stripes,
/// Linear gradient along U (or the projection axis).
Gradient,
/// Wood grain: growth rings with fibers along X.
Wood,
/// Running-bond bricks with mortar joints (0 = mortar).
Bricks,
/// Square tiles with grout joints (0 = grout).
Tiles,
/// Plain fabric weave.
Weave,
/// Leather grain: pebbled cells with creases.
Leather,
/// Hammered metal dimples.
Hammered,
/// Fine brushed-metal lines along X.
Brushed,
/// Marble veins.
Marble,
/// Flat random tone per Voronoi cell (crystals, spangle, stones).
Voronoi,
/// Vertical streaks and leaks (along the projection's up axis).
Streaks,
/// Fingerprints and smudges.
Smudges,
/// Small round pores and pits (0 = pore).
Pores,
/// Sharp-edged paint chips.
Chips,
}
impl ProceduralKind {
pub const ALL: [ProceduralKind; 22] = [
ProceduralKind::Clouds,
ProceduralKind::Perlin,
ProceduralKind::Noise,
ProceduralKind::Cells,
ProceduralKind::Grunge,
ProceduralKind::Scratches,
ProceduralKind::Checker,
ProceduralKind::Stripes,
ProceduralKind::Gradient,
ProceduralKind::Wood,
ProceduralKind::Bricks,
ProceduralKind::Tiles,
ProceduralKind::Weave,
ProceduralKind::Leather,
ProceduralKind::Hammered,
ProceduralKind::Brushed,
ProceduralKind::Marble,
ProceduralKind::Voronoi,
ProceduralKind::Streaks,
ProceduralKind::Smudges,
ProceduralKind::Pores,
ProceduralKind::Chips,
];
pub fn label(self) -> &'static str {
match self {
ProceduralKind::Clouds => "Clouds",
ProceduralKind::Perlin => "Perlin noise",
ProceduralKind::Noise => "Fine noise",
ProceduralKind::Cells => "Cells",
ProceduralKind::Grunge => "Grunge",
ProceduralKind::Scratches => "Scratches",
ProceduralKind::Checker => "Checker",
ProceduralKind::Stripes => "Stripes",
ProceduralKind::Gradient => "Gradient",
ProceduralKind::Wood => "Wood grain",
ProceduralKind::Bricks => "Bricks",
ProceduralKind::Tiles => "Tiles",
ProceduralKind::Weave => "Fabric weave",
ProceduralKind::Leather => "Leather grain",
ProceduralKind::Hammered => "Hammered",
ProceduralKind::Brushed => "Brushed lines",
ProceduralKind::Marble => "Marble veins",
ProceduralKind::Voronoi => "Voronoi",
ProceduralKind::Streaks => "Streaks",
ProceduralKind::Smudges => "Fingerprints",
ProceduralKind::Pores => "Pores",
ProceduralKind::Chips => "Paint chips",
}
}
pub fn parse(s: &str) -> Option<ProceduralKind> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], "");
ProceduralKind::ALL.into_iter().find(|k| norm(k.label()) == norm(s) || norm(&format!("{k:?}")) == norm(s))
}
}
/// A procedural grayscale pattern. Its output maps 0..1 between `low` and `high` values.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Procedural {
pub kind: ProceduralKind,
/// Pattern frequency (repeats per projection unit).
pub scale: f32,
pub seed: u32,
/// Contrast around 0.5 (1 = unchanged).
pub contrast: f32,
/// Shifts the pattern brighter (+) or darker (−).
pub balance: f32,
pub invert: bool,
}
impl Procedural {
pub fn new(kind: ProceduralKind) -> Procedural {
Procedural { kind, scale: 4.0, seed: 1, contrast: 1.0, balance: 0.0, invert: false }
}
}
/// What a fill writes into one channel.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Source {
/// A constant value (linear RGB for colors; `[v, v, v]` for scalars).
Uniform([f32; 3]),
/// A procedural pattern mixing two values.
Procedural { pattern: Procedural, low: [f32; 3], high: [f32; 3] },
/// An imported image resource, by name.
Image { name: String },
/// The stack value recorded by an anchor point effect (`anchor` is the effect id) for
/// `channel`; colors read as gray where a scalar is needed.
Anchor { anchor: LayerId, channel: Channel },
}
impl Source {
pub fn uniform_of(c: Channel) -> Source {
Source::Uniform(c.default_value())
}
/// The anchor point this source reads, if any.
pub fn anchor(&self) -> Option<LayerId> {
match self {
Source::Anchor { anchor, .. } => Some(*anchor),
_ => None,
}
}
}
/// A fill layer's material: one source per channel, plus how it is projected.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Default)]
pub struct Fill {
pub sources: BTreeMap<Channel, Source>,
pub projection: Projection,
}
impl Fill {
/// Value used for `c` when the fill has no source for it: the channel default.
pub fn source(&self, c: Channel) -> Source {
self.sources.get(&c).cloned().unwrap_or_else(|| Source::uniform_of(c))
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum MaskBackground {
#[default]
White,
Black,
}
/// A layer mask: a background color with a stack of effects on top.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Mask {
pub enabled: bool,
pub background: MaskBackground,
/// Effects bottom → top. Paint effects hold bitmap data keyed by their id.
pub effects: Vec<Effect>,
}
impl Mask {
pub fn new(background: MaskBackground) -> Mask {
Mask { enabled: true, background, effects: Vec::new() }
}
}
/// Levels remap: input range, gamma, output range.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct Levels {
pub in_low: f32,
pub in_high: f32,
pub gamma: f32,
pub out_low: f32,
pub out_high: f32,
}
impl Default for Levels {
fn default() -> Self {
Levels { in_low: 0.0, in_high: 1.0, gamma: 1.0, out_low: 0.0, out_high: 1.0 }
}
}
impl Levels {
pub fn apply(&self, x: f32) -> f32 {
let t = ((x - self.in_low) / (self.in_high - self.in_low).max(1e-5)).clamp(0.0, 1.0);
let t = t.powf(1.0 / self.gamma.max(1e-3));
self.out_low + (self.out_high - self.out_low) * t
}
}
/// Mesh-map driven mask generators (the "smart mask" building blocks).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub enum GeneratorKind {
/// Convex edges from the curvature map.
EdgeWear,
/// Crevices from ambient occlusion.
Dirt,
/// Thin parts from the thickness map.
ThinAreas,
/// Raw curvature.
Curvature,
/// Raw ambient occlusion.
AmbientOcclusion,
/// Gradient along a world axis (bottom → top by default).
Position,
/// Surfaces facing a direction (e.g. up for dust).
Direction,
}
impl GeneratorKind {
pub const ALL: [GeneratorKind; 7] = [
GeneratorKind::EdgeWear,
GeneratorKind::Dirt,
GeneratorKind::ThinAreas,
GeneratorKind::Curvature,
GeneratorKind::AmbientOcclusion,
GeneratorKind::Position,
GeneratorKind::Direction,
];
pub fn label(self) -> &'static str {
match self {
GeneratorKind::EdgeWear => "Mask Editor: Edge wear",
GeneratorKind::Dirt => "Dirt",
GeneratorKind::ThinAreas => "Thin areas",
GeneratorKind::Curvature => "Curvature",
GeneratorKind::AmbientOcclusion => "Ambient occlusion",
GeneratorKind::Position => "Position gradient",
GeneratorKind::Direction => "Light / direction",
}
}
pub fn parse(s: &str) -> Option<GeneratorKind> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-', ':'], "");
GeneratorKind::ALL.into_iter().find(|k| norm(&format!("{k:?}")) == norm(s) || norm(k.label()) == norm(s))
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Generator {
pub kind: GeneratorKind,
/// Where the mask starts (0..1, generator specific threshold).
pub level: f32,
/// Edge softness (0 = hard).
pub softness: f32,
/// Breaks the result up with world-space noise (0 = none).
pub noise_amount: f32,
pub noise_scale: f32,
pub seed: u32,
/// Direction for `Position` / `Direction` generators (world space).
pub direction: [f32; 3],
pub invert: bool,
}
impl Generator {
pub fn new(kind: GeneratorKind) -> Generator {
let (level, softness, noise_amount) = match kind {
GeneratorKind::EdgeWear => (0.6, 0.12, 0.5),
GeneratorKind::Dirt => (0.55, 0.25, 0.35),
GeneratorKind::ThinAreas => (0.3, 0.2, 0.0),
_ => (0.5, 0.25, 0.0),
};
Generator { kind, level, softness, noise_amount, noise_scale: 8.0, seed: 7, direction: [0.0, 1.0, 0.0], invert: false }
}
}
/// Filters usable on masks and content.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum Filter {
Blur {
radius: f32,
},
Sharpen {
amount: f32,
},
Invert,
Threshold {
level: f32,
},
/// Hue/saturation/lightness shift (color channels; lightness only on grays and masks).
/// `hue` is in turns, `saturation` and `lightness` in −1..1; all zero = unchanged.
Hsl {
hue: f32,
saturation: f32,
lightness: f32,
},
}
/// Push `x` (0..1) towards 1 (`amount` > 0) or 0 (`amount` < 0); `amount` in −1..1.
fn shift_unit(x: f32, amount: f32) -> f32 {
let a = amount.clamp(-1.0, 1.0);
if a >= 0.0 { x + (1.0 - x) * a } else { x * (1.0 + a) }
}
fn hue_to_rgb(p: f32, q: f32, t: f32) -> f32 {
let t = t.rem_euclid(1.0);
if t < 1.0 / 6.0 {
p + (q - p) * 6.0 * t
} else if t < 0.5 {
q
} else if t < 2.0 / 3.0 {
p + (q - p) * (2.0 / 3.0 - t) * 6.0
} else {
p
}
}
/// HSL adjustment of a 0..1 color (see [`Filter::Hsl`]). A gray stays gray and only its
/// lightness changes.
pub fn hsl_adjust(rgb: [f32; 3], hue: f32, saturation: f32, lightness: f32) -> [f32; 3] {
let [r, g, b] = rgb.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 });
let (mx, mn) = (r.max(g).max(b), r.min(g).min(b));
let (d, l) = (mx - mn, (mx + mn) * 0.5);
let (h, s) = if d <= 1e-6 {
(0.0, 0.0)
} else {
let s = if l > 0.5 { d / (2.0 - mx - mn) } else { d / (mx + mn) };
let h = if mx == r {
((g - b) / d).rem_euclid(6.0)
} else if mx == g {
(b - r) / d + 2.0
} else {
(r - g) / d + 4.0
};
(h / 6.0, s)
};
let h = h + if hue.is_finite() { hue } else { 0.0 };
let (s, l) = (if d <= 1e-6 { 0.0 } else { shift_unit(s, saturation) }, shift_unit(l, lightness));
if s <= 0.0 {
return [l; 3];
}
let q = if l < 0.5 { l * (1.0 + s) } else { l + s - l * s };
let p = 2.0 * l - q;
[hue_to_rgb(p, q, h + 1.0 / 3.0), hue_to_rgb(p, q, h), hue_to_rgb(p, q, h - 1.0 / 3.0)]
}
impl Filter {
pub fn label(&self) -> &'static str {
match self {
Filter::Blur { .. } => "Blur",
Filter::Sharpen { .. } => "Sharpen",
Filter::Invert => "Invert",
Filter::Threshold { .. } => "Threshold",
Filter::Hsl { .. } => "HSL Perceptive",
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub enum EffectKind {
/// Painted grayscale (mask) or material (content) pixels keyed by the effect id.
Paint,
/// A uniform or procedural grayscale fill.
Fill {
source: Source,
projection: Projection,
},
Generator(Generator),
Levels(Levels),
Filter(Filter),
/// Select ID-map colors within a tolerance.
ColorSelection {
colors: Vec<[f32; 3]>,
tolerance: f32,
},
/// Compare the mask with a constant.
Compare {
op: CompareOp,
value: f32,
tolerance: f32,
},
/// Content only: a material fill (one source per channel; channels without a source are
/// left as they are).
Material(Fill),
/// Content only: records the composited stack right after its layer (that layer and
/// everything below) so masks and fills above can read it ([`Source::Anchor`]).
Anchor,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum CompareOp {
LesserThan,
WithinTolerance,
GreaterThan,
}
impl EffectKind {
pub fn name(&self) -> &'static str {
match self {
EffectKind::Paint => "Paint",
EffectKind::Fill { .. } => "Fill",
EffectKind::Generator(_) => "Generator",
EffectKind::Levels(_) => "Levels",
EffectKind::Filter(f) => f.label(),
EffectKind::ColorSelection { .. } => "Color selection",
EffectKind::Compare { .. } => "Compare mask",
EffectKind::Material(_) => "Fill",
EffectKind::Anchor => "Anchor point",
}
}
/// Whether the effect belongs in a layer's content stack (`true`), its mask (`false`), or
/// both (`None`).
pub fn content_only(&self) -> Option<bool> {
match self {
EffectKind::Material(_) | EffectKind::Anchor => Some(true),
EffectKind::Fill { .. } | EffectKind::Generator(_) | EffectKind::ColorSelection { .. } | EffectKind::Compare { .. } => Some(false),
EffectKind::Paint | EffectKind::Levels(_) | EffectKind::Filter(_) => None,
}
}
/// Anchor points read by this effect's sources.
fn reads_anchor(&self) -> bool {
match self {
EffectKind::Fill { source, .. } => source.anchor().is_some(),
EffectKind::Material(f) => f.sources.values().any(|s| s.anchor().is_some()),
_ => false,
}
}
}
impl Layer {
/// Whether any source of the layer (fill, mask or content effects) reads an anchor point.
pub fn reads_anchor(&self) -> bool {
let fill = match &self.kind {
LayerKind::Fill(f) => f.sources.values().any(|s| s.anchor().is_some()),
_ => false,
};
fill || self.mask.iter().flat_map(|m| m.effects.iter()).chain(self.content_effects.iter()).any(|e| e.kind.reads_anchor())
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Effect {
pub id: LayerId,
pub name: String,
pub visible: bool,
pub kind: EffectKind,
pub blend: BlendMode,
pub opacity: f32,
}
impl Effect {
pub fn new(id: LayerId, kind: EffectKind) -> Effect {
// Generators and fills that build a mask usually add on top of the background.
Effect { id, name: kind.name().to_string(), visible: true, kind, blend: BlendMode::Normal, opacity: 1.0 }
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn levels_map_range_and_gamma() {
let l = Levels { in_low: 0.2, in_high: 0.6, gamma: 1.0, out_low: 0.0, out_high: 1.0 };
assert!((l.apply(0.4) - 0.5).abs() < 1e-6);
assert_eq!(l.apply(0.0), 0.0);
assert_eq!(l.apply(1.0), 1.0);
let g = Levels { gamma: 2.0, ..Levels::default() };
assert!((g.apply(0.25) - 0.5).abs() < 1e-6);
// Degenerate ranges never divide by zero.
let d = Levels { in_low: 0.5, in_high: 0.5, ..Levels::default() };
assert!(d.apply(0.7).is_finite());
}
#[test]
fn hsl_adjust_shifts_hue_saturation_and_lightness() {
let close = |a: [f32; 3], b: [f32; 3]| (0..3).all(|i| (a[i] - b[i]).abs() < 1e-4);
let c = [0.8, 0.3, 0.1];
assert!(close(hsl_adjust(c, 0.0, 0.0, 0.0), c), "identity");
assert!(close(hsl_adjust([1.0, 0.0, 0.0], 1.0 / 3.0, 0.0, 0.0), [0.0, 1.0, 0.0]), "red → green");
assert!(close(hsl_adjust([1.0, 0.0, 0.0], -1.0 / 3.0, 0.0, 0.0), [0.0, 0.0, 1.0]), "red → blue");
let gray = hsl_adjust(c, 0.0, -1.0, 0.0);
assert!((gray[0] - gray[1]).abs() < 1e-6 && (gray[1] - gray[2]).abs() < 1e-6);
// Grays only change lightness, whatever the hue and saturation.
assert!(close(hsl_adjust([0.4; 3], 0.3, 1.0, 0.5), [0.7; 3]));
assert!(close(hsl_adjust([0.4; 3], 0.0, 0.0, -0.5), [0.2; 3]));
assert!(hsl_adjust([f32::NAN, 2.0, -1.0], f32::NAN, 5.0, -5.0).iter().all(|v| v.is_finite()));
}
#[test]
fn effect_targets_and_anchor_reads() {
assert_eq!(EffectKind::Anchor.content_only(), Some(true));
assert_eq!(EffectKind::Generator(Generator::new(GeneratorKind::Dirt)).content_only(), Some(false));
assert_eq!(EffectKind::Filter(Filter::Invert).content_only(), None);
let mut l = Layer::new(LayerId(1), "l", LayerKind::Paint, &[Channel::BaseColor]);
assert!(!l.reads_anchor());
let source = Source::Anchor { anchor: LayerId(9), channel: Channel::Height };
l.mask = Some(Mask { effects: vec![Effect::new(LayerId(2), EffectKind::Fill { source, projection: Projection::default() })], ..Mask::new(MaskBackground::Black) });
assert!(l.reads_anchor());
}
#[test]
fn height_mask_keeps_the_ends_and_follows_height() {
let off = HeightMask::default();
assert_eq!(off.apply(0.3, 1.0), 0.3, "disabled");
let hm = HeightMask { enabled: true, contrast: 1.0, offset: 0.0 };
for h in [-1.0, 0.0, 1.0] {
assert_eq!(hm.apply(0.0, h), 0.0);
assert_eq!(hm.apply(1.0, h), 1.0);
}
assert_eq!(hm.apply(0.5, 0.0), 0.5, "no height, no change");
assert_eq!(hm.apply(0.5, 0.5), 1.0);
assert_eq!(hm.apply(0.5, -0.5), 0.0);
assert!(hm.apply(0.5, 0.1) > 0.5 && hm.apply(0.5, -0.1) < 0.5);
assert!(HeightMask { offset: 0.5, ..hm }.apply(0.5, 0.0) > 0.5);
assert_eq!(hm.apply(0.5, f32::NAN), 0.5);
}
#[test]
fn generator_kinds_parse() {
for k in GeneratorKind::ALL {
assert_eq!(GeneratorKind::parse(&format!("{k:?}")), Some(k));
}
for k in ProceduralKind::ALL {
assert_eq!(ProceduralKind::parse(k.label()), Some(k));
}
}
}
+38
View File
@@ -0,0 +1,38 @@
//! # texturecraft-core
//!
//! The TextureCraft document model: a [`Project`] holds texture sets (one per mesh material),
//! each with a stack of [`Layer`]s (paint, fill, group) whose channels blend with one of
//! Painter's [`BlendMode`]s. Pure data with serde; pixels live in `texturecraft-texel` images
//! owned by the engine. [`blend`] is the CPU reference for every blend mode.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod blend;
pub mod channel;
pub mod layer;
pub mod project;
pub use blend::{BlendMode, blend1, blend3, lum, mix3};
pub use channel::{Channel, ChannelFormat, ChannelKind};
pub use layer::{
ChannelBlend, CompareOp, Effect, EffectKind, Fill, Filter, Generator, GeneratorKind, HeightMask, Layer, LayerId, LayerKind, Levels, Mask, MaskBackground, Procedural,
ProceduralKind, Projection, Source, hsl_adjust,
};
pub use project::{AoMixing, BakeMatch, BakeSettings, BakedMap, DisplaySettings, FORMAT_VERSION, NormalFormat, NormalMixing, Project, TextureSet, ToneMapping};
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum CoreError {
#[error("no layer with id {}", .0.0)]
NoLayer(LayerId),
#[error("no texture set {0}")]
NoTextureSet(usize),
#[error("{0}")]
Invalid(String),
}
pub type Result<T> = std::result::Result<T, CoreError>;
/// Product name for user-facing text.
pub const APP_NAME: &str = "TextureCraft";
/// Native project file extension.
pub const PROJECT_EXT: &str = "tcraft";
+744
View File
@@ -0,0 +1,744 @@
//! The project: texture sets, their layer stacks, and project-wide settings.
use std::collections::{BTreeMap, BTreeSet};
use serde::{Deserialize, Serialize};
use crate::{Channel, ChannelFormat, CoreError, Effect, Layer, LayerId, LayerKind, Result};
pub const FORMAT_VERSION: u32 = 1;
/// Maximum group nesting (also bounds recursion over hostile project files).
pub const MAX_DEPTH: usize = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum NormalFormat {
#[default]
OpenGl,
DirectX,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
pub enum BakedMap {
Normal,
WorldNormal,
Id,
AmbientOcclusion,
Curvature,
Position,
Thickness,
Height,
/// World-space direction of least occlusion (packed like the world-space normal).
BentNormal,
/// 1 where the high poly covers the low poly (times the high poly's vertex alpha).
Opacity,
/// The high poly's vertex colors.
ColorMap,
/// Facing ratio towards [`BakeSettings::direction`] (0.5 = perpendicular).
WorldDirection,
}
impl BakedMap {
pub const ALL: [BakedMap; 12] = [
BakedMap::Normal,
BakedMap::WorldNormal,
BakedMap::Id,
BakedMap::AmbientOcclusion,
BakedMap::Curvature,
BakedMap::Position,
BakedMap::Thickness,
BakedMap::Height,
BakedMap::BentNormal,
BakedMap::Opacity,
BakedMap::ColorMap,
BakedMap::WorldDirection,
];
pub fn label(self) -> &'static str {
match self {
BakedMap::Normal => "Normal",
BakedMap::WorldNormal => "World space normal",
BakedMap::Id => "ID",
BakedMap::AmbientOcclusion => "Ambient occlusion",
BakedMap::Curvature => "Curvature",
BakedMap::Position => "Position",
BakedMap::Thickness => "Thickness",
BakedMap::Height => "Height",
BakedMap::BentNormal => "Bent normals",
BakedMap::Opacity => "Opacity",
BakedMap::ColorMap => "Color map",
BakedMap::WorldDirection => "World space direction",
}
}
pub fn id(self) -> &'static str {
match self {
BakedMap::Normal => "normal_base",
BakedMap::WorldNormal => "world_space_normals",
BakedMap::Id => "id",
BakedMap::AmbientOcclusion => "ambient_occlusion",
BakedMap::Curvature => "curvature",
BakedMap::Position => "position",
BakedMap::Thickness => "thickness",
BakedMap::Height => "height",
BakedMap::BentNormal => "bent_normals",
BakedMap::Opacity => "opacity",
BakedMap::ColorMap => "color_map",
BakedMap::WorldDirection => "world_space_direction",
}
}
/// Components stored (3 for vector maps, 1 for scalar maps).
pub fn components(self) -> usize {
match self {
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::Id | BakedMap::Position | BakedMap::BentNormal | BakedMap::ColorMap => 3,
_ => 1,
}
}
/// Value where nothing was baked (uncovered texels, missing maps).
pub fn neutral(self) -> [f32; 3] {
match self {
BakedMap::Normal | BakedMap::WorldNormal | BakedMap::BentNormal => [0.5, 0.5, 1.0],
BakedMap::AmbientOcclusion | BakedMap::Thickness => [1.0; 3],
BakedMap::Curvature | BakedMap::Height | BakedMap::WorldDirection => [0.5; 3],
BakedMap::Id | BakedMap::Position | BakedMap::Opacity | BakedMap::ColorMap => [0.0; 3],
}
}
pub fn parse(s: &str) -> Option<BakedMap> {
let norm = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], "");
BakedMap::ALL.into_iter().find(|m| norm(m.label()) == norm(s) || norm(m.id()) == norm(s) || norm(&format!("{m:?}")) == norm(s))
}
}
/// How low-poly parts find their high-poly counterparts (Painter's "Match").
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum BakeMatch {
/// Every low-poly part sees every high-poly part.
#[default]
Always,
/// A low-poly part sees only high-poly parts of the same name once the suffixes are removed
/// (`wheel_low` ↔ `wheel_high`).
ByMeshName,
}
/// Bake parameters (Painter's "Common parameters" plus the per-map parameters). Fields missing
/// from older projects take their defaults.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct BakeSettings {
/// Included by "Bake selected textures".
pub enabled: bool,
pub resolution: u32,
/// Supersampling per axis: 1 (none), 2, 4 or 8.
pub antialiasing: u32,
pub dilation: u32,
/// Rays per texel for AO, thickness and bent normals.
pub rays: u32,
/// Max occluder distance relative to the bounding-box diagonal.
pub max_distance: f32,
/// Curvature strength.
pub curvature_strength: f32,
/// Curvature from the baked normal map instead of the mesh.
pub curvature_from_normal: bool,
/// World-space direction of the "World space direction" map.
pub direction: [f32; 3],
pub maps: BTreeSet<BakedMap>,
/// Bake from the low poly itself ("Use low poly mesh as high poly").
pub use_low_as_high: bool,
/// Ray start distance in front of the low poly, relative to the bbox diagonal.
pub max_frontal: f32,
pub max_rear: f32,
/// Cast rays along normals averaged over hard edges (no gaps at split normals).
pub average_normals: bool,
pub matching: BakeMatch,
pub low_suffix: String,
pub high_suffix: String,
}
impl Default for BakeSettings {
fn default() -> Self {
BakeSettings {
enabled: true,
resolution: 1024,
antialiasing: 1,
dilation: 16,
rays: 32,
max_distance: 0.25,
curvature_strength: 1.0,
curvature_from_normal: false,
direction: [0.0, 1.0, 0.0],
maps: [
BakedMap::Normal,
BakedMap::WorldNormal,
BakedMap::Id,
BakedMap::AmbientOcclusion,
BakedMap::Curvature,
BakedMap::Position,
BakedMap::Thickness,
]
.into_iter()
.collect(),
use_low_as_high: true,
max_frontal: 0.01,
max_rear: 0.01,
average_normals: true,
matching: BakeMatch::Always,
low_suffix: "_low".into(),
high_suffix: "_high".into(),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum NormalMixing {
#[default]
Combine,
Replace,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum AoMixing {
#[default]
Multiply,
None,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct TextureSet {
pub name: String,
#[serde(default)]
pub description: String,
/// Material index in the mesh this set paints.
pub material: usize,
/// Power of two, 128..=8192.
pub resolution: u32,
pub channels: Vec<(Channel, ChannelFormat)>,
/// Top-level layers, bottom → top.
pub stack: Vec<LayerId>,
#[serde(default)]
pub normal_mixing: NormalMixing,
#[serde(default)]
pub ao_mixing: AoMixing,
/// Height-to-normal strength.
#[serde(default = "one")]
pub height_strength: f32,
#[serde(default)]
pub bake: BakeSettings,
/// Mesh maps that have been baked (pixels live with the engine / project file).
#[serde(default)]
pub baked: BTreeSet<BakedMap>,
#[serde(default = "yes")]
pub visible: bool,
}
fn one() -> f32 {
1.0
}
fn yes() -> bool {
true
}
impl TextureSet {
pub fn new(name: impl Into<String>, material: usize, resolution: u32) -> TextureSet {
TextureSet {
name: name.into(),
description: String::new(),
material,
resolution,
channels: Channel::DEFAULT_SET.iter().map(|c| (*c, ChannelFormat::default_for(*c))).collect(),
stack: Vec::new(),
normal_mixing: NormalMixing::Combine,
ao_mixing: AoMixing::Multiply,
height_strength: 1.0,
bake: BakeSettings::default(),
baked: BTreeSet::new(),
visible: true,
}
}
pub fn has_channel(&self, c: Channel) -> bool {
self.channels.iter().any(|(x, _)| *x == c)
}
pub fn channel_list(&self) -> Vec<Channel> {
self.channels.iter().map(|(c, _)| *c).collect()
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ToneMapping {
#[default]
Linear,
AcesFilmic,
}
/// Viewport display settings (saved with the project, as Painter does). Fields missing from
/// older projects take their defaults.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct DisplaySettings {
/// A built-in environment name, or `resource:<name>` for an imported equirect image.
pub environment: String,
/// Background visibility 0..1.
pub env_opacity: f32,
pub env_exposure: f32,
pub env_blur: f32,
/// Degrees.
pub env_rotation: f32,
pub shadows: bool,
pub tone_mapping: ToneMapping,
pub fov: f32,
pub post_effects: bool,
pub bloom: f32,
pub vignette: f32,
pub sharpen: f32,
pub grain: f32,
pub ao_intensity: f32,
/// Accumulate jittered frames while the view is still (temporal anti-aliasing).
pub taa: bool,
/// Shader: PBR specular/glossiness (base color = diffuse, Specular = F0 color, Glossiness)
/// instead of metallic/roughness.
pub spec_gloss: bool,
/// Parallax occlusion mapping from the height channel (same depth as height-to-normal).
pub parallax: bool,
}
/// Prefix of [`DisplaySettings::environment`] naming an image resource.
pub const ENV_RESOURCE_PREFIX: &str = "resource:";
impl DisplaySettings {
/// The image resource used as the environment, if any.
pub fn environment_resource(&self) -> Option<&str> {
self.environment.strip_prefix(ENV_RESOURCE_PREFIX)
}
}
impl Default for DisplaySettings {
fn default() -> Self {
DisplaySettings {
environment: "Studio Soft".into(),
env_opacity: 0.0,
env_exposure: 0.0,
env_blur: 0.35,
env_rotation: 0.0,
shadows: false,
tone_mapping: ToneMapping::AcesFilmic,
fov: 40.0,
post_effects: false,
bloom: 0.0,
vignette: 0.0,
sharpen: 0.0,
grain: 0.0,
ao_intensity: 0.75,
taa: true,
spec_gloss: false,
parallax: false,
}
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Project {
pub format_version: u32,
pub name: String,
/// Path of the mesh inside the project file (or a built-in primitive id `builtin:<name>`).
pub mesh: String,
pub normal_format: NormalFormat,
pub texture_sets: Vec<TextureSet>,
pub layers: BTreeMap<LayerId, Layer>,
pub next_id: u64,
pub display: DisplaySettings,
}
impl Project {
pub fn new(name: impl Into<String>, mesh: impl Into<String>) -> Project {
Project {
format_version: FORMAT_VERSION,
name: name.into(),
mesh: mesh.into(),
normal_format: NormalFormat::OpenGl,
texture_sets: Vec::new(),
layers: BTreeMap::new(),
next_id: 1,
display: DisplaySettings::default(),
}
}
pub fn alloc_id(&mut self) -> LayerId {
let id = LayerId(self.next_id);
self.next_id = self.next_id.saturating_add(1);
id
}
pub fn texture_set(&self, ts: usize) -> Result<&TextureSet> {
self.texture_sets.get(ts).ok_or(CoreError::NoTextureSet(ts))
}
pub fn texture_set_mut(&mut self, ts: usize) -> Result<&mut TextureSet> {
self.texture_sets.get_mut(ts).ok_or(CoreError::NoTextureSet(ts))
}
pub fn layer(&self, id: LayerId) -> Result<&Layer> {
self.layers.get(&id).ok_or(CoreError::NoLayer(id))
}
pub fn layer_mut(&mut self, id: LayerId) -> Result<&mut Layer> {
self.layers.get_mut(&id).ok_or(CoreError::NoLayer(id))
}
/// The texture set and parent group (None = top level) holding `id`, plus its index.
pub fn locate(&self, id: LayerId) -> Option<(usize, Option<LayerId>, usize)> {
for (ts, set) in self.texture_sets.iter().enumerate() {
if let Some(i) = set.stack.iter().position(|x| *x == id) {
return Some((ts, None, i));
}
if let Some((parent, i)) = self.find_in(&set.stack, id, 0) {
return Some((ts, Some(parent), i));
}
}
None
}
fn find_in(&self, list: &[LayerId], id: LayerId, depth: usize) -> Option<(LayerId, usize)> {
if depth > MAX_DEPTH {
return None;
}
for g in list {
let Some(layer) = self.layers.get(g) else { continue };
let kids = layer.children();
if let Some(i) = kids.iter().position(|x| *x == id) {
return Some((*g, i));
}
if let Some(found) = self.find_in(kids, id, depth + 1) {
return Some(found);
}
}
None
}
/// The sibling list holding `id` (a texture set stack or a group's children).
fn siblings_mut(&mut self, ts: usize, parent: Option<LayerId>) -> Result<&mut Vec<LayerId>> {
match parent {
None => Ok(&mut self.texture_set_mut(ts)?.stack),
Some(p) => match &mut self.layer_mut(p)?.kind {
LayerKind::Group { children, .. } => Ok(children),
_ => Err(CoreError::Invalid(format!("layer {} is not a group", p.0))),
},
}
}
/// Insert `layer` into texture set `ts` above `above` (None = top of the stack). When
/// `above` is a group and `inside` is true, the layer goes to the top of the group.
pub fn insert_layer(&mut self, ts: usize, layer: Layer, above: Option<LayerId>, inside: bool) -> Result<LayerId> {
self.texture_set(ts)?;
let id = layer.id;
if self.layers.contains_key(&id) {
return Err(CoreError::Invalid(format!("layer id {} already exists", id.0)));
}
self.layers.insert(id, layer);
let placed = match above {
Some(target) if inside && self.layers.get(&target).is_some_and(Layer::is_group) => self.siblings_mut(ts, Some(target)).map(|kids| kids.push(id)),
Some(target) => match self.locate(target) {
Some((t, parent, i)) if t == ts => self.siblings_mut(ts, parent).map(|list| list.insert(i + 1, id)),
_ => self.texture_set_mut(ts).map(|s| s.stack.push(id)),
},
None => self.texture_set_mut(ts).map(|s| s.stack.push(id)),
};
if let Err(e) = placed {
self.layers.remove(&id);
return Err(e);
}
Ok(id)
}
/// Remove a layer (and, for groups, everything inside). Returns the removed ids.
pub fn remove_layer(&mut self, id: LayerId) -> Result<Vec<LayerId>> {
let (ts, parent, i) = self.locate(id).ok_or(CoreError::NoLayer(id))?;
let list = self.siblings_mut(ts, parent)?;
if i < list.len() {
list.remove(i);
}
let mut removed = Vec::new();
self.collect_subtree(id, 0, &mut removed);
for r in &removed {
self.layers.remove(r);
}
Ok(removed)
}
fn collect_subtree(&self, id: LayerId, depth: usize, out: &mut Vec<LayerId>) {
if depth > MAX_DEPTH || out.contains(&id) {
return;
}
out.push(id);
if let Some(l) = self.layers.get(&id) {
for c in l.children() {
self.collect_subtree(*c, depth + 1, out);
}
}
}
/// Move `id` within its sibling list to `index` (clamped).
pub fn move_layer(&mut self, id: LayerId, index: usize) -> Result<()> {
let (ts, parent, i) = self.locate(id).ok_or(CoreError::NoLayer(id))?;
let list = self.siblings_mut(ts, parent)?;
if i < list.len() {
list.remove(i);
let to = index.min(list.len());
list.insert(to, id);
}
Ok(())
}
/// Move `id` above `target` anywhere in the same texture set (drag & drop).
pub fn move_above(&mut self, id: LayerId, target: Option<LayerId>, inside: bool) -> Result<()> {
if Some(id) == target {
return Ok(());
}
let (ts, parent, i) = self.locate(id).ok_or(CoreError::NoLayer(id))?;
if let Some(t) = target {
let mut sub = Vec::new();
self.collect_subtree(id, 0, &mut sub);
if sub.contains(&t) {
return Err(CoreError::Invalid("cannot move a group into itself".into()));
}
}
let list = self.siblings_mut(ts, parent)?;
if i < list.len() {
list.remove(i);
}
let layer = self.layers.remove(&id).ok_or(CoreError::NoLayer(id))?;
self.insert_layer(ts, layer, target, inside).map(|_| ())
}
/// Visible-order walk of a stack: every layer id, depth-first, bottom → top.
pub fn walk(&self, ts: usize) -> Vec<(LayerId, usize)> {
let mut out = Vec::new();
if let Some(set) = self.texture_sets.get(ts) {
self.walk_list(&set.stack, 0, &mut out);
}
out
}
fn walk_list(&self, list: &[LayerId], depth: usize, out: &mut Vec<(LayerId, usize)>) {
if depth > MAX_DEPTH {
return;
}
for id in list {
out.push((*id, depth));
if let Some(l) = self.layers.get(id) {
self.walk_list(l.children(), depth + 1, out);
}
}
}
/// Find an effect anywhere (mask or content stacks) by id: (owning layer, effect).
pub fn effect(&self, id: LayerId) -> Option<(LayerId, &Effect)> {
self.layers.values().find_map(|l| l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()).find(|e| e.id == id).map(|e| (l.id, e)))
}
pub fn effect_mut(&mut self, id: LayerId) -> Option<&mut Effect> {
self.layers.values_mut().find_map(|l| {
let in_mask = l.mask.as_mut().and_then(|m| m.effects.iter_mut().find(|e| e.id == id));
match in_mask {
Some(e) => Some(e),
None => l.content_effects.iter_mut().find(|e| e.id == id),
}
})
}
/// A unique "<base> <n>" name among the layers of texture set `ts`.
pub fn next_layer_name(&self, ts: usize, base: &str) -> String {
let names: BTreeSet<&str> = self.walk(ts).iter().filter_map(|(id, _)| self.layers.get(id).map(|l| l.name.as_str())).collect();
(1..).map(|n| format!("{base} {n}")).find(|n| !names.contains(n.as_str())).unwrap_or_else(|| base.to_string())
}
/// Check structural invariants (ids exist, no layer appears twice). Used after loading.
pub fn validate(&self) -> Result<()> {
if self.format_version > FORMAT_VERSION {
return Err(CoreError::Invalid(format!("project format {} is newer than this TextureCraft supports ({FORMAT_VERSION})", self.format_version)));
}
let mut seen = BTreeSet::new();
for ts in 0..self.texture_sets.len() {
for (id, depth) in self.walk(ts) {
if depth > MAX_DEPTH {
return Err(CoreError::Invalid("layer groups nested too deeply".into()));
}
if !self.layers.contains_key(&id) {
return Err(CoreError::Invalid(format!("stack references missing layer {}", id.0)));
}
if !seen.insert(id) {
return Err(CoreError::Invalid(format!("layer {} appears twice", id.0)));
}
}
}
match self.instance_cycle() {
Some(id) => Err(CoreError::Invalid(format!("instance layer {} draws itself", id.0))),
None => Ok(()),
}
}
/// Every layer drawn when `roots` are drawn: the roots, folder children and instance
/// sources, recursively, each once.
pub fn render_tree(&self, roots: &[LayerId]) -> BTreeSet<LayerId> {
let mut out = BTreeSet::new();
let mut todo: Vec<(LayerId, usize)> = roots.iter().map(|id| (*id, 0)).collect();
while let Some((id, depth)) = todo.pop() {
if depth > 2 * MAX_DEPTH || !out.insert(id) {
continue;
}
if let Some(l) = self.layers.get(&id) {
todo.extend(l.children().iter().chain(l.instance_source().as_ref()).map(|c| (*c, depth + 1)));
}
}
out
}
/// An instance layer that draws itself (through folders and other instances), if any.
pub fn instance_cycle(&self) -> Option<LayerId> {
self.layers.values().filter_map(|l| Some((l.id, l.instance_source()?))).find(|(id, s)| self.render_tree(&[*s]).contains(id)).map(|(id, _)| id)
}
/// The layer whose content `id` draws: itself, or an instance's source.
pub fn content_layer(&self, id: LayerId) -> Option<&Layer> {
let mut l = self.layers.get(&id)?;
for _ in 0..=MAX_DEPTH {
match l.instance_source() {
Some(s) => l = self.layers.get(&s)?,
None => return Some(l),
}
}
None
}
/// The layer holding the mask `id` draws with: itself when it has a mask (an instance's
/// override), else the instance's source.
pub fn mask_owner(&self, id: LayerId) -> LayerId {
match self.layers.get(&id) {
Some(l) if l.mask.is_none() => self.content_layer(id).map_or(id, |c| c.id),
_ => id,
}
}
/// Texture sets that draw layer `id`: the set holding it and every set with an instance of
/// it (or of a folder holding it).
pub fn sets_drawing(&self, id: LayerId) -> Vec<usize> {
(0..self.texture_sets.len()).filter(|ts| self.texture_sets.get(*ts).is_some_and(|set| self.render_tree(&set.stack).contains(&id))).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
fn project() -> Project {
let mut p = Project::new("t", "builtin:sphere");
p.texture_sets.push(TextureSet::new("Body", 0, 512));
p
}
fn paint(p: &mut Project, name: &str) -> Layer {
Layer::new(p.alloc_id(), name, LayerKind::Paint, &Channel::DEFAULT_SET)
}
#[test]
fn insert_move_remove_keep_tree_consistent() {
let mut p = project();
let a = paint(&mut p, "a");
let a = p.insert_layer(0, a, None, false).unwrap();
let b = paint(&mut p, "b");
let b = p.insert_layer(0, b, None, false).unwrap();
let gid = p.alloc_id();
let g = Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &Channel::DEFAULT_SET);
p.insert_layer(0, g, Some(a), false).unwrap();
assert_eq!(p.texture_sets[0].stack, vec![a, gid, b]);
p.move_above(b, Some(gid), true).unwrap();
assert_eq!(p.texture_sets[0].stack, vec![a, gid]);
assert_eq!(p.layer(gid).unwrap().children(), &[b]);
assert_eq!(p.locate(b), Some((0, Some(gid), 0)));
assert!(p.move_above(gid, Some(b), true).is_err(), "a group cannot go inside itself");
p.validate().unwrap();
let removed = p.remove_layer(gid).unwrap();
assert_eq!(removed, vec![gid, b]);
assert_eq!(p.texture_sets[0].stack, vec![a]);
assert!(p.layer(b).is_err());
p.validate().unwrap();
}
#[test]
fn names_are_unique() {
let mut p = project();
let l = Layer::new(p.alloc_id(), "Layer 1", LayerKind::Paint, &[]);
p.insert_layer(0, l, None, false).unwrap();
assert_eq!(p.next_layer_name(0, "Layer"), "Layer 2");
}
#[test]
fn serde_round_trip_is_stable() {
let mut p = project();
let l = paint(&mut p, "x");
p.insert_layer(0, l, None, false).unwrap();
let json = serde_json::to_string(&p).unwrap();
let back: Project = serde_json::from_str(&json).unwrap();
assert_eq!(back, p);
assert_eq!(serde_json::to_string(&back).unwrap(), json);
}
#[test]
fn content_effects_and_anchors_round_trip_and_old_projects_load() {
use crate::{Effect, EffectKind, Fill, Filter, Mask, MaskBackground, Projection, Source};
let mut p = project();
let mut l = paint(&mut p, "x");
let (anchor, hsl, fill) = (p.alloc_id(), p.alloc_id(), p.alloc_id());
let mut material = Fill::default();
material.sources.insert(Channel::Roughness, Source::Uniform([0.2; 3]));
l.content_effects = vec![
Effect::new(fill, EffectKind::Material(material)),
Effect::new(hsl, EffectKind::Filter(Filter::Hsl { hue: 0.25, saturation: -0.5, lightness: 0.1 })),
Effect::new(anchor, EffectKind::Anchor),
];
let id = p.insert_layer(0, l, None, false).unwrap();
let mut top = paint(&mut p, "y");
let source = Source::Anchor { anchor, channel: Channel::Height };
top.mask = Some(Mask { effects: vec![Effect::new(p.alloc_id(), EffectKind::Fill { source, projection: Projection::default() })], ..Mask::new(MaskBackground::Black) });
p.insert_layer(0, top, Some(id), false).unwrap();
let json = serde_json::to_string(&p).unwrap();
let back: Project = serde_json::from_str(&json).unwrap();
assert_eq!(back, p);
assert_eq!(back.effect(anchor).map(|(owner, _)| owner), Some(id));
// Projects saved before content effects existed load with empty stacks.
let mut v: serde_json::Value = serde_json::from_str(&json).unwrap();
for l in v["layers"].as_object_mut().unwrap().values_mut() {
l.as_object_mut().unwrap().remove("content_effects");
}
let old: Project = serde_json::from_value(v).unwrap();
assert!(old.layers.values().all(|l| l.content_effects.is_empty()));
}
#[test]
fn instances_resolve_draw_in_their_sets_and_cycles_are_found() {
let mut p = project();
p.texture_sets.push(TextureSet::new("Head", 1, 512));
let a = paint(&mut p, "a");
let a = p.insert_layer(0, a, None, false).unwrap();
let inst = Layer::new(p.alloc_id(), "a", LayerKind::Instance { source: a }, &[]);
let inst = p.insert_layer(1, inst, None, false).unwrap();
assert_eq!(p.content_layer(inst).map(|l| l.id), Some(a));
assert_eq!(p.sets_drawing(a), vec![0, 1]);
assert_eq!(p.sets_drawing(inst), vec![1]);
p.validate().unwrap();
// A folder holding an instance of itself draws itself.
let gid = p.alloc_id();
p.insert_layer(1, Layer::new(gid, "g", LayerKind::Group { children: vec![], collapsed: false }, &[]), None, false).unwrap();
let loop_id = p.alloc_id();
p.insert_layer(1, Layer::new(loop_id, "g", LayerKind::Instance { source: gid }, &[]), Some(gid), true).unwrap();
assert_eq!(p.instance_cycle(), Some(loop_id));
assert!(p.validate().is_err());
assert!(p.content_layer(LayerId(999)).is_none());
}
#[test]
fn validate_rejects_newer_formats_and_dangling_ids() {
let mut p = project();
p.texture_sets[0].stack.push(LayerId(99));
assert!(p.validate().is_err());
let mut q = project();
q.format_version = FORMAT_VERSION + 1;
assert!(q.validate().is_err());
}
}
+25
View File
@@ -0,0 +1,25 @@
[package]
name = "texturecraft-engine"
description = "TextureCraft session, command registry, painting, baking and inspection"
version.workspace = true
edition.workspace = true
license.workspace = true
[lints]
workspace = true
[dependencies]
texturecraft-core = { workspace = true }
texturecraft-texel = { workspace = true }
texturecraft-geom = { workspace = true }
texturecraft-compose = { workspace = true }
texturecraft-paint = { workspace = true }
texturecraft-bake = { workspace = true }
texturecraft-formats = { workspace = true }
rayon = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
[dev-dependencies]
image = { workspace = true }
+390
View File
@@ -0,0 +1,390 @@
//! Mesh-map baking commands (Painter's "Bake Mesh Maps" window): bake settings, the
//! high-definition mesh list, the cage, and running a bake.
use std::collections::BTreeSet;
use std::sync::Arc;
use serde_json::{Value, json};
use texturecraft_bake::{BakeOutput, BakeRequest, HighPoly, MAX_RAYS, Progress, bake};
use texturecraft_core::{BakeMatch, BakeSettings, BakedMap};
use texturecraft_geom::{Bvh, Mesh};
use crate::commands::{CommandSpec, always, bad, boolp, f32p, strp, u64p};
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("bake.run", "Bake mesh maps", ["Mode"], None, "{ts?: index|[indices]|\"all\"|\"selected\", ...any bake.settings parameter}", always, bake_run),
cmd!(
"bake.settings",
"Bake settings",
[],
None,
"{ts?: index|[indices]|\"all\"|\"selected\" (default: the active set), resolution?, antialiasing?: 1|2|4|8, dilation?, rays?, maxDistance?, curvatureStrength?, curvatureFromNormal?, direction?: [x,y,z], maps?: [ids], enabled?, useLowAsHigh?, maxFrontal?, maxRear?, averageNormals?, matching?: always|byMeshName, lowSuffix?, highSuffix?}",
always,
settings
),
cmd!("bake.highPoly.add", "Add high definition mesh", [], None, "{path} — a mesh file (glb, gltf, fbx, dae, obj, ply, stl)", always, high_add),
cmd!("bake.highPoly.remove", "Remove high definition mesh", [], None, "{index? | name? | all?: true}", always, high_remove),
cmd!("bake.highPoly.list", "List high definition meshes", [], None, "{}", always, |s, _| Ok(meshes_json(s))),
cmd!("bake.cage.set", "Load cage mesh", [], None, "{path} — a mesh with the low poly's triangles", always, cage_set),
cmd!("bake.cage.clear", "Remove cage mesh", [], None, "{}", always, |s, _| {
s.bake_meshes.cage = None;
s.modified = true;
Ok(meshes_json(s))
}),
]
}
/// A mesh file as saved in a project: (file name, bytes).
type MeshFile = (String, Vec<u8>);
/// A mesh file the baker reads (high poly or cage): its name, original bytes (saved in the
/// project) and parsed mesh.
#[derive(Clone, Debug)]
pub struct BakeMesh {
pub name: String,
pub bytes: Arc<Vec<u8>>,
pub mesh: Arc<Mesh>,
}
/// The high-definition meshes and the cage. Like the low-poly mesh they are not part of the
/// undo history.
#[derive(Clone, Debug, Default)]
pub struct BakeMeshes {
pub high: Vec<BakeMesh>,
pub cage: Option<BakeMesh>,
/// Every high poly appended into one mesh, with its BVH (rebuilt when the list changes).
merged: Option<(Arc<Mesh>, Arc<Bvh>)>,
}
impl BakeMeshes {
// shortcut: the merged copy doubles high-poly memory; build the BVH over the parts in place if
// multi-million-triangle sets run out of memory.
fn rebuild(&mut self) {
self.merged = (!self.high.is_empty()).then(|| {
let mut all = Mesh::default();
for h in &self.high {
all.append(&h.mesh);
}
let bvh = Bvh::new(&all);
(Arc::new(all), Arc::new(bvh))
});
}
}
/// A self-contained bake task that can run on another thread.
pub struct BakeTask {
pub ts: usize,
pub mesh: Arc<Mesh>,
pub bvh: Arc<Bvh>,
pub material: usize,
pub settings: BakeSettings,
/// The merged high polys, unless the set bakes from the low poly.
pub high: Option<(Arc<Mesh>, Arc<Bvh>)>,
pub cage: Option<Arc<Mesh>>,
}
impl BakeTask {
pub fn run(&self, progress: &Progress) -> Result<BakeOutput> {
let high = self.high.as_ref().map(|(mesh, bvh)| HighPoly { mesh, bvh });
let req = BakeRequest { mesh: &self.mesh, bvh: &self.bvh, material: self.material, settings: &self.settings, high, cage: self.cage.as_deref() };
bake(&req, progress).map_err(|e| EngineError::Other(format!("bake failed: {e}")))
}
}
/// A mesh file name made unique among `taken` (and safe as a project file entry).
fn unique_name(file_name: &str, taken: &[&str]) -> String {
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("mesh");
let base = texturecraft_formats::sanitize_resource_name(leaf);
let mut name = base.clone();
let mut n = 2;
while taken.contains(&name.as_str()) {
name = format!("{n}_{base}");
n += 1;
}
name
}
fn parse_mesh(file_name: &str, bytes: Vec<u8>) -> Result<(Arc<Vec<u8>>, Arc<Mesh>)> {
let mesh = texturecraft_formats::import_high_poly_bytes(file_name, &bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
Ok((Arc::new(bytes), Arc::new(mesh)))
}
impl Session {
pub fn bake_task(&self, ts: usize) -> Result<BakeTask> {
let set = self.doc.project.texture_set(ts)?;
let high = if set.bake.use_low_as_high { None } else { self.bake_meshes.merged.clone() };
let cage = high.as_ref().and(self.bake_meshes.cage.as_ref()).map(|c| c.mesh.clone());
Ok(BakeTask { ts, mesh: self.mesh.clone(), bvh: self.bvh.clone(), material: set.material, settings: set.bake.clone(), high, cage })
}
/// Store a finished bake (one undo step).
pub fn apply_bake(&mut self, ts: usize, out: BakeOutput) -> Result<()> {
self.edit("Bake mesh maps", |s| {
let maps: BTreeSet<BakedMap> = out.maps.keys().copied().collect();
let entry = s.doc.baked.entry(ts).or_default();
entry.resolution = out.resolution;
for (m, data) in out.maps {
entry.maps.insert(m, Arc::new(data));
}
s.doc.project.texture_set_mut(ts)?.baked.extend(maps);
Ok(())
})
}
/// Bake texture set `ts` now (blocking).
pub fn bake_now(&mut self, ts: usize) -> Result<()> {
let task = self.bake_task(ts)?;
let out = task.run(&Progress::new())?;
self.apply_bake(ts, out)
}
/// Add a high-definition mesh from file bytes (the web picker, the desktop dialog and
/// `bake.highPoly.add`); every texture set then bakes from the high polys. Returns its name.
pub fn add_high_poly_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
let (bytes, mesh) = parse_mesh(file_name, bytes)?;
let taken: Vec<&str> = self.bake_meshes.high.iter().map(|h| h.name.as_str()).collect();
let name = unique_name(file_name, &taken);
self.log.push(format!("High poly {name}: {} triangles", mesh.triangle_count()));
self.bake_meshes.high.push(BakeMesh { name: name.clone(), bytes, mesh });
self.bake_meshes.rebuild();
for set in &mut self.doc.project.texture_sets {
set.bake.use_low_as_high = false;
}
self.modified = true;
Ok(name)
}
/// Remove high-definition mesh `index`.
pub fn remove_high_poly(&mut self, index: usize) -> Result<BakeMesh> {
if index >= self.bake_meshes.high.len() {
return Err(EngineError::Other(format!("no high poly mesh {index}")));
}
let removed = self.bake_meshes.high.remove(index);
self.bake_meshes.rebuild();
self.modified = true;
Ok(removed)
}
/// Use a cage mesh (same triangles as the low poly) from file bytes.
pub fn set_cage_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
let (bytes, mesh) = parse_mesh(file_name, bytes)?;
if mesh.triangle_count() != self.mesh.triangle_count() {
return Err(EngineError::Other(format!(
"the cage has {} triangles but the low poly has {}; export the cage from the low poly",
mesh.triangle_count(),
self.mesh.triangle_count()
)));
}
let name = unique_name(file_name, &[]);
self.bake_meshes.cage = Some(BakeMesh { name: name.clone(), bytes, mesh });
self.modified = true;
Ok(name)
}
/// Restore the bake meshes saved in a project file; unreadable ones are logged and skipped.
pub(crate) fn load_bake_meshes(&mut self, high: Vec<MeshFile>, cage: Option<MeshFile>) {
for (name, bytes) in high {
match parse_mesh(&name, bytes) {
Ok((bytes, mesh)) => self.bake_meshes.high.push(BakeMesh { name, bytes, mesh }),
Err(e) => self.log.push(format!("skipped high poly mesh: {e}")),
}
}
self.bake_meshes.rebuild();
if let Some((name, bytes)) = cage
&& let Err(e) = self.set_cage_bytes(&name, bytes)
{
self.log.push(format!("skipped cage mesh: {e}"));
}
}
/// The bake meshes for a project file: (high polys, cage).
pub(crate) fn saved_bake_meshes(&self) -> (Vec<MeshFile>, Option<MeshFile>) {
let entry = |m: &BakeMesh| (m.name.clone(), m.bytes.as_ref().clone());
(self.bake_meshes.high.iter().map(entry).collect(), self.bake_meshes.cage.as_ref().map(entry))
}
}
/// `bake.highPoly.list`: the high polys and the cage (also part of `project.inspect`).
pub fn meshes_json(s: &Session) -> Value {
let one = |m: &BakeMesh| json!({ "name": m.name, "triangles": m.mesh.triangle_count(), "parts": m.mesh.submeshes.iter().map(|p| p.name.as_str()).collect::<Vec<_>>() });
json!({ "highPoly": s.bake_meshes.high.iter().map(one).collect::<Vec<_>>(), "cage": s.bake_meshes.cage.as_ref().map(one) })
}
#[cfg(not(target_arch = "wasm32"))]
fn read_mesh_file(cmd: &str, p: &Value) -> Result<(String, Vec<u8>)> {
let path = strp(p, "path").ok_or_else(|| bad(cmd, "`path` is required"))?;
let meta = std::fs::metadata(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
if meta.len() > texturecraft_formats::mesh_import::MAX_MESH_FILE_BYTES {
return Err(bad(cmd, format!("{path} is too large")));
}
let bytes = std::fs::read(path).map_err(|e| bad(cmd, format!("cannot read {path}: {e}")))?;
Ok((path.to_string(), bytes))
}
#[cfg(target_arch = "wasm32")]
fn read_mesh_file(_: &str, _: &Value) -> Result<(String, Vec<u8>)> {
Err(EngineError::Other("file paths are not available in the browser; use the bake panel's file picker".into()))
}
fn high_add(s: &mut Session, p: &Value) -> Result<Value> {
let (path, bytes) = read_mesh_file("bake.highPoly.add", p)?;
let name = s.add_high_poly_bytes(&path, bytes)?;
Ok(json!({ "name": name, "meshes": meshes_json(s) }))
}
fn high_remove(s: &mut Session, p: &Value) -> Result<Value> {
if boolp(p, "all") == Some(true) {
s.bake_meshes.high.clear();
s.bake_meshes.rebuild();
s.modified = true;
return Ok(meshes_json(s));
}
let index = match (u64p(p, "index"), strp(p, "name")) {
(Some(i), _) => usize::try_from(i).unwrap_or(usize::MAX),
(None, Some(n)) => s.bake_meshes.high.iter().position(|h| h.name == n).ok_or_else(|| bad("bake.highPoly.remove", format!("no high poly `{n}`")))?,
(None, None) => return Err(bad("bake.highPoly.remove", "`index`, `name` or `all` is required")),
};
s.remove_high_poly(index)?;
Ok(meshes_json(s))
}
fn cage_set(s: &mut Session, p: &Value) -> Result<Value> {
let (path, bytes) = read_mesh_file("bake.cage.set", p)?;
let name = s.set_cage_bytes(&path, bytes)?;
Ok(json!({ "name": name, "meshes": meshes_json(s) }))
}
/// Texture sets named by `ts` (default: the active one).
fn sets_param(s: &Session, cmd: &str, p: &Value) -> Result<Vec<usize>> {
let n = s.set_count();
let one = |v: &Value| v.as_u64().map(|t| t as usize).filter(|t| *t < n).ok_or_else(|| bad(cmd, format!("invalid texture set {v}")));
match p.get("ts") {
Some(Value::String(a)) if a == "all" => Ok((0..n).collect()),
Some(Value::String(a)) if a == "selected" => Ok((0..n).filter(|t| s.doc.project.texture_sets.get(*t).is_some_and(|set| set.bake.enabled)).collect()),
Some(Value::Array(a)) => a.iter().map(one).collect(),
Some(v) => Ok(vec![one(v)?]),
None => Ok(vec![s.ts()]),
}
}
/// `b` as `bake.settings` parameters (what the command returns and the UI sends back).
pub fn settings_params(b: &BakeSettings) -> Value {
json!({
"resolution": b.resolution,
"antialiasing": b.antialiasing,
"dilation": b.dilation,
"rays": b.rays,
"maxDistance": b.max_distance,
"curvatureStrength": b.curvature_strength,
"curvatureFromNormal": b.curvature_from_normal,
"direction": b.direction,
"maps": b.maps.iter().map(|m| m.id()).collect::<Vec<_>>(),
"enabled": b.enabled,
"useLowAsHigh": b.use_low_as_high,
"maxFrontal": b.max_frontal,
"maxRear": b.max_rear,
"averageNormals": b.average_normals,
"matching": match b.matching { BakeMatch::Always => "always", BakeMatch::ByMeshName => "byMeshName" },
"lowSuffix": b.low_suffix,
"highSuffix": b.high_suffix,
})
}
/// Apply the `bake.settings` parameters present in `p` to `b`.
fn apply_settings(b: &mut BakeSettings, p: &Value, cmd: &str) -> Result<()> {
if let Some(r) = u64p(p, "resolution") {
b.resolution = crate::session::check_resolution(u32::try_from(r).unwrap_or(0))?;
}
if let Some(a) = u64p(p, "antialiasing") {
if ![1, 2, 4, 8].contains(&a) {
return Err(bad(cmd, "antialiasing must be 1, 2, 4 or 8"));
}
b.antialiasing = a as u32;
}
if let Some(d) = u64p(p, "dilation") {
b.dilation = d.min(256) as u32;
}
if let Some(r) = u64p(p, "rays") {
b.rays = r.clamp(1, u64::from(MAX_RAYS)) as u32;
}
for (k, slot, lo, hi) in [
("maxDistance", &mut b.max_distance, 0.001, 10.0),
("curvatureStrength", &mut b.curvature_strength, 0.0, 16.0),
("maxFrontal", &mut b.max_frontal, 0.0, 1.0),
("maxRear", &mut b.max_rear, 0.0, 1.0),
] {
if let Some(v) = f32p(p, k).filter(|v| v.is_finite()) {
*slot = v.clamp(lo, hi);
}
}
for (k, slot) in [
("curvatureFromNormal", &mut b.curvature_from_normal),
("enabled", &mut b.enabled),
("useLowAsHigh", &mut b.use_low_as_high),
("averageNormals", &mut b.average_normals),
] {
if let Some(v) = boolp(p, k) {
*slot = v;
}
}
if let Some(d) = p.get("direction") {
let v: Vec<f32> = d.as_array().into_iter().flatten().filter_map(Value::as_f64).map(|x| x as f32).collect();
match v[..] {
[x, y, z] if [x, y, z].iter().all(|c| c.is_finite()) && [x, y, z] != [0.0; 3] => b.direction = [x, y, z],
_ => return Err(bad(cmd, "`direction` must be three finite numbers, not all zero")),
}
}
if let Some(a) = p.get("maps").and_then(Value::as_array) {
b.maps = a.iter().map(|v| v.as_str().and_then(BakedMap::parse).ok_or_else(|| bad(cmd, format!("unknown mesh map {v}")))).collect::<Result<_>>()?;
}
match strp(p, "matching") {
Some("always") => b.matching = BakeMatch::Always,
Some("byMeshName") | Some("byName") => b.matching = BakeMatch::ByMeshName,
Some(o) => return Err(bad(cmd, format!("unknown matching `{o}` (always|byMeshName)"))),
None => {}
}
for (k, slot) in [("lowSuffix", &mut b.low_suffix), ("highSuffix", &mut b.high_suffix)] {
if let Some(v) = strp(p, k) {
*slot = v.chars().take(64).collect();
}
}
Ok(())
}
/// Validate and apply the settings parameters to every set first, so a bad parameter changes
/// nothing.
fn set_settings(s: &mut Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
let sets = sets_param(s, cmd, p)?;
let mut next = Vec::with_capacity(sets.len());
for &ts in &sets {
let mut b = s.doc.project.texture_set(ts)?.bake.clone();
apply_settings(&mut b, p, cmd)?;
next.push((ts, b));
}
for (ts, b) in next {
let set = s.doc.project.texture_set_mut(ts)?;
if set.bake != b {
set.bake = b;
s.modified = true;
}
}
Ok(sets)
}
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
let sets = set_settings(s, p, "bake.settings")?;
let out: Vec<Value> =
sets.iter().filter_map(|t| s.doc.project.texture_sets.get(*t).map(|set| json!({ "ts": t, "settings": settings_params(&set.bake) }))).collect();
Ok(json!(out))
}
fn bake_run(s: &mut Session, p: &Value) -> Result<Value> {
let sets = set_settings(s, p, "bake.run")?;
for &ts in &sets {
s.bake_now(ts)?;
}
s.update();
Ok(json!({ "baked": sets }))
}
+177
View File
@@ -0,0 +1,177 @@
//! The command registry. Every user-visible action is a command with a stable id; the menus,
//! shortcuts, CLI, control channel and MCP server all dispatch them by id. Ids follow
//! Painter's menu structure (see `menu_catalog`).
use serde_json::{Value, json};
use texturecraft_core::{BlendMode, Channel};
use crate::{EngineError, Result, Session};
pub type Run = fn(&mut Session, &Value) -> Result<Value>;
pub type Enabled = fn(&Session) -> std::result::Result<(), String>;
pub struct CommandSpec {
pub id: &'static str,
pub label: &'static str,
/// Menu placement, e.g. `["Edit"]`. Empty = not in menus.
pub menu: &'static [&'static str],
/// Default shortcut in egui notation (`Ctrl+Shift+E`), mapped per platform by the UI.
pub shortcut: Option<&'static str>,
/// Parameters, for humans and agents.
pub params: &'static str,
pub enabled: Enabled,
pub run: Run,
}
pub(crate) fn always(_: &Session) -> std::result::Result<(), String> {
Ok(())
}
pub(crate) fn has_layer(s: &Session) -> std::result::Result<(), String> {
s.selected_layer().map(|_| ()).ok_or_else(|| "no layer selected".into())
}
pub(crate) fn can_undo(s: &Session) -> std::result::Result<(), String> {
if s.can_undo() { Ok(()) } else { Err("nothing to undo".into()) }
}
pub(crate) fn can_redo(s: &Session) -> std::result::Result<(), String> {
if s.can_redo() { Ok(()) } else { Err("nothing to redo".into()) }
}
#[macro_export]
#[doc(hidden)]
macro_rules! cmd {
($id:literal, $label:literal, [$($m:literal),*], $sc:expr, $params:literal, $en:expr, $run:expr) => {
$crate::commands::CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: $sc, params: $params, enabled: $en, run: $run }
};
}
pub fn command_specs() -> &'static [CommandSpec] {
static SPECS: std::sync::OnceLock<Vec<CommandSpec>> = std::sync::OnceLock::new();
SPECS.get_or_init(|| {
let mut v = Vec::new();
v.extend(crate::view_cmds::edit_specs());
v.extend(crate::layer_cmds::specs());
v.extend(crate::layer_ops::specs());
v.extend(crate::instance_cmds::specs());
v.extend(crate::mask_cmds::specs());
v.extend(crate::tool_cmds::specs());
v.extend(crate::path_tool::specs());
v.extend(crate::view_cmds::specs());
v.extend(crate::quick_mask::specs());
v.extend(crate::set_cmds::specs());
v.extend(crate::project_cmds::specs());
v.extend(crate::bake_cmds::specs());
v.extend(crate::file_cmds::specs());
v.extend(crate::resource_cmds::specs());
v.extend(crate::material_lib::specs());
v.extend(crate::smart_masks::specs());
v
})
}
pub fn find(id: &str) -> Option<&'static CommandSpec> {
command_specs().iter().find(|c| c.id == id)
}
/// Run a command by id with JSON params (empty params = defaults, never a dialog).
pub fn execute(s: &mut Session, id: &str, params: &Value) -> Result<Value> {
let spec = find(id).ok_or_else(|| EngineError::UnknownCommand(id.to_string()))?;
(spec.enabled)(s).map_err(|why| EngineError::Disabled { cmd: id.to_string(), why })?;
(spec.run)(s, params)
}
/// Every command, as JSON (for `commands` listings and MCP).
pub fn list(s: &Session, filter: Option<&str>) -> Value {
let f = filter.map(str::to_ascii_lowercase);
let items: Vec<Value> = command_specs()
.iter()
.filter(|c| f.as_ref().is_none_or(|f| c.id.to_ascii_lowercase().contains(f) || c.label.to_ascii_lowercase().contains(f)))
.map(|c| {
json!({
"id": c.id,
"label": c.label,
"menu": c.menu,
"shortcut": c.shortcut,
"params": c.params,
"enabled": (c.enabled)(s).is_ok(),
})
})
.collect();
Value::Array(items)
}
// ---------- param helpers ----------
pub(crate) fn bad(cmd: &str, msg: impl Into<String>) -> EngineError {
EngineError::BadParams { cmd: cmd.into(), msg: msg.into() }
}
pub(crate) fn f32p(p: &Value, key: &str) -> Option<f32> {
p.get(key).and_then(Value::as_f64).map(|v| v as f32).filter(|v| v.is_finite())
}
pub(crate) fn u64p(p: &Value, key: &str) -> Option<u64> {
p.get(key).and_then(|v| v.as_u64().or_else(|| v.as_f64().filter(|f| f.is_finite() && *f >= 0.0).map(|f| f.round() as u64)))
}
pub(crate) fn boolp(p: &Value, key: &str) -> Option<bool> {
p.get(key).and_then(Value::as_bool)
}
pub(crate) fn strp<'a>(p: &'a Value, key: &str) -> Option<&'a str> {
p.get(key).and_then(Value::as_str)
}
/// A layer id param (`"layer"`), defaulting to the selected layer.
pub(crate) fn layer_param(s: &Session, cmd: &str, p: &Value) -> Result<texturecraft_core::LayerId> {
match u64p(p, "layer") {
Some(id) => {
let id = texturecraft_core::LayerId(id);
s.doc.project.layer(id).map_err(|_| bad(cmd, format!("no layer {}", id.0)))?;
Ok(id)
}
None => s.selected_layer().ok_or_else(|| bad(cmd, "no layer selected and no `layer` given")),
}
}
/// [`layer_param`], following an instance to the layer whose content it draws.
pub(crate) fn content_param(s: &Session, cmd: &str, p: &Value) -> Result<texturecraft_core::LayerId> {
let id = layer_param(s, cmd, p)?;
Ok(s.doc.project.content_layer(id).map_or(id, |l| l.id))
}
pub(crate) fn channel_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Channel>> {
match strp(p, key) {
None => Ok(None),
Some(s) => Channel::parse(s).map(Some).ok_or_else(|| bad(cmd, format!("unknown channel `{s}`"))),
}
}
pub(crate) fn blend_param(cmd: &str, p: &Value, key: &str) -> Result<Option<BlendMode>> {
match strp(p, key) {
None => Ok(None),
Some(s) => BlendMode::parse(s).map(Some).ok_or_else(|| bad(cmd, format!("unknown blend mode `{s}`"))),
}
}
/// A color: `[r, g, b]` (linear 0..1) or `"#rrggbb"` (sRGB hex, converted to linear).
pub(crate) fn color_param(p: &Value, key: &str) -> Option<[f32; 3]> {
match p.get(key)? {
Value::Array(a) if a.len() >= 3 => {
let v: Vec<f32> = a.iter().take(3).map(|x| x.as_f64().unwrap_or(0.0) as f32).collect();
if v.iter().all(|x| x.is_finite()) { Some([v[0], v[1], v[2]]) } else { None }
}
Value::Number(n) => n.as_f64().map(|v| [v as f32; 3]).filter(|v| v[0].is_finite()),
Value::String(s) => {
let s = s.trim_start_matches('#');
if s.len() != 6 {
return None;
}
let c = |i: usize| u8::from_str_radix(s.get(i..i + 2)?, 16).ok().map(|v| texturecraft_texel::srgb_to_linear(v as f32 / 255.0));
Some([c(0)?, c(2)?, c(4)?])
}
_ => None,
}
}
+432
View File
@@ -0,0 +1,432 @@
//! Files: projects (`.tcraft`), mesh import, texture export. Byte-based functions work on the
//! web; path-based commands are native only.
use serde_json::{Value, json};
use texturecraft_core::NormalFormat;
#[cfg(not(target_arch = "wasm32"))]
use texturecraft_core::PROJECT_EXT;
use texturecraft_formats::{ExportInput, ExportOptions, ExportedFile, FileFormat, Padding, ProjectFile};
use texturecraft_geom::{Mesh, primitives};
use crate::commands::{CommandSpec, always, bad, strp, u64p};
use crate::session::{Document, Session};
use crate::{EngineError, Result, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"file.new",
"New project from a mesh file",
[],
None,
"{mesh: path to .glb/.gltf/.fbx/.dae/.obj/.ply/.stl, resolution?: 2048, name?}",
always,
new_from_mesh
),
cmd!("file.open", "Open...", ["File"], Some("Ctrl+O"), "{path: .tcraft project or mesh file}", always, open),
cmd!("file.save", "Save", ["File"], Some("Ctrl+S"), "{path?: .tcraft (default: the project's own file)}", always, save),
cmd!("file.saveAs", "Save as...", ["File"], Some("Ctrl+Shift+S"), "{path}", always, save_as),
cmd!("file.saveCopy", "Save a copy...", ["File"], None, "{path}", always, save_copy),
cmd!("file.close", "Close", ["File"], Some("Ctrl+F4"), "{}", always, close),
cmd!("file.reimportMesh", "Reimport mesh", ["Edit"], Some("Ctrl+Shift+R"), "{path?}", always, reimport),
cmd!(
"file.exportTextures",
"Export textures",
["File"],
None,
"{dir, preset?: name, ts?: index|\"all\", format?: png|jpg|tga|tif|exr|..., bitDepth?, padding?: none|dilation|dilationDefault|infinite, dilation?: px, size?: px, normalFormat?: openGl|directX}",
always,
export_textures
),
cmd!(
"file.exportMesh",
"Export Mesh...",
["File"],
None,
"{path: .obj or .glb file, format?: obj|glb (default: from the extension, else obj)}",
always,
export_mesh
),
cmd!("export.presets", "Export presets", [], None, "{}", always, |_, _| Ok(json!(
texturecraft_formats::builtin_presets().iter().map(|p| json!({"name": p.name, "maps": p.maps.len()})).collect::<Vec<_>>()
))),
cmd!("export.plan", "List export outputs", [], None, "{preset?, ts?, format?}", always, plan),
]
}
fn fe(e: texturecraft_formats::FormatError) -> EngineError {
EngineError::Other(e.to_string())
}
fn ext_of(name: &str) -> String {
std::path::Path::new(name).extension().and_then(|e| e.to_str()).unwrap_or("").to_ascii_lowercase()
}
fn stem_of(name: &str) -> String {
std::path::Path::new(name).file_stem().and_then(|e| e.to_str()).unwrap_or("Untitled").to_string()
}
impl Session {
/// The working mesh as Wavefront OBJ.
pub fn mesh_obj_bytes(&self) -> Vec<u8> {
texturecraft_formats::obj_bytes(&self.mesh, &self.doc.project.name)
}
/// The working mesh as binary glTF with each material's textures (from its texture set's
/// composite, through the texture export pipeline) embedded.
pub fn mesh_glb_bytes(&mut self) -> Result<Vec<u8>> {
let opts = texturecraft_formats::glb_export_options();
let mut textures = Vec::with_capacity(self.mesh.materials.len());
for m in 0..self.mesh.materials.len() {
let ts = self.doc.project.texture_sets.iter().position(|t| t.material == m);
let files = match ts {
Some(ts) => self.export_files(&[ts], &opts)?,
None => Vec::new(),
};
textures.push(texturecraft_formats::GlbTextures::from_files(files));
}
texturecraft_formats::glb_bytes(&self.mesh, &self.doc.project.name, &textures).map_err(fe)
}
/// A new project from mesh file bytes (one texture set per material).
pub fn from_mesh_bytes(file_name: &str, bytes: &[u8], resolution: u32, name: &str) -> Result<Session> {
let imported = texturecraft_formats::import_mesh_bytes(file_name, bytes).map_err(fe)?;
let ext = ext_of(file_name);
let mut s = Session::new_project(name, imported.mesh, &format!("mesh.{ext}"), Some((ext, bytes.to_vec())), resolution)?;
s.log.extend(imported.report.warnings.iter().cloned());
s.log.push(format!(
"Imported {} ({} triangles, {} materials{})",
file_name,
imported.report.triangles,
imported.report.materials,
if imported.report.uvs_generated { ", UVs generated" } else { "" }
));
Ok(s)
}
/// Open a `.tcraft` project from bytes.
pub fn from_project_bytes(bytes: &[u8]) -> Result<Session> {
let pf = texturecraft_formats::load_project_bytes(bytes).map_err(fe)?;
Session::from_project_file(pf)
}
pub fn from_project_file(pf: ProjectFile) -> Result<Session> {
let mesh = match (&pf.mesh, pf.project.mesh.strip_prefix("builtin:")) {
(_, Some(id)) => primitives::builtin(id).ok_or_else(|| EngineError::Other(format!("unknown built-in mesh `{id}`")))?,
(Some((ext, bytes)), None) => texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh,
(None, None) => return Err(EngineError::Other("the project has no mesh".into())),
};
check_materials(&pf.project, &mesh)?;
let source = pf.mesh.clone();
let resources = pf.resources.into_iter().map(|(k, v)| (k, std::sync::Arc::new(v))).collect();
let mut s = Session::new(Document { project: pf.project, pixels: pf.pixels, baked: pf.baked, resources }, mesh, source)?;
s.sync_images();
s.load_bake_meshes(pf.high_poly, pf.cage);
Ok(s)
}
/// The project as a `ProjectFile` (for saving).
pub fn project_file(&self) -> ProjectFile {
let mut pixels = self.doc.pixels.clone();
// Drop pixel images whose size no longer matches their texture set (never unloadable).
let res_of = |id: texturecraft_core::LayerId| {
self.doc.project.locate(id).and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts)).map(|t| t.resolution).or_else(|| {
self.doc
.project
.effect(id)
.and_then(|(owner, _)| self.doc.project.locate(owner))
.and_then(|(ts, _, _)| self.doc.project.texture_sets.get(ts))
.map(|t| t.resolution)
})
};
pixels.layers.retain(|(id, _), img| res_of(*id) == Some(img.width()));
pixels.masks.retain(|id, img| res_of(*id) == Some(img.width()));
let (high_poly, cage) = self.saved_bake_meshes();
ProjectFile {
project: self.doc.project.clone(),
pixels,
baked: self.doc.baked.clone(),
mesh: self.mesh_source.clone(),
high_poly,
cage,
thumbnail: None,
resources: self.doc.resources.iter().map(|(k, v)| (k.clone(), v.as_ref().clone())).collect(),
}
}
pub fn to_project_bytes(&self) -> Result<Vec<u8>> {
texturecraft_formats::save_project_bytes(&self.project_file()).map_err(fe)
}
/// Render every export file for texture sets `sets` (in memory; works on the web).
pub fn export_files(&mut self, sets: &[usize], opts: &ExportOptions) -> Result<Vec<ExportedFile>> {
self.update();
let mesh_name = stem_of(self.doc.project.mesh.trim_start_matches("builtin:"));
let mut out = Vec::new();
let empty = Default::default();
for &ts in sets {
let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other(format!("no texture set {ts}")))?;
let coverage = cache.gbuf.coverage_mask();
let input = ExportInput {
project: &self.doc.project,
ts,
composite: &cache.composite,
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
coverage: &coverage,
mesh_name: &mesh_name,
};
out.extend(texturecraft_formats::render_maps(&input, opts).map_err(fe)?);
}
Ok(out)
}
}
fn check_materials(p: &texturecraft_core::Project, mesh: &Mesh) -> Result<()> {
for t in &p.texture_sets {
if t.material >= mesh.materials.len().max(1) {
return Err(EngineError::Other(format!("texture set \"{}\" refers to a material the mesh doesn't have", t.name)));
}
}
Ok(())
}
/// Export options from command params.
pub fn export_options(p: &Value, cmd: &str) -> Result<ExportOptions> {
let name = strp(p, "preset").unwrap_or("Document channels + Normal + AO");
let preset = texturecraft_formats::builtin_preset(name).ok_or_else(|| bad(cmd, format!("unknown export preset `{name}`")))?;
let mut o = ExportOptions::new(preset);
if let Some(f) = strp(p, "format") {
o.format_override = Some(FileFormat::from_extension(f).ok_or_else(|| bad(cmd, format!("unknown format `{f}`")))?);
}
if let Some(b) = u64p(p, "bitDepth") {
o.bit_depth_override = Some(b.min(32) as u8);
}
let px = u64p(p, "dilation").map(|v| v.min(256) as u32).unwrap_or(16);
if let Some(pad) = strp(p, "padding") {
o.padding = match pad {
"none" => Padding::None,
"dilation" => Padding::Dilation(px),
"dilationDefault" => Padding::DilationDefault(px),
"infinite" => Padding::Infinite,
other => return Err(bad(cmd, format!("unknown padding `{other}`"))),
};
}
if let Some(sz) = u64p(p, "size") {
o.size = Some(crate::session::check_resolution(u32::try_from(sz).unwrap_or(0))?);
}
o.normal_format = match strp(p, "normalFormat") {
Some("openGl") | Some("opengl") => Some(NormalFormat::OpenGl),
Some("directX") | Some("directx") => Some(NormalFormat::DirectX),
Some(other) => return Err(bad(cmd, format!("unknown normal format `{other}`"))),
None => None,
};
Ok(o)
}
fn sets_param(s: &Session, p: &Value, cmd: &str) -> Result<Vec<usize>> {
match p.get("ts") {
None => Ok((0..s.set_count()).collect()),
Some(Value::String(a)) if a == "all" => Ok((0..s.set_count()).collect()),
Some(v) => Ok(vec![v.as_u64().map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad(cmd, "invalid `ts`"))?]),
}
}
fn plan(s: &mut Session, p: &Value) -> Result<Value> {
let opts = export_options(p, "export.plan")?;
let mesh_name = stem_of(s.doc.project.mesh.trim_start_matches("builtin:"));
let mut names = Vec::new();
for ts in sets_param(s, p, "export.plan")? {
for f in texturecraft_formats::list_outputs(&s.doc.project, ts, &mesh_name, &opts).map_err(fe)? {
names.push(json!({"ts": ts, "file": f.name, "format": f.format.extension(), "bitDepth": f.bit_depth, "warnings": f.warnings}));
}
}
Ok(json!(names))
}
#[cfg(not(target_arch = "wasm32"))]
mod native {
use super::*;
use std::path::Path;
pub fn path_param<'a>(p: &'a Value, key: &str, cmd: &str) -> Result<&'a str> {
strp(p, key).filter(|s| !s.trim().is_empty()).ok_or_else(|| bad(cmd, format!("`{key}` is required")))
}
/// Open a project or a mesh file.
pub fn open_path(path: &str) -> Result<Session> {
let p = Path::new(path);
if ext_of(path) == PROJECT_EXT {
let pf = texturecraft_formats::load_project(p).map_err(fe)?;
let mut s = Session::from_project_file(pf)?;
s.path = Some(path.to_string());
s.modified = false;
Ok(s)
} else {
let bytes = std::fs::read(p).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
Session::from_mesh_bytes(path, &bytes, 2048, &stem_of(path))
}
}
pub fn save_to(s: &mut Session, path: &str, adopt: bool) -> Result<Value> {
let path = if ext_of(path) == PROJECT_EXT { path.to_string() } else { format!("{path}.{PROJECT_EXT}") };
texturecraft_formats::save_project(Path::new(&path), &s.project_file()).map_err(fe)?;
if adopt {
s.path = Some(path.clone());
s.modified = false;
}
s.log.push(format!("Saved {path}"));
Ok(json!({ "path": path }))
}
}
#[cfg(not(target_arch = "wasm32"))]
pub use native::open_path;
#[cfg(not(target_arch = "wasm32"))]
fn new_from_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "mesh", "file.new")?;
let bytes = std::fs::read(path).map_err(|e| bad("file.new", format!("cannot read {path}: {e}")))?;
let res = u32::try_from(u64p(p, "resolution").unwrap_or(2048)).unwrap_or(0);
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| stem_of(path));
let mut next = Session::from_mesh_bytes(path, &bytes, res, &name)?;
next.viewport = s.viewport;
*s = next;
Ok(crate::inspect::session(s))
}
#[cfg(not(target_arch = "wasm32"))]
fn open(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "path", "file.open")?;
let mut next = native::open_path(path)?;
next.viewport = s.viewport;
*s = next;
Ok(crate::inspect::session(s))
}
#[cfg(not(target_arch = "wasm32"))]
fn save(s: &mut Session, p: &Value) -> Result<Value> {
let path = match strp(p, "path") {
Some(x) => x.to_string(),
None => s.path.clone().ok_or_else(|| bad("file.save", "the project has no file yet: give `path` (Save as)"))?,
};
native::save_to(s, &path, true)
}
#[cfg(not(target_arch = "wasm32"))]
fn save_as(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "path", "file.saveAs")?.to_string();
native::save_to(s, &path, true)
}
#[cfg(not(target_arch = "wasm32"))]
fn save_copy(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "path", "file.saveCopy")?.to_string();
native::save_to(s, &path, false)
}
#[cfg(not(target_arch = "wasm32"))]
fn reimport(s: &mut Session, p: &Value) -> Result<Value> {
// Re-read the mesh and keep the project (texture sets map by material index).
let mesh = match strp(p, "path") {
Some(path) => {
let bytes = std::fs::read(path).map_err(|e| bad("file.reimportMesh", format!("cannot read {path}: {e}")))?;
let m = texturecraft_formats::import_mesh_bytes(path, &bytes).map_err(fe)?.mesh;
s.mesh_source = Some((ext_of(path), bytes));
s.doc.project.mesh = format!("mesh.{}", ext_of(path));
m
}
None => match &s.mesh_source {
Some((ext, bytes)) => texturecraft_formats::import_mesh_bytes(&format!("mesh.{ext}"), bytes).map_err(fe)?.mesh,
None => return Err(bad("file.reimportMesh", "built-in meshes can't be reimported; give `path`")),
},
};
check_materials(&s.doc.project, &mesh)?;
let doc = s.doc.clone();
let source = s.mesh_source.clone();
let mut next = Session::new(doc, mesh, source)?;
next.path = s.path.clone();
next.viewport = s.viewport;
*s = next;
Ok(Value::Null)
}
#[cfg(not(target_arch = "wasm32"))]
fn export_textures(s: &mut Session, p: &Value) -> Result<Value> {
let dir = native::path_param(p, "dir", "file.exportTextures")?.to_string();
let opts = export_options(p, "file.exportTextures")?;
let sets = sets_param(s, p, "file.exportTextures")?;
std::fs::create_dir_all(&dir).map_err(|e| bad("file.exportTextures", format!("cannot create {dir}: {e}")))?;
let files = s.export_files(&sets, &opts)?;
let warnings: Vec<String> = files.iter().flat_map(|f| f.warnings.iter().cloned()).collect();
let written = texturecraft_formats::write_files(&files, std::path::Path::new(&dir)).map_err(fe)?;
s.log.push(format!("Exported {} textures to {dir}", written.len()));
Ok(json!({ "files": written.iter().map(|p| p.display().to_string()).collect::<Vec<_>>(), "warnings": warnings }))
}
#[cfg(not(target_arch = "wasm32"))]
fn export_mesh(s: &mut Session, p: &Value) -> Result<Value> {
let path = native::path_param(p, "path", "file.exportMesh")?;
let ext = match strp(p, "format") {
Some(f @ ("obj" | "glb")) => f.to_string(),
Some(other) => return Err(bad("file.exportMesh", format!("unknown mesh format `{other}` (obj or glb)"))),
None if ext_of(path) == "glb" => "glb".into(),
None => "obj".into(),
};
let path = if ext_of(path) == ext { path.to_string() } else { format!("{path}.{ext}") };
let bytes = if ext == "glb" { s.mesh_glb_bytes()? } else { s.mesh_obj_bytes() };
std::fs::write(&path, bytes).map_err(|e| bad("file.exportMesh", format!("cannot write {path}: {e}")))?;
s.log.push(format!("Exported mesh to {path}"));
Ok(json!({ "path": path }))
}
#[cfg(target_arch = "wasm32")]
fn unsupported(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Other("file paths are not available in the browser; use the web file buttons".into()))
}
#[cfg(target_arch = "wasm32")]
use unsupported as new_from_mesh;
#[cfg(target_arch = "wasm32")]
use unsupported as open;
#[cfg(target_arch = "wasm32")]
use unsupported as save;
#[cfg(target_arch = "wasm32")]
use unsupported as save_as;
#[cfg(target_arch = "wasm32")]
use unsupported as save_copy;
#[cfg(target_arch = "wasm32")]
use unsupported as reimport;
#[cfg(target_arch = "wasm32")]
use unsupported as export_textures;
#[cfg(target_arch = "wasm32")]
use unsupported as export_mesh;
fn close(s: &mut Session, _: &Value) -> Result<Value> {
let mut next = Session::new_project("Untitled", primitives::material_ball(), "builtin:material_ball", None, 2048)?;
next.viewport = s.viewport;
*s = next;
Ok(Value::Null)
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
#[test]
fn export_mesh_writes_obj_by_default_and_textured_glb() {
let mut s = Session::new_project("t", primitives::material_ball(), "builtin:material_ball", None, 128).unwrap();
let dir = std::env::temp_dir().join(format!("tc_export_mesh_{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let base = dir.join("ball").display().to_string();
let obj = crate::execute(&mut s, "file.exportMesh", &json!({ "path": base })).unwrap();
assert!(obj["path"].as_str().unwrap().ends_with("ball.obj"));
let glb = crate::execute(&mut s, "file.exportMesh", &json!({ "path": base, "format": "glb" })).unwrap();
let bytes = std::fs::read(glb["path"].as_str().unwrap()).unwrap();
let back = texturecraft_formats::import_mesh_bytes("ball.glb", &bytes).unwrap();
assert_eq!(back.mesh.triangle_count(), s.mesh.triangle_count());
assert_eq!(back.mesh.materials, s.mesh.materials);
// Base color, ORM and normal per texture set.
assert_eq!(bytes.windows(9).filter(|w| *w == b"image/png").count(), 3 * s.mesh.materials.len());
assert!(crate::execute(&mut s, "file.exportMesh", &json!({ "path": base, "format": "fbx" })).is_err());
let _ = std::fs::remove_dir_all(&dir);
}
}
+143
View File
@@ -0,0 +1,143 @@
//! JSON views of the session for agents: everything an agent changed must be visible here
//! without a screenshot.
use serde_json::{Value, json};
use texturecraft_core::{Effect, EffectKind, Fill, Filter, Layer, LayerKind, Source};
use crate::Session;
use crate::session::StackTarget;
fn source_json(s: &Source) -> Value {
match s {
Source::Uniform(v) => json!({ "uniform": v }),
Source::Procedural { pattern, low, high } => json!({
"procedural": pattern.kind.label(), "scale": pattern.scale, "seed": pattern.seed, "contrast": pattern.contrast, "low": low, "high": high
}),
Source::Image { name } => json!({ "image": name }),
Source::Anchor { anchor, channel } => json!({ "anchor": anchor.0, "channel": channel.id() }),
}
}
fn fill_json(f: &Fill) -> Value {
json!({
"projection": f.projection.label(),
"sources": f.sources.iter().map(|(c, s)| (c.id().to_string(), source_json(s))).collect::<serde_json::Map<_, _>>(),
})
}
/// A mask or content (`content`) effect.
fn effect_json(s: &Session, e: &Effect, content: bool) -> Value {
let mut ej = json!({ "id": e.id.0, "name": e.name, "kind": e.kind.name(), "visible": e.visible, "blend": e.blend.label(), "opacity": e.opacity });
match &e.kind {
EffectKind::Generator(g) => ej["generator"] = json!({ "type": format!("{:?}", g.kind), "level": g.level, "softness": g.softness, "noise": g.noise_amount, "invert": g.invert }),
EffectKind::Levels(lv) => ej["levels"] = json!([lv.in_low, lv.in_high, lv.gamma, lv.out_low, lv.out_high]),
EffectKind::Paint if content => {
ej["tiles"] = json!(s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == e.id).map(|(_, img)| img.allocated_count()).sum::<usize>())
}
EffectKind::Paint => ej["tiles"] = json!(s.doc.pixels.masks.get(&e.id).map(|i| i.allocated_count()).unwrap_or(0)),
EffectKind::Fill { source, .. } => ej["source"] = source_json(source),
EffectKind::Material(f) => ej["fill"] = fill_json(f),
EffectKind::Filter(Filter::Hsl { hue, saturation, lightness }) => ej["hsl"] = json!([hue, saturation, lightness]),
EffectKind::Filter(Filter::Blur { radius }) => ej["radius"] = json!(radius),
_ => {}
}
ej
}
fn layer_json(s: &Session, l: &Layer, depth: usize) -> Value {
let channels: serde_json::Map<String, Value> =
l.channels.iter().map(|(c, b)| (c.id().to_string(), json!({ "mode": b.mode.label(), "opacity": b.opacity }))).collect();
let mut v = json!({
"id": l.id.0,
"name": l.name,
"kind": l.kind.name(),
"visible": l.visible,
"channels": channels,
"colorTag": l.color_tag,
});
if let LayerKind::Fill(f) = &l.kind {
v["fill"] = fill_json(f);
}
if let Some(src) = l.instance_source() {
let source = s.doc.project.layers.get(&src);
let set = s.doc.project.locate(src).map(|(ts, _, _)| ts);
v["instanceOf"] = json!({ "layer": src.0, "name": source.map(|x| x.name.as_str()), "textureSet": set });
}
if l.height_mask.enabled {
v["heightMask"] = json!({ "contrast": l.height_mask.contrast, "offset": l.height_mask.offset });
}
if matches!(l.kind, LayerKind::Paint) {
// Sorted: the store is a hash map, and inspect output must be stable.
let mut painted: Vec<(&str, usize)> = s.doc.pixels.layers.iter().filter(|((id, _), _)| *id == l.id).map(|((_, c), img)| (c.id(), img.allocated_count())).collect();
painted.sort_unstable();
v["painted"] = json!(painted.iter().map(|(c, n)| json!({ "channel": c, "tiles": n })).collect::<Vec<_>>());
}
if let Some(m) = &l.mask {
v["mask"] = json!({
"enabled": m.enabled,
"background": format!("{:?}", m.background).to_lowercase(),
"effects": m.effects.iter().map(|e| effect_json(s, e, false)).collect::<Vec<_>>(),
});
}
if !l.content_effects.is_empty() {
v["contentEffects"] = json!(l.content_effects.iter().map(|e| effect_json(s, e, true)).collect::<Vec<_>>());
}
if depth < texturecraft_core::project::MAX_DEPTH {
let kids: Vec<Value> = l.children().iter().rev().filter_map(|c| s.doc.project.layers.get(c)).map(|c| layer_json(s, c, depth + 1)).collect();
if l.is_group() {
v["children"] = json!(kids);
}
}
v
}
/// The layer stack of texture set `ts`, top → bottom (as displayed).
pub fn stack(s: &Session, ts: usize) -> Value {
let Some(set) = s.doc.project.texture_sets.get(ts) else { return Value::Null };
json!(set.stack.iter().rev().filter_map(|id| s.doc.project.layers.get(id)).map(|l| layer_json(s, l, 0)).collect::<Vec<_>>())
}
pub fn texture_sets(s: &Session) -> Value {
json!(
s.doc
.project
.texture_sets
.iter()
.enumerate()
.map(|(i, t)| json!({
"index": i,
"name": t.name,
"resolution": t.resolution,
"channels": t.channels.iter().map(|(c, f)| json!({ "channel": c.id(), "format": f.label() })).collect::<Vec<_>>(),
"layers": s.doc.project.walk(i).len(),
"baked": crate::project_cmds::baked_json(s.doc.baked.get(&i)),
"visible": t.visible,
"active": i == s.ts(),
}))
.collect::<Vec<_>>()
)
}
/// The whole session.
pub fn session(s: &Session) -> Value {
let ts = s.ts();
json!({
"project": s.doc.project.name,
"mesh": { "source": s.doc.project.mesh, "triangles": s.mesh.triangle_count(), "vertices": s.mesh.vertex_count(), "materials": s.mesh.materials },
"path": s.path,
"modified": s.modified,
"textureSets": texture_sets(s),
"bakeMeshes": crate::bake_cmds::meshes_json(s),
"activeTextureSet": ts,
"selectedLayer": s.selected_layer().map(|l| l.0),
"target": match s.target { StackTarget::Content => json!("content"), StackTarget::Mask => json!("mask"), StackTarget::Effect(e) => json!(e.0) },
"layers": stack(s, ts),
"tool": { "tool": s.tool.tool.id(), "brush": crate::tool_cmds::brush_json(s) },
"view": s.view.label(),
"camera": crate::view_cmds::camera_json(s),
"display": s.doc.project.display,
"history": { "undo": s.undo_label(), "redo": s.redo_label(), "depth": s.history_labels().len() },
"memoryBytes": s.memory().total(),
"pendingTiles": s.pending_tiles(),
})
}
+163
View File
@@ -0,0 +1,163 @@
//! Instance layers (linked copies that draw another layer, possibly in another texture set) and
//! per-layer properties set through `layer.set`.
use serde_json::{Value, json};
use texturecraft_core::{Layer, LayerId, LayerKind};
use crate::commands::{CommandSpec, bad, boolp, content_param, f32p, has_layer, layer_param, u64p};
use crate::session::{Document, StackTarget};
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"layer.instance",
"Create instance",
["Layers"],
None,
"{layer?, ts?: texture set (default active)} — a linked instance above that set's selection; edits to the source show in every instance",
has_layer,
instance
),
cmd!(
"layer.pasteInstance",
"Paste as instance",
["Layers"],
None,
"{} — an instance of the copied layer above the selection",
can_paste_instance,
paste_instance
),
cmd!(
"layer.set",
"Set layer properties",
[],
None,
"{layer?, heightMask?: {enabled?, contrast?: 0..64, offset?: -1..1} | bool} — mask with height: m' = saturate(m + contrast·4m(1−m)·(height + offset))",
has_layer,
set
),
]
}
/// Insert an instance of `source` (an instance's own source) into texture set `ts` above that
/// set's selection, and select it.
pub(crate) fn make_instance(s: &mut Session, source: LayerId, ts: usize) -> Result<LayerId> {
let src = s.doc.project.content_layer(source).ok_or_else(|| EngineError::Other(format!("layer {} has no source to instance", source.0)))?;
let (src_id, name) = (src.id, src.name.clone());
let id = s.doc.project.alloc_id();
let sel = s.selected.get(&ts).copied().filter(|l| s.doc.project.locate(*l).is_some_and(|(t, _, _)| t == ts));
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(Layer::is_group);
s.doc.project.insert_layer(ts, Layer::new(id, name, LayerKind::Instance { source: src_id }, &[]), sel, inside)?;
s.selected.insert(ts, id);
if ts == s.ts() {
s.target = StackTarget::Content;
}
Ok(id)
}
fn instance(s: &mut Session, p: &Value) -> Result<Value> {
let source = layer_param(s, "layer.instance", p)?;
let ts = match u64p(p, "ts") {
Some(t) => usize::try_from(t).ok().filter(|t| *t < s.set_count()).ok_or_else(|| bad("layer.instance", format!("no texture set {t}")))?,
None => s.ts(),
};
let id = s.edit("Create instance", |s| make_instance(s, source, ts))?;
Ok(json!({ "layer": id.0, "textureSet": ts }))
}
fn can_paste_instance(s: &Session) -> std::result::Result<(), String> {
match &s.clipboard {
Some((_, id)) if s.doc.project.locate(*id).is_some() => Ok(()),
Some(_) => Err("the copied layer is no longer in the project (paste it instead)".into()),
None => Err("the layer clipboard is empty".into()),
}
}
fn paste_instance(s: &mut Session, _: &Value) -> Result<Value> {
let id = s.clipboard.as_ref().map(|(_, id)| *id).ok_or_else(|| EngineError::Other("the layer clipboard is empty".into()))?;
let ts = s.ts();
let new = s.edit("Paste as instance", |s| make_instance(s, id, ts))?;
Ok(json!({ "layer": new.0 }))
}
/// Replace instance `inst` with an independent copy of its source taken from `src` (its name,
/// visibility, color tag and own mask are kept). Returns the copy.
pub(crate) fn detach(s: &mut Session, src: &Document, inst: LayerId) -> Result<LayerId> {
let layer = s.doc.project.layer(inst)?.clone();
let source = layer.instance_source().ok_or_else(|| EngineError::Other(format!("\"{}\" is not an instance", layer.name)))?;
let (ts, _, _) = s.doc.project.locate(inst).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let copy = crate::layer_ops::copy_tree(src, source, &mut s.doc, ts, Some(inst), false, 0)?;
let l = s.doc.project.layer_mut(copy)?;
l.name = layer.name;
l.visible = layer.visible;
l.color_tag = layer.color_tag;
if layer.mask.is_some() {
l.mask = layer.mask;
}
s.doc.project.remove_layer(inst)?;
if s.selected.get(&ts) == Some(&inst) {
s.selected.insert(ts, copy);
}
Ok(copy)
}
/// After layers were removed: instances of a removed layer become independent copies (taken
/// from `before`, the document before the removal), then pixels of removed layers are dropped.
pub(crate) fn detach_orphans(s: &mut Session, before: &Document) -> Result<()> {
// Copies can hold instances of removed layers in turn; the depth bounds the rounds.
for _ in 0..=texturecraft_core::project::MAX_DEPTH {
let orphans: Vec<LayerId> = s
.doc
.project
.layers
.values()
.filter(|l| l.instance_source().is_some_and(|src| !s.doc.project.layers.contains_key(&src) && before.project.layers.contains_key(&src)))
.map(|l| l.id)
.collect();
if orphans.is_empty() {
break;
}
for inst in orphans {
detach(s, before, inst)?;
}
}
prune_pixels(&mut s.doc);
Ok(())
}
/// Drop pixels of layers and effects that no longer exist.
pub(crate) fn prune_pixels(doc: &mut Document) {
let p = &doc.project;
let alive: std::collections::BTreeSet<LayerId> = p
.layers
.values()
.flat_map(|l| std::iter::once(l.id).chain(l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()).map(|e| e.id)))
.collect();
doc.pixels.retain(|x| alive.contains(&x));
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
// Linked properties live on an instance's source.
let id = content_param(s, "layer.set", p)?;
let hm = match p.get("heightMask") {
Some(Value::Bool(on)) => json!({ "enabled": on }),
Some(v @ Value::Object(_)) => v.clone(),
Some(_) => return Err(bad("layer.set", "`heightMask` must be an object {enabled?, contrast?, offset?} or a bool")),
None => return Err(bad("layer.set", "give `heightMask`")),
};
let out = s.edit("Layer properties", |s| {
let h = &mut s.doc.project.layer_mut(id)?.height_mask;
if let Some(on) = boolp(&hm, "enabled") {
h.enabled = on;
}
if let Some(c) = f32p(&hm, "contrast") {
h.contrast = c.clamp(0.0, 64.0);
}
if let Some(o) = f32p(&hm, "offset") {
h.offset = o.clamp(-1.0, 1.0);
}
Ok(json!({ "layer": id.0, "heightMask": { "enabled": h.enabled, "contrast": h.contrast, "offset": h.offset } }))
})?;
Ok(out)
}
+404
View File
@@ -0,0 +1,404 @@
//! Layer stack commands: add, remove, duplicate, select, rename, visibility, reorder, group,
//! per-channel blending and fill sources.
use serde_json::{Value, json};
use texturecraft_core::{BlendMode, Channel, ChannelBlend, EffectKind, Fill, Layer, LayerId, LayerKind, Procedural, ProceduralKind, Projection, Source};
use crate::commands::{CommandSpec, always, bad, blend_param, boolp, channel_param, color_param, content_param, f32p, has_layer, layer_param, strp, u64p};
use crate::{EngineError, Result, Session, cmd, session::StackTarget};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("layer.add.paint", "Add paint layer", ["Layers"], None, "{name?}", always, add_paint),
cmd!("layer.add.fill", "Add fill layer", ["Layers"], None, "{name?, color?, roughness?, metallic?}", always, add_fill),
cmd!("layer.add.group", "Add folder", ["Layers"], None, "{name?}", always, add_group),
cmd!("layer.remove", "Remove layer(s)", ["Layers"], Some("Delete"), "{layer?}", has_layer, remove),
cmd!("layer.duplicate", "Duplicate layer(s)", ["Layers"], Some("Ctrl+D"), "{layer?}", has_layer, duplicate),
cmd!("layer.group", "Group layer(s)", ["Layers"], Some("Ctrl+G"), "{layer?}", has_layer, group),
cmd!("layer.select", "Select layer", [], None, "{layer, target?: content|mask|<effect id>}", always, select),
cmd!("layer.rename", "Rename layer", [], None, "{layer?, name}", has_layer, rename),
cmd!("layer.visible", "Toggle layer visibility", [], None, "{layer?, visible?}", has_layer, visible),
cmd!("layer.move", "Move layer", [], None, "{layer?, index?} | {layer?, above?: id|null, inside?: bool} | {layer?, delta: ±n}", has_layer, move_layer),
cmd!("layer.blend", "Set channel blending", [], None, "{layer?, channel?: id|all, mode?, opacity?: 0..1, enabled?}", has_layer, blend),
cmd!(
"layer.fill.set",
"Set fill source",
[],
None,
"{layer? | effect?: content fill effect id, channel, color?|value?|procedural?: kind, scale?, seed?, contrast?, balance?, invert?, low?, high?|image?|anchor?: anchor effect id, anchorChannel?, enabled?}",
has_layer,
fill_set
),
cmd!(
"layer.fill.projection",
"Set fill projection",
[],
None,
"{layer? | effect?: content fill effect id, projection: uv|triplanar|planar|spherical|cylindrical, scale?, rotation?, sharpness?, axis?}",
has_layer,
fill_projection
),
cmd!("layer.colorTag", "Set layer color tag", [], None, "{layer?, tag?: 0..7 (absent clears)}", has_layer, color_tag),
cmd!("layer.list", "List layers", [], None, "{ts?}", always, list),
]
}
/// Insert a layer above the selection (inside it when it is a group) and select it.
pub(crate) fn insert_selected(s: &mut Session, layer: Layer) -> Result<LayerId> {
let ts = s.ts();
let sel = s.selected_layer();
let inside = sel.and_then(|id| s.doc.project.layer(id).ok()).is_some_and(|l| l.is_group());
let id = s.doc.project.insert_layer(ts, layer, sel, inside)?;
s.selected.insert(ts, id);
s.target = StackTarget::Content;
Ok(id)
}
fn channels_of(s: &Session) -> Vec<Channel> {
s.doc.project.texture_set(s.ts()).map(|t| t.channel_list()).unwrap_or_default()
}
fn add_paint(s: &mut Session, p: &Value) -> Result<Value> {
let ts = s.ts();
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.next_layer_name(ts, "Layer"));
let id = s.edit("Add paint layer", |s| {
let id = s.doc.project.alloc_id();
insert_selected(s, Layer::new(id, name, LayerKind::Paint, &channels_of(s)))
})?;
Ok(json!({ "layer": id.0 }))
}
/// A uniform fill from the `color`, `roughness`, `metallic`, `height` and `opacity` params.
pub(crate) fn fill_from(p: &Value) -> Fill {
let mut fill = Fill::default();
if let Some(c) = color_param(p, "color") {
fill.sources.insert(Channel::BaseColor, Source::Uniform(c));
}
for (key, ch) in [("roughness", Channel::Roughness), ("metallic", Channel::Metallic), ("height", Channel::Height), ("opacity", Channel::Opacity)] {
if let Some(v) = f32p(p, key) {
fill.sources.insert(ch, Source::Uniform([v; 3]));
}
}
fill
}
fn add_fill(s: &mut Session, p: &Value) -> Result<Value> {
let ts = s.ts();
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.next_layer_name(ts, "Fill layer"));
let fill = fill_from(p);
let id = s.edit("Add fill layer", |s| {
let id = s.doc.project.alloc_id();
insert_selected(s, Layer::new(id, name, LayerKind::Fill(fill), &channels_of(s)))
})?;
Ok(json!({ "layer": id.0 }))
}
fn add_group(s: &mut Session, p: &Value) -> Result<Value> {
let ts = s.ts();
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.next_layer_name(ts, "Folder"));
let id = s.edit("Add folder", |s| {
let id = s.doc.project.alloc_id();
let mut l = Layer::new(id, name, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels_of(s));
for b in l.channels.values_mut() {
b.mode = BlendMode::Passthrough;
}
insert_selected(s, l)
})?;
Ok(json!({ "layer": id.0 }))
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.remove", p)?;
let before = s.doc.clone();
let removed = s.edit("Remove layer", |s| {
let (ts, parent, i) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let removed = s.doc.project.remove_layer(id)?;
// Instances of what was removed keep their look as independent layers.
crate::instance_cmds::detach_orphans(s, &before)?;
// Select the layer below (or above) the removed one.
let list = match parent {
Some(g) => s.doc.project.layer(g).map(|l| l.children().to_vec()).unwrap_or_default(),
None => s.doc.project.texture_set(ts).map(|t| t.stack.clone()).unwrap_or_default(),
};
let next = list.get(i.saturating_sub(1)).or(list.first()).copied().or(parent);
match next {
Some(n) => s.selected.insert(ts, n),
None => s.selected.remove(&ts),
};
Ok(removed)
})?;
Ok(json!({ "removed": removed.iter().map(|l| l.0).collect::<Vec<_>>() }))
}
fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.duplicate", p)?;
let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let src = s.doc.clone();
let new = s.edit("Duplicate layer", |s| {
let new = crate::layer_ops::copy_tree(&src, id, &mut s.doc, ts, Some(id), false, 0)?;
let name = format!("{} copy", src.project.layer(id)?.name);
s.doc.project.layer_mut(new)?.name = name;
Ok(new)
})?;
s.selected.insert(ts, new);
Ok(json!({ "layer": new.0 }))
}
fn group(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.group", p)?;
let g = s.edit("Group layers", |s| {
let (ts, _, _) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let gid = s.doc.project.alloc_id();
let name = s.doc.project.next_layer_name(ts, "Folder");
let channels = s.doc.project.texture_set(ts)?.channel_list();
let mut gl = Layer::new(gid, name, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels);
for b in gl.channels.values_mut() {
b.mode = BlendMode::Passthrough;
}
s.doc.project.insert_layer(ts, gl, Some(id), false)?;
s.doc.project.move_above(id, Some(gid), true)?;
s.selected.insert(ts, gid);
Ok(gid)
})?;
Ok(json!({ "layer": g.0 }))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.select", p)?;
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| bad("layer.select", "layer not in a stack"))?;
s.active_set = ts;
s.selected.insert(ts, id);
s.target = match p.get("target") {
Some(Value::String(t)) if t == "mask" => {
if s.doc.project.layer(s.doc.project.mask_owner(id))?.mask.is_none() {
return Err(bad("layer.select", "the layer has no mask"));
}
StackTarget::Mask
}
Some(Value::String(t)) if t == "content" => StackTarget::Content,
Some(v) => match v.as_u64() {
Some(e) if s.doc.project.effect(LayerId(e)).is_some_and(|(owner, _)| owner == id) => StackTarget::Effect(LayerId(e)),
_ => return Err(bad("layer.select", "target must be content, mask or an effect id of this layer")),
},
None => StackTarget::Content,
};
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "layer": id.0, "textureSet": ts }))
}
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.rename", p)?;
let name = strp(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad("layer.rename", "`name` is required"))?.to_string();
if name.chars().count() > 256 {
return Err(bad("layer.rename", "name is longer than 256 characters"));
}
s.edit("Rename layer", |s| {
s.doc.project.layer_mut(id)?.name = name;
Ok(())
})?;
Ok(Value::Null)
}
fn visible(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.visible", p)?;
let v = s.edit("Layer visibility", |s| {
let l = s.doc.project.layer_mut(id)?;
l.visible = boolp(p, "visible").unwrap_or(!l.visible);
Ok(l.visible)
})?;
Ok(json!({ "visible": v }))
}
fn move_layer(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.move", p)?;
s.edit("Move layer", |s| {
if let Some(d) = p.get("delta").and_then(Value::as_i64) {
let (_, _, i) = s.doc.project.locate(id).ok_or(EngineError::Other("layer not in a stack".into()))?;
let to = (i as i64 + d).max(0) as usize;
s.doc.project.move_layer(id, to)?;
} else if let Some(i) = u64p(p, "index") {
s.doc.project.move_layer(id, usize::try_from(i).unwrap_or(usize::MAX))?;
} else if p.get("above").is_some() {
let above = u64p(p, "above").map(LayerId);
s.doc.project.move_above(id, above, boolp(p, "inside").unwrap_or(false))?;
} else {
return Err(bad("layer.move", "give `delta`, `index` or `above`"));
}
Ok(())
})?;
Ok(Value::Null)
}
fn blend(s: &mut Session, p: &Value) -> Result<Value> {
let id = content_param(s, "layer.blend", p)?;
let all = strp(p, "channel") == Some("all");
let ch = if all { None } else { channel_param("layer.blend", p, "channel")? };
let mode = blend_param("layer.blend", p, "mode")?;
let opacity = f32p(p, "opacity").map(|o| o.clamp(0.0, 1.0));
let enabled = boolp(p, "enabled");
let ts_channels = channels_of(s);
s.edit("Layer blending", |s| {
let l = s.doc.project.layer_mut(id)?;
let targets: Vec<Channel> = match ch {
Some(c) => vec![c],
None => ts_channels.clone(),
};
for c in targets {
match enabled {
Some(false) => {
l.channels.remove(&c);
continue;
}
Some(true) => {
let mode = if l.is_group() { BlendMode::Passthrough } else { BlendMode::Normal };
l.channels.entry(c).or_insert(ChannelBlend { mode, opacity: 1.0 });
}
None => {}
}
if let Some(b) = l.channels.get_mut(&c) {
if let Some(m) = mode {
b.mode = m;
}
if let Some(o) = opacity {
b.opacity = o;
}
}
}
Ok(())
})?;
Ok(Value::Null)
}
/// Which fill `layer.fill.*` edits: a fill layer's (`layer`) or a content fill effect's
/// (`effect`).
#[derive(Clone, Copy)]
enum FillTarget {
Layer(LayerId),
Effect(LayerId),
}
fn fill_target(s: &Session, p: &Value, cmd: &str) -> Result<FillTarget> {
match u64p(p, "effect").map(LayerId) {
Some(e) => match s.doc.project.effect(e) {
Some((_, x)) if matches!(x.kind, EffectKind::Material(_)) => Ok(FillTarget::Effect(e)),
_ => Err(bad(cmd, format!("{} is not a content fill effect", e.0))),
},
None => Ok(FillTarget::Layer(content_param(s, cmd, p)?)),
}
}
fn fill_mut(s: &mut Session, target: FillTarget) -> Result<&mut Fill> {
match target {
FillTarget::Layer(id) => match &mut s.doc.project.layer_mut(id)?.kind {
LayerKind::Fill(f) => Ok(f),
_ => Err(EngineError::Other("not a fill layer".into())),
},
FillTarget::Effect(e) => match s.doc.project.effect_mut(e).map(|x| &mut x.kind) {
Some(EffectKind::Material(f)) => Ok(f),
_ => Err(EngineError::Other("not a content fill effect".into())),
},
}
}
fn fill_set(s: &mut Session, p: &Value) -> Result<Value> {
let target = fill_target(s, p, "layer.fill.set")?;
let ch = channel_param("layer.fill.set", p, "channel")?.ok_or_else(|| bad("layer.fill.set", "`channel` is required"))?;
let enabled = boolp(p, "enabled");
let source = if let Some(kind) = strp(p, "procedural") {
let kind = ProceduralKind::parse(kind).ok_or_else(|| bad("layer.fill.set", format!("unknown procedural `{kind}`")))?;
let mut pr = Procedural::new(kind);
if let Some(v) = f32p(p, "scale") {
pr.scale = v.clamp(0.001, 1000.0);
}
if let Some(v) = u64p(p, "seed") {
pr.seed = v as u32;
}
if let Some(v) = f32p(p, "contrast") {
pr.contrast = v.clamp(0.0, 20.0);
}
if let Some(v) = f32p(p, "balance") {
pr.balance = v.clamp(-1.0, 1.0);
}
pr.invert = boolp(p, "invert").unwrap_or(false);
Some(Source::Procedural { pattern: pr, low: color_param(p, "low").unwrap_or([0.0; 3]), high: color_param(p, "high").unwrap_or([1.0; 3]) })
} else if let Some(c) = color_param(p, "color").or_else(|| color_param(p, "value")) {
Some(Source::Uniform(c))
} else if let Some(name) = strp(p, "image") {
Some(Source::Image { name: name.to_string() })
} else if let Some(a) = u64p(p, "anchor") {
let reader = match target {
FillTarget::Layer(id) => Some(id),
FillTarget::Effect(e) => s.doc.project.effect(e).map(|(owner, _)| owner),
};
let reader = reader.ok_or_else(|| bad("layer.fill.set", "the fill is not in a layer"))?;
let anchor_channel = channel_param("layer.fill.set", p, "anchorChannel")?.unwrap_or(ch);
Some(crate::mask_cmds::anchor_source(s, "layer.fill.set", reader, LayerId(a), anchor_channel)?)
} else if enabled.is_some() {
None
} else {
return Err(bad("layer.fill.set", "give `color`, `value`, `procedural`, `image`, `anchor` or `enabled`"));
};
s.edit("Set fill", |s| {
let f = fill_mut(s, target)?;
match target {
// A fill effect's channel is on while it has a source.
FillTarget::Effect(_) if enabled == Some(false) => {
f.sources.remove(&ch);
}
FillTarget::Effect(_) => {
let src = source.unwrap_or_else(|| f.source(ch));
f.sources.insert(ch, src);
}
FillTarget::Layer(id) => {
if let Some(src) = source {
f.sources.insert(ch, src);
}
let l = s.doc.project.layer_mut(id)?;
if enabled == Some(false) {
l.channels.remove(&ch);
} else {
l.channels.entry(ch).or_default();
}
}
}
Ok(())
})?;
Ok(Value::Null)
}
pub(crate) fn projection_from(p: &Value, cmd: &str) -> Result<Projection> {
let scale = f32p(p, "scale").unwrap_or(1.0).clamp(0.001, 1000.0);
Ok(match strp(p, "projection").unwrap_or("uv") {
"uv" => Projection::Uv { scale: [scale, scale], rotation: f32p(p, "rotation").unwrap_or(0.0), offset: [0.0, 0.0] },
"triplanar" | "tri-planar" => Projection::Triplanar { scale, sharpness: f32p(p, "sharpness").unwrap_or(8.0).clamp(1.0, 64.0), offset: [0.0; 3] },
"planar" => Projection::Planar { scale, axis: u64p(p, "axis").unwrap_or(2).min(2) as u8, offset: [0.0; 3] },
"spherical" => Projection::Spherical { scale },
"cylindrical" => Projection::Cylindrical { scale, axis: u64p(p, "axis").unwrap_or(1).min(2) as u8 },
other => return Err(bad(cmd, format!("unknown projection `{other}`"))),
})
}
fn fill_projection(s: &mut Session, p: &Value) -> Result<Value> {
let target = fill_target(s, p, "layer.fill.projection")?;
let proj = projection_from(p, "layer.fill.projection")?;
s.edit("Fill projection", |s| {
fill_mut(s, target)?.projection = proj;
Ok(())
})?;
Ok(Value::Null)
}
fn color_tag(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.colorTag", p)?;
let tag = u64p(p, "tag").map(|t| t.min(7) as u8);
s.edit("Layer color tag", |s| {
s.doc.project.layer_mut(id)?.color_tag = tag;
Ok(())
})?;
Ok(Value::Null)
}
fn list(s: &mut Session, p: &Value) -> Result<Value> {
let ts = u64p(p, "ts").map(|t| t as usize).unwrap_or(s.ts());
Ok(crate::inspect::stack(s, ts))
}
+217
View File
@@ -0,0 +1,217 @@
//! Layer clipboard (copy, cut, paste across texture sets), flatten, and resampling of painted
//! pixels when a texture set changes size.
use serde_json::{Value, json};
use texturecraft_core::{Channel, ChannelKind, LayerId, LayerKind};
use texturecraft_texel::TileImage;
use crate::commands::{CommandSpec, boolp, has_layer, layer_param};
use crate::session::{Document, StackTarget};
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("layer.copy", "Copy layer(s)", ["Layers"], Some("Ctrl+C"), "{layer?}", has_layer, copy),
cmd!("layer.cut", "Cut layer(s)", ["Layers"], Some("Ctrl+X"), "{layer?}", has_layer, cut),
cmd!("layer.paste", "Paste layer(s)", ["Layers"], Some("Ctrl+V"), "{} — above the selection, in the active texture set", can_paste, paste),
cmd!("layer.flatten", "Flatten layer", ["Layers"], Some("Ctrl+M"), "{layer?} — a fill or masked paint layer becomes a plain paint layer", has_layer, flatten),
cmd!(
"layer.instantiateAll",
"Instantiate across texture sets",
["Layers"],
Some("Ctrl+Shift+D"),
"{layer?, copy?: bool} — a linked instance of the layer on top of every other texture set (`copy`: independent copies)",
has_layer,
to_all_sets
),
]
}
fn can_paste(s: &Session) -> std::result::Result<(), String> {
if s.clipboard.is_some() { Ok(()) } else { Err("the layer clipboard is empty".into()) }
}
/// Encoded "nothing painted" texel for a channel image (value 0, coverage 0).
pub(crate) fn empty_texel(c: Channel) -> Vec<u16> {
let zero = if c.kind() == ChannelKind::Signed { texturecraft_texel::to_u16_signed(0.0) } else { 0 };
let mut v = vec![zero; c.components()];
v.push(0);
v
}
fn fit(img: &TileImage, res: u32, empty: &[u16]) -> TileImage {
if img.width() == res { img.clone() } else { img.resampled(res, res, empty) }
}
/// Copy layer `id` of document `src` (recursively, with pixels) into the session's texture set
/// `ts`, above `above` (or inside it when `inside`). Pixels are resampled to the target set's
/// resolution. Returns the new id.
pub(crate) fn copy_tree(src: &Document, id: LayerId, s: &mut Document, ts: usize, above: Option<LayerId>, inside: bool, depth: usize) -> Result<LayerId> {
if depth > texturecraft_core::project::MAX_DEPTH {
return Err(EngineError::Other("layer groups nested too deeply".into()));
}
let res = s.project.texture_set(ts)?.resolution;
let channels = s.project.texture_set(ts)?.channel_list();
let layer = src.project.layer(id)?.clone();
let new = s.project.alloc_id();
let mut copy = layer.clone();
copy.id = new;
// Channels the target set doesn't have are dropped; ones it has but the source didn't
// stay disabled.
copy.channels.retain(|c, _| channels.contains(c));
for e in copy.mask.iter_mut().flat_map(|m| m.effects.iter_mut()).chain(copy.content_effects.iter_mut()) {
let old = e.id;
e.id = s.project.alloc_id();
if let Some(img) = src.pixels.masks.get(&old) {
s.pixels.masks.insert(e.id, fit(img, res, &[0, 0]));
}
// Content paint effects keep per-channel pixels.
for c in channels.iter().copied() {
if let Some(img) = src.pixels.layer(old, c) {
s.pixels.layers.insert((e.id, c), fit(img, res, &empty_texel(c)));
}
}
}
let children = layer.children().to_vec();
if let LayerKind::Group { children: c, .. } = &mut copy.kind {
c.clear();
}
for c in Channel::ALL {
if let Some(img) = src.pixels.layer(id, c)
&& channels.contains(&c)
{
s.pixels.layers.insert((new, c), fit(img, res, &empty_texel(c)));
}
}
s.project.insert_layer(ts, copy, above, inside)?;
let mut below = None;
for c in children {
// Children keep their bottom → top order inside the new group.
let placed = match below {
None => copy_tree(src, c, s, ts, Some(new), true, depth + 1)?,
Some(b) => copy_tree(src, c, s, ts, Some(b), false, depth + 1)?,
};
below = Some(placed);
}
Ok(new)
}
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.copy", p)?;
s.clipboard = Some((s.doc.clone(), id));
Ok(json!({ "copied": id.0 }))
}
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.cut", p)?;
s.clipboard = Some((s.doc.clone(), id));
crate::execute(s, "layer.remove", &json!({ "layer": id.0 }))?;
Ok(json!({ "cut": id.0 }))
}
fn paste(s: &mut Session, _: &Value) -> Result<Value> {
let (src, id) = s.clipboard.clone().ok_or_else(|| EngineError::Other("the layer clipboard is empty".into()))?;
let new = s.edit("Paste layer", |s| {
let ts = s.ts();
let sel = s.selected_layer();
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group());
let new = copy_tree(&src, id, &mut s.doc, ts, sel, inside, 0)?;
s.selected.insert(ts, new);
s.target = StackTarget::Content;
Ok(new)
})?;
Ok(json!({ "layer": new.0 }))
}
fn to_all_sets(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.instantiateAll", p)?;
let (from, _, _) = s.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let src = s.doc.clone();
let copy = boolp(p, "copy").unwrap_or(false);
let label = if copy { "Copy layer to all texture sets" } else { "Instantiate across texture sets" };
let made = s.edit(label, |s| {
let mut made = Vec::new();
for ts in (0..s.set_count()).filter(|ts| *ts != from) {
let new = if copy {
copy_tree(&src, id, &mut s.doc, ts, None, false, 0)?
} else {
// On top of the set: clear its selection first.
s.selected.remove(&ts);
crate::instance_cmds::make_instance(s, id, ts)?
};
made.push(new.0);
}
Ok(made)
})?;
Ok(json!({ "layers": made }))
}
fn flatten(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "layer.flatten", p)?;
let (ts, _, _) = s.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let layer = s.doc.project.layer(id)?.clone();
// An instance flattens what it draws into a plain layer of its own.
let content = s.doc.project.content_layer(id).cloned().ok_or_else(|| EngineError::Other("the instance's source is missing".into()))?;
if content.is_group() {
return Err(EngineError::Other("flattening a folder is not supported yet; flatten its layers".into()));
}
s.update();
let cache = s.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let res = cache.resolution;
let tiles: Vec<(u32, u32)> = cache.covered_tiles.iter().copied().collect();
let empty = Default::default();
let inputs = texturecraft_compose::Inputs {
project: &s.doc.project,
ts,
mesh: &s.mesh,
gbuf: &cache.gbuf,
pixels: &s.doc.pixels,
baked: s.doc.baked.get(&ts).unwrap_or(&empty),
preview: None,
images: &s.images,
bounds: s.mesh.bounds(),
};
let flat = texturecraft_compose::flatten_layer(&inputs, id, &tiles).ok_or_else(|| EngineError::Other("nothing to flatten".into()))?;
s.edit("Flatten layer", |s| {
for c in Channel::ALL {
s.doc.pixels.layers.remove(&(id, c));
}
let effects: Vec<LayerId> = layer.mask.iter().flat_map(|m| m.effects.iter()).chain(layer.content_effects.iter()).map(|e| e.id).collect();
s.doc.pixels.masks.retain(|e, _| !effects.contains(e));
s.doc.pixels.layers.retain(|(e, _), _| !effects.contains(e));
for (c, (tx, ty), data) in flat {
let img = s.doc.pixels.layer_mut(id, c, res);
img.set_tile(tx, ty, Some(std::sync::Arc::new(data)));
}
let channels = s.doc.project.texture_set(ts)?.channel_list();
let l = s.doc.project.layer_mut(id)?;
l.kind = LayerKind::Paint;
l.mask = None;
l.content_effects.clear();
l.height_mask = Default::default();
l.channels = content.channels.into_iter().filter(|(c, _)| channels.contains(c)).collect();
s.target = StackTarget::Content;
Ok(())
})?;
Ok(json!({ "layer": id.0 }))
}
/// Resample every painted image of texture set `ts` to `res` (after a size change).
pub(crate) fn resample_set(s: &mut Session, ts: usize, res: u32) {
let ids: Vec<LayerId> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect();
let effect_ids: Vec<LayerId> = ids
.iter()
.filter_map(|id| s.doc.project.layers.get(id))
.flat_map(|l| l.mask.iter().flat_map(|m| m.effects.iter()).chain(l.content_effects.iter()).map(|e| e.id))
.collect();
for ((id, c), img) in s.doc.pixels.layers.iter_mut() {
if (ids.contains(id) || effect_ids.contains(id)) && img.width() != res {
*img = img.resampled(res, res, &empty_texel(*c));
}
}
for (id, img) in s.doc.pixels.masks.iter_mut() {
if effect_ids.contains(id) && img.width() != res {
*img = img.resampled(res, res, &[0, 0]);
}
}
}
+64
View File
@@ -0,0 +1,64 @@
//! # texturecraft-engine
//!
//! The TextureCraft session: a [`Session`] owns the document (project + copy-on-write pixels +
//! baked maps), the mesh with its BVH and per-texture-set caches (UV G-buffer, padding map,
//! composite), snapshot-based undo, the tool state and the active stroke. Every user-visible
//! action is a command in the [`commands`] registry, dispatched by id from the UI, the CLI,
//! the control channel and the MCP server alike.
#![forbid(unsafe_code)]
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
pub mod bake_cmds;
pub mod commands;
pub mod file_cmds;
pub mod inspect;
pub mod instance_cmds;
pub mod layer_cmds;
pub mod layer_ops;
pub mod mask_cmds;
pub mod material_lib;
pub mod materials;
pub mod painting;
pub mod path_tool;
pub mod preview;
pub mod project_cmds;
pub mod quick_mask;
pub mod resource_cmds;
pub mod session;
pub mod set_cmds;
pub mod smart_masks;
pub mod tool_cmds;
pub mod view_cmds;
pub use bake_cmds::{BakeMesh, BakeMeshes, BakeTask};
pub use commands::{CommandSpec, command_specs, execute, find};
pub use path_tool::PathState;
pub use project_cmds::sample_session;
pub use session::{CloneSource, Document, FillMode, Session, SetCache, StackTarget, StencilState, Tool, ToolState, ViewMode};
pub use texturecraft_bake as bake;
pub use texturecraft_compose as compose;
pub use texturecraft_core as core;
pub use texturecraft_formats as formats;
pub use texturecraft_geom as geom;
pub use texturecraft_paint as paint;
pub use texturecraft_texel as texel;
#[derive(Debug, thiserror::Error)]
pub enum EngineError {
#[error("unknown command `{0}`")]
UnknownCommand(String),
#[error("`{cmd}` is not available: {why}")]
Disabled { cmd: String, why: String },
#[error("`{cmd}`: {msg}")]
BadParams { cmd: String, msg: String },
#[error(transparent)]
Core(#[from] texturecraft_core::CoreError),
#[error("{0}")]
Other(String),
}
pub type Result<T> = std::result::Result<T, EngineError>;
/// Version string shown in About, `--version` and window titles.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
+485
View File
@@ -0,0 +1,485 @@
//! Mask and effect commands (the layer context menu's mask section and "Add <effect>").
use serde_json::{Value, json};
use texturecraft_core::{
BlendMode, Channel, CompareOp, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Levels, Mask, MaskBackground, Procedural, ProceduralKind,
Source,
};
use crate::commands::{CommandSpec, bad, blend_param, boolp, channel_param, color_param, f32p, has_layer, layer_param, strp, u64p};
use crate::layer_cmds::projection_from;
use crate::session::StackTarget;
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("mask.add.white", "Add white mask", ["Layers", "Mask"], None, "{layer?}", has_layer, |s, p| add_mask(s, p, MaskBackground::White)),
cmd!("mask.add.black", "Add black mask", ["Layers", "Mask"], None, "{layer?}", has_layer, |s, p| add_mask(s, p, MaskBackground::Black)),
cmd!(
"mask.add.colorSelection",
"Add mask with color selection",
["Layers", "Mask"],
None,
"{layer?, color?: [r,g,b] ID color, tolerance?}",
has_layer,
add_color_mask
),
cmd!("mask.toggle", "Toggle mask", ["Layers", "Mask"], None, "{layer?, enabled?}", has_layer, toggle),
cmd!("mask.invertBackground", "Invert mask background", ["Layers", "Mask"], None, "{layer?}", has_layer, invert_background),
cmd!("mask.invert", "Invert mask", ["Layers", "Mask"], None, "{layer?}", has_layer, invert),
cmd!("mask.clear", "Clear mask", ["Layers", "Mask"], None, "{layer?}", has_layer, clear),
cmd!("mask.remove", "Remove mask", ["Layers", "Mask"], None, "{layer?}", has_layer, remove),
cmd!(
"effect.add.paint",
"Add paint",
["Layers", "Effects"],
None,
"{layer?, target?: mask|content, name?}",
has_layer,
|s, p| push_effect(s, p, EffectKind::Paint, BlendMode::Normal)
),
cmd!(
"effect.add.fill",
"Add fill",
["Layers", "Effects"],
None,
"{layer?, target?: mask|content, name?, mask: value?: 0..1 | procedural?: kind, scale?, seed? | anchor?: anchor effect id, anchorChannel?: channel (height); content: color?, roughness?, metallic?, height?, opacity? (default: every layer channel); projection?}",
has_layer,
add_fill
),
cmd!(
"effect.add.generator",
"Add generator",
["Layers", "Effects"],
None,
"{layer?, name?, generator?: edgeWear|dirt|thinAreas|curvature|ambientOcclusion|position|direction, level?, softness?, noise?, invert?}",
has_layer,
add_generator
),
cmd!(
"effect.add.levels",
"Add levels",
["Layers", "Effects"],
None,
"{layer?, target?: mask|content, name?, inLow?, inHigh?, gamma?, outLow?, outHigh?}",
has_layer,
add_levels
),
cmd!(
"effect.add.filter",
"Add filter",
["Layers", "Effects"],
None,
"{layer?, target?: mask|content, name?, filter?: invert|threshold|blur|sharpen|hsl, level?, radius?, amount?, hue?: turns -1..1, saturation?: -1..1, lightness?: -1..1}",
has_layer,
add_filter
),
cmd!(
"effect.add.compare",
"Add compare mask",
["Layers", "Effects"],
None,
"{layer?, name?, op?: lesser|within|greater, value?, tolerance?}",
has_layer,
add_compare
),
cmd!(
"effect.add.anchor",
"Add anchor point",
["Layers", "Effects"],
None,
"{layer?, name?} (records the stack up to this layer for fills and masks above: effect.add.fill {anchor})",
has_layer,
|s, p| push_effect(s, p, EffectKind::Anchor, BlendMode::Normal)
),
cmd!(
"effect.set",
"Edit effect",
[],
None,
"{effect, visible?, blend?, opacity?, name?, level?, softness?, noise?, noiseScale?, invert?, value?, anchor?, anchorChannel?, inLow?, inHigh?, gamma?, outLow?, outHigh?, radius?, amount?, hue?, saturation?, lightness?, tolerance?}",
has_layer,
set
),
cmd!("effect.remove", "Remove effect", [], None, "{effect}", has_layer, remove_effect),
]
}
fn with_mask<T>(s: &mut Session, p: &Value, cmd: &str, label: &str, f: impl FnOnce(&mut Session, LayerId) -> Result<T>) -> Result<T> {
let id = layer_param(s, cmd, p)?;
s.edit(label, |s| f(s, id))
}
fn add_mask(s: &mut Session, p: &Value, bg: MaskBackground) -> Result<Value> {
let label = if bg == MaskBackground::White { "Add white mask" } else { "Add black mask" };
with_mask(s, p, "mask.add", label, |s, id| {
let l = s.doc.project.layer_mut(id)?;
if l.mask.is_some() {
return Err(EngineError::Other(format!("\"{}\" already has a mask", l.name)));
}
l.mask = Some(Mask::new(bg));
s.target = StackTarget::Mask;
Ok(())
})?;
Ok(Value::Null)
}
fn add_color_mask(s: &mut Session, p: &Value) -> Result<Value> {
let color = color_param(p, "color").unwrap_or([1.0, 0.0, 0.0]);
let tolerance = f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0);
with_mask(s, p, "mask.add.colorSelection", "Add mask with color selection", |s, id| {
let eid = s.doc.project.alloc_id();
let l = s.doc.project.layer_mut(s.doc.project.mask_owner(id))?;
let m = l.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black));
m.effects.push(Effect::new(eid, EffectKind::ColorSelection { colors: vec![color], tolerance }));
Ok(())
})?;
Ok(Value::Null)
}
/// The mask layer `id` draws with (an instance's source's unless it has its own).
fn mask_of(s: &mut Session, id: LayerId) -> Result<&mut Mask> {
let l = s.doc.project.layer_mut(s.doc.project.mask_owner(id))?;
let name = l.name.clone();
l.mask.as_mut().ok_or_else(|| EngineError::Other(format!("\"{name}\" has no mask")))
}
fn toggle(s: &mut Session, p: &Value) -> Result<Value> {
let on = with_mask(s, p, "mask.toggle", "Toggle mask", |s, id| {
let m = mask_of(s, id)?;
m.enabled = boolp(p, "enabled").unwrap_or(!m.enabled);
Ok(m.enabled)
})?;
Ok(json!({ "enabled": on }))
}
fn invert_background(s: &mut Session, p: &Value) -> Result<Value> {
with_mask(s, p, "mask.invertBackground", "Invert mask background", |s, id| {
let m = mask_of(s, id)?;
m.background = if m.background == MaskBackground::White { MaskBackground::Black } else { MaskBackground::White };
Ok(())
})?;
Ok(Value::Null)
}
fn invert(s: &mut Session, p: &Value) -> Result<Value> {
with_mask(s, p, "mask.invert", "Invert mask", |s, id| {
let eid = s.doc.project.alloc_id();
let m = mask_of(s, id)?;
// Inverting twice cancels out.
if m.effects.last().is_some_and(|e| matches!(e.kind, EffectKind::Filter(Filter::Invert))) {
m.effects.pop();
} else {
m.effects.push(Effect::new(eid, EffectKind::Filter(Filter::Invert)));
}
Ok(())
})?;
Ok(Value::Null)
}
fn clear(s: &mut Session, p: &Value) -> Result<Value> {
with_mask(s, p, "mask.clear", "Clear mask", |s, id| {
let m = mask_of(s, id)?;
let ids: Vec<LayerId> = m.effects.drain(..).map(|e| e.id).collect();
for e in ids {
s.doc.pixels.masks.remove(&e);
}
Ok(())
})?;
Ok(Value::Null)
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
with_mask(s, p, "mask.remove", "Remove mask", |s, id| {
let m = s.doc.project.layer_mut(s.doc.project.mask_owner(id))?.mask.take().ok_or_else(|| EngineError::Other("the layer has no mask".into()))?;
for e in m.effects {
s.doc.pixels.masks.remove(&e.id);
}
s.target = StackTarget::Content;
Ok(())
})?;
Ok(Value::Null)
}
/// Whether `effect.add.*` targets the layer content (`target: "content"`) or its mask (the
/// default).
fn content_target(p: &Value, cmd: &str) -> Result<bool> {
match strp(p, "target") {
None | Some("mask") => Ok(false),
Some("content") => Ok(true),
Some(other) => Err(bad(cmd, format!("unknown target `{other}`: use content or mask"))),
}
}
/// A valid `name` param.
fn name_param(p: &Value) -> Option<&str> {
strp(p, "name").filter(|n| !n.trim().is_empty() && n.chars().count() <= 256)
}
/// Add an effect to the selected layer's mask (creating a mask if there is none) or, with
/// `target: "content"` or a content-only effect, to its content stack.
fn push_effect(s: &mut Session, p: &Value, kind: EffectKind, blend: BlendMode) -> Result<Value> {
let content = kind.content_only() == Some(true) || content_target(p, "effect.add")?;
if kind.content_only().is_some_and(|c| c != content) {
return Err(bad("effect.add", format!("{} effects go on masks, not on layer content", kind.name())));
}
let label = format!("Add {}", kind.name().to_ascii_lowercase());
let eid = with_mask(s, p, "effect.add", &label, |s, id| {
let eid = s.doc.project.alloc_id();
// An instance's content and (unless it has its own) mask belong to its source.
let id = if content { s.doc.project.content_layer(id).map_or(id, |l| l.id) } else { s.doc.project.mask_owner(id) };
let l = s.doc.project.layer_mut(id)?;
let bg = if matches!(kind, EffectKind::Generator(_) | EffectKind::Fill { .. }) { MaskBackground::Black } else { MaskBackground::White };
let mut e = Effect::new(eid, kind);
e.blend = blend;
if let Some(n) = name_param(p) {
e.name = n.to_string();
}
if !content {
l.mask.get_or_insert_with(|| Mask::new(bg)).effects.push(e);
} else if l.is_group() {
return Err(EngineError::Other(format!("\"{}\" is a folder: content effects go on paint and fill layers", l.name)));
} else {
l.content_effects.push(e);
}
s.target = StackTarget::Effect(eid);
Ok(eid)
})?;
Ok(json!({ "effect": eid.0 }))
}
/// A source reading anchor point `anchor` for layer `reader`: the anchor must sit on a layer
/// below the reader in the same texture set (the compositor walks bottom → top).
pub(crate) fn anchor_source(s: &Session, cmd: &str, reader: LayerId, anchor: LayerId, channel: Channel) -> Result<Source> {
let owner = match s.doc.project.effect(anchor) {
Some((owner, e)) if matches!(e.kind, EffectKind::Anchor) => owner,
_ => return Err(bad(cmd, format!("{} is not an anchor point", anchor.0))),
};
let (ts, _, _) = s.doc.project.locate(reader).ok_or_else(|| bad(cmd, "layer not in a stack"))?;
let order: Vec<LayerId> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect();
let pos = |id: LayerId| order.iter().position(|x| *x == id);
match (pos(owner), pos(reader)) {
(Some(o), Some(r)) if o < r => Ok(Source::Anchor { anchor, channel }),
_ => Err(bad(cmd, "the anchor point must be on a layer below this one in the same texture set")),
}
}
fn add_fill(s: &mut Session, p: &Value) -> Result<Value> {
let projection = projection_from(p, "effect.add.fill")?;
let blend = blend_param("effect.add.fill", p, "blend")?.unwrap_or(BlendMode::Normal);
let id = layer_param(s, "effect.add.fill", p)?;
if content_target(p, "effect.add.fill")? {
let mut fill = crate::layer_cmds::fill_from(p);
if fill.sources.is_empty() {
fill.sources = s.doc.project.layer(id)?.channels.keys().map(|c| (*c, Source::uniform_of(*c))).collect();
}
fill.projection = projection;
return push_effect(s, p, EffectKind::Material(fill), blend);
}
if let Some(a) = u64p(p, "anchor") {
let channel = channel_param("effect.add.fill", p, "anchorChannel")?.unwrap_or(Channel::Height);
let source = anchor_source(s, "effect.add.fill", id, LayerId(a), channel)?;
return push_effect(s, p, EffectKind::Fill { source, projection }, blend);
}
let source = match strp(p, "procedural") {
Some(k) => {
let kind = ProceduralKind::parse(k).ok_or_else(|| bad("effect.add.fill", format!("unknown procedural `{k}`")))?;
let mut pr = Procedural::new(kind);
if let Some(v) = f32p(p, "scale") {
pr.scale = v.clamp(0.001, 1000.0);
}
if let Some(v) = u64p(p, "seed") {
pr.seed = v as u32;
}
Source::Procedural { pattern: pr, low: [0.0; 3], high: [1.0; 3] }
}
None => Source::Uniform([f32p(p, "value").unwrap_or(1.0).clamp(0.0, 1.0); 3]),
};
push_effect(s, p, EffectKind::Fill { source, projection }, blend)
}
fn generator_from(p: &Value, g: &mut Generator) {
if let Some(v) = f32p(p, "level") {
g.level = v.clamp(0.0, 1.0);
}
if let Some(v) = f32p(p, "softness") {
g.softness = v.clamp(0.0, 1.0);
}
if let Some(v) = f32p(p, "noise") {
g.noise_amount = v.clamp(0.0, 2.0);
}
if let Some(v) = f32p(p, "noiseScale") {
g.noise_scale = v.clamp(0.01, 1000.0);
}
if let Some(v) = u64p(p, "seed") {
g.seed = v as u32;
}
if let Some(v) = boolp(p, "invert") {
g.invert = v;
}
if let Some(d) = color_param(p, "direction") {
g.direction = d;
}
}
fn add_generator(s: &mut Session, p: &Value) -> Result<Value> {
let kind = match strp(p, "generator") {
Some(k) => GeneratorKind::parse(k).ok_or_else(|| bad("effect.add.generator", format!("unknown generator `{k}`")))?,
None => GeneratorKind::EdgeWear,
};
let mut g = Generator::new(kind);
generator_from(p, &mut g);
let blend = blend_param("effect.add.generator", p, "blend")?.unwrap_or(BlendMode::Normal);
push_effect(s, p, EffectKind::Generator(g), blend)
}
fn levels_from(p: &Value, l: &mut Levels) {
for (k, slot) in [("inLow", &mut l.in_low), ("inHigh", &mut l.in_high), ("gamma", &mut l.gamma), ("outLow", &mut l.out_low), ("outHigh", &mut l.out_high)] {
if let Some(v) = f32p(p, k) {
*slot = if k == "gamma" { v.clamp(0.01, 10.0) } else { v.clamp(0.0, 1.0) };
}
}
}
fn add_levels(s: &mut Session, p: &Value) -> Result<Value> {
let mut l = Levels::default();
levels_from(p, &mut l);
push_effect(s, p, EffectKind::Levels(l), BlendMode::Normal)
}
fn add_filter(s: &mut Session, p: &Value) -> Result<Value> {
let f = match strp(p, "filter").unwrap_or("invert") {
"invert" => Filter::Invert,
"threshold" => Filter::Threshold { level: f32p(p, "level").unwrap_or(0.5).clamp(0.0, 1.0) },
"blur" => Filter::Blur { radius: f32p(p, "radius").unwrap_or(2.0).clamp(0.0, 64.0) },
"sharpen" => Filter::Sharpen { amount: f32p(p, "amount").unwrap_or(1.0).clamp(0.0, 10.0) },
"hsl" => {
let mut f = Filter::Hsl { hue: 0.0, saturation: 0.0, lightness: 0.0 };
hsl_from(p, &mut f);
f
}
other => return Err(bad("effect.add.filter", format!("unknown filter `{other}`"))),
};
push_effect(s, p, EffectKind::Filter(f), BlendMode::Normal)
}
fn hsl_from(p: &Value, f: &mut Filter) {
if let Filter::Hsl { hue, saturation, lightness } = f {
for (k, slot) in [("hue", hue), ("saturation", saturation), ("lightness", lightness)] {
if let Some(v) = f32p(p, k) {
*slot = v.clamp(-1.0, 1.0);
}
}
}
}
fn add_compare(s: &mut Session, p: &Value) -> Result<Value> {
let op = match strp(p, "op").unwrap_or("greater") {
"lesser" | "less" => CompareOp::LesserThan,
"within" => CompareOp::WithinTolerance,
"greater" => CompareOp::GreaterThan,
other => return Err(bad("effect.add.compare", format!("unknown op `{other}`"))),
};
let kind =
EffectKind::Compare { op, value: f32p(p, "value").unwrap_or(0.5).clamp(0.0, 1.0), tolerance: f32p(p, "tolerance").unwrap_or(0.1).clamp(0.0, 1.0) };
push_effect(s, p, kind, BlendMode::Normal)
}
fn effect_id(p: &Value, cmd: &str) -> Result<LayerId> {
u64p(p, "effect").map(LayerId).ok_or_else(|| bad(cmd, "`effect` id is required"))
}
fn set(s: &mut Session, p: &Value) -> Result<Value> {
let eid = effect_id(p, "effect.set")?;
let blend = blend_param("effect.set", p, "blend")?;
// A fill reading an anchor: `anchor` picks the anchor point, `anchorChannel` alone
// re-targets the current one.
let anchor = match s.doc.project.effect(eid) {
Some((owner, Effect { kind: EffectKind::Fill { source, .. }, .. })) => {
let (current, channel) = match source {
Source::Anchor { anchor, channel } => (Some(*anchor), *channel),
_ => (None, Channel::Height),
};
let channel_param = channel_param("effect.set", p, "anchorChannel")?;
match u64p(p, "anchor").map(LayerId).or(current.filter(|_| channel_param.is_some())) {
Some(a) => Some(anchor_source(s, "effect.set", owner, a, channel_param.unwrap_or(channel))?),
None => None,
}
}
_ => None,
};
s.edit("Edit effect", |s| {
let e = s.doc.project.effect_mut(eid).ok_or_else(|| bad("effect.set", format!("no effect {}", eid.0)))?;
if let Some(v) = boolp(p, "visible") {
e.visible = v;
}
if let Some(b) = blend {
e.blend = b;
}
if let Some(o) = f32p(p, "opacity") {
e.opacity = o.clamp(0.0, 1.0);
}
if let Some(n) = name_param(p) {
e.name = n.to_string();
}
match &mut e.kind {
EffectKind::Generator(g) => generator_from(p, g),
EffectKind::Levels(l) => levels_from(p, l),
EffectKind::Filter(f @ Filter::Hsl { .. }) => hsl_from(p, f),
EffectKind::Fill { source, .. } => {
if let Some(a) = anchor {
*source = a;
} else if let Some(x) = f32p(p, "value")
&& matches!(source, Source::Uniform(_) | Source::Anchor { .. })
{
*source = Source::Uniform([x.clamp(0.0, 1.0); 3]);
}
}
EffectKind::Filter(Filter::Threshold { level }) => {
if let Some(x) = f32p(p, "level") {
*level = x.clamp(0.0, 1.0);
}
}
EffectKind::Filter(Filter::Blur { radius }) => {
if let Some(x) = f32p(p, "radius") {
*radius = x.clamp(0.0, 256.0);
}
}
EffectKind::Filter(Filter::Sharpen { amount }) => {
if let Some(x) = f32p(p, "amount") {
*amount = x.clamp(0.0, 10.0);
}
}
EffectKind::ColorSelection { tolerance, .. } | EffectKind::Compare { tolerance, .. } => {
if let Some(x) = f32p(p, "tolerance") {
*tolerance = x.clamp(0.0, 1.0);
}
}
_ => {}
}
Ok(())
})?;
Ok(Value::Null)
}
fn remove_effect(s: &mut Session, p: &Value) -> Result<Value> {
let eid = effect_id(p, "effect.remove")?;
s.edit("Remove effect", |s| {
let content = match s.doc.project.effect(eid) {
Some((owner, _)) => s.doc.project.layer(owner)?.content_effects.iter().any(|e| e.id == eid),
None => return Err(bad("effect.remove", format!("no effect {}", eid.0))),
};
for l in s.doc.project.layers.values_mut() {
for list in l.mask.iter_mut().map(|m| &mut m.effects).chain(std::iter::once(&mut l.content_effects)) {
list.retain(|e| e.id != eid);
}
}
s.doc.pixels.masks.remove(&eid);
s.doc.pixels.layers.retain(|(id, _), _| *id != eid);
if s.target == StackTarget::Effect(eid) {
s.target = if content { StackTarget::Content } else { StackTarget::Mask };
}
Ok(())
})?;
Ok(Value::Null)
}
+142
View File
@@ -0,0 +1,142 @@
//! User smart materials: a layer (or folder) saved with its pixels and images as a `.tcmat` file
//! (the `.tcraft` container holding a one-texture-set project), and added back above the
//! selection in any project.
use std::collections::BTreeMap;
use std::sync::Arc;
use serde_json::Value;
use texturecraft_compose::PixelStore;
use texturecraft_core::{EffectKind, LayerId, LayerKind, Project, Source, TextureSet};
use crate::commands::{CommandSpec, always, has_layer};
use crate::session::{Document, StackTarget};
use crate::{EngineError, Result, Session, cmd};
/// Smart material file extension.
pub const SMART_MATERIAL_EXT: &str = "tcmat";
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("material.save", "Create smart material", ["Layers"], None, "{layer?, path: .tcmat file, name?}", has_layer, save),
cmd!("material.load", "Add smart material from file", [], None, "{path: .tcmat file}", always, load),
]
}
fn fe(e: texturecraft_formats::FormatError) -> EngineError {
EngineError::Other(e.to_string())
}
/// Image resources a layer subtree uses (fill sources and fill effects).
pub(crate) fn images_used(p: &Project, id: LayerId, out: &mut Vec<String>, depth: usize) {
if depth > texturecraft_core::project::MAX_DEPTH {
return;
}
let Some(l) = p.layers.get(&id) else { return };
if let LayerKind::Fill(f) = &l.kind {
for s in f.sources.values() {
if let Source::Image { name } = s {
out.push(name.clone());
}
}
}
for e in l.mask.iter().flat_map(|m| m.effects.iter()) {
if let EffectKind::Fill { source: Source::Image { name }, .. } = &e.kind {
out.push(name.clone());
}
}
for c in l.children() {
images_used(p, *c, out, depth + 1);
}
}
impl Session {
/// Serialize layer `id` (with children, pixels and images) as a smart material file.
pub fn smart_material_bytes(&self, id: LayerId, name: &str) -> Result<Vec<u8>> {
let (ts, _, _) = self.doc.project.locate(id).ok_or_else(|| EngineError::Other("layer not in a stack".into()))?;
let src_set = self.doc.project.texture_set(ts)?;
let mut project = Project::new(name, "builtin:none");
let mut set = TextureSet::new(name, 0, src_set.resolution);
set.channels = src_set.channels.clone();
project.texture_sets.push(set);
let mut mini = Document { project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() };
let new = crate::layer_ops::copy_tree(&self.doc, id, &mut mini, 0, None, false, 0)?;
if let Ok(l) = mini.project.layer_mut(new) {
l.name = name.to_string();
}
let mut used = Vec::new();
images_used(&mini.project, new, &mut used, 0);
let resources = used.iter().filter_map(|n| self.doc.resources.get(n).map(|b| (n.clone(), b.as_ref().clone()))).collect();
let pf = texturecraft_formats::ProjectFile {
project: mini.project,
pixels: mini.pixels,
baked: BTreeMap::new(),
mesh: None,
high_poly: Vec::new(),
cage: None,
thumbnail: None,
resources,
};
texturecraft_formats::save_project_bytes(&pf).map_err(fe)
}
/// Add a smart material file above the selection (one undo step). Returns the new layer.
pub fn add_smart_material_bytes(&mut self, bytes: &[u8]) -> Result<LayerId> {
let pf = texturecraft_formats::load_project_bytes(bytes).map_err(fe)?;
let root = pf.project.texture_sets.first().and_then(|t| t.stack.last().copied()).ok_or_else(|| EngineError::Other("the smart material file has no layer".into()))?;
let resources: BTreeMap<String, Arc<Vec<u8>>> = pf.resources.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
let src = Document { project: pf.project, pixels: pf.pixels, baked: BTreeMap::new(), resources: resources.clone() };
let id = self.edit("Add smart material", |s| {
for (k, v) in &resources {
s.doc.resources.entry(k.clone()).or_insert_with(|| v.clone());
}
let ts = s.ts();
let sel = s.selected_layer();
let inside = sel.and_then(|l| s.doc.project.layer(l).ok()).is_some_and(|l| l.is_group());
let id = crate::layer_ops::copy_tree(&src, root, &mut s.doc, ts, sel, inside, 0)?;
s.selected.insert(ts, id);
s.target = StackTarget::Content;
Ok(id)
})?;
self.sync_images();
Ok(id)
}
}
#[cfg(not(target_arch = "wasm32"))]
use crate::commands::{bad, layer_param, strp};
#[cfg(not(target_arch = "wasm32"))]
use serde_json::json;
#[cfg(not(target_arch = "wasm32"))]
fn save(s: &mut Session, p: &Value) -> Result<Value> {
let id = layer_param(s, "material.save", p)?;
let path = strp(p, "path").ok_or_else(|| bad("material.save", "`path` is required"))?;
let name = strp(p, "name").map(str::to_string).unwrap_or_else(|| s.doc.project.layer(id).map(|l| l.name.clone()).unwrap_or_default());
let bytes = s.smart_material_bytes(id, &name)?;
let path = if path.ends_with(&format!(".{SMART_MATERIAL_EXT}")) { path.to_string() } else { format!("{path}.{SMART_MATERIAL_EXT}") };
if let Some(dir) = std::path::Path::new(&path).parent().filter(|d| !d.as_os_str().is_empty()) {
std::fs::create_dir_all(dir).map_err(|e| bad("material.save", format!("cannot create {}: {e}", dir.display())))?;
}
let tmp = format!("{path}.tmp");
std::fs::write(&tmp, bytes).and_then(|_| std::fs::rename(&tmp, &path)).map_err(|e| bad("material.save", format!("cannot write {path}: {e}")))?;
Ok(json!({ "path": path }))
}
#[cfg(not(target_arch = "wasm32"))]
fn load(s: &mut Session, p: &Value) -> Result<Value> {
let path = strp(p, "path").ok_or_else(|| bad("material.load", "`path` is required"))?;
let bytes = std::fs::read(path).map_err(|e| bad("material.load", format!("cannot read {path}: {e}")))?;
let id = s.add_smart_material_bytes(&bytes)?;
Ok(json!({ "layer": id.0 }))
}
#[cfg(target_arch = "wasm32")]
fn save(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
#[cfg(target_arch = "wasm32")]
fn load(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Other("file paths are not available in the browser".into()))
}
+579
View File
@@ -0,0 +1,579 @@
//! Built-in materials and smart materials: fill layers (and folders of fill layers with
//! mesh-map-driven masks), all procedural (no bitmap assets), so they are original to
//! TextureCraft and work at any resolution.
//!
//! Values follow physically based conventions: metals are metallic 1 with base colors from
//! published measured reflectance (F0) tables; dielectrics are metallic 0 with linear albedo
//! between about 0.02 (charcoal, rubber) and 0.9 (fresh snow).
use texturecraft_core::{
BlendMode, Channel, ChannelBlend, EffectKind, Fill, GeneratorKind, Layer, LayerId, LayerKind, MaskBackground, Procedural, ProceduralKind, Project,
Projection, Source,
};
use crate::smart_masks::{build_mask, directional, generator, pattern};
use crate::{EngineError, Result, Session};
/// One material in the shelf: id, label, category, and a representative color/metal/roughness.
pub struct SmartMaterial {
pub id: &'static str,
pub label: &'static str,
/// Shelf group ("Metal", "Wood", …).
pub category: &'static str,
pub base: [f32; 3],
pub metallic: f32,
pub roughness: f32,
/// True for multi-layer "smart" materials (worn, dirty…), false for simple materials.
pub smart: bool,
}
const fn m(id: &'static str, label: &'static str, category: &'static str, base: [f32; 3], metallic: f32, roughness: f32) -> SmartMaterial {
SmartMaterial { id, label, category, base, metallic, roughness, smart: false }
}
const fn sm(id: &'static str, label: &'static str, category: &'static str, base: [f32; 3], metallic: f32, roughness: f32) -> SmartMaterial {
SmartMaterial { id, label, category, base, metallic, roughness, smart: true }
}
const METAL: &str = "Metal";
const WOOD: &str = "Wood";
const STONE: &str = "Stone & Masonry";
const PLASTIC: &str = "Plastic & Rubber";
const FABRIC: &str = "Fabric & Leather";
const GLASS: &str = "Ceramic & Glass";
pub const MATERIALS: &[SmartMaterial] = &[
// Metals (base color = measured F0, linear).
m("steel", "Steel", METAL, [0.56, 0.57, 0.58], 1.0, 0.34),
m("steel_stainless", "Steel Stainless", METAL, [0.65, 0.64, 0.62], 1.0, 0.24),
m("steel_dark", "Steel Dark", METAL, [0.48, 0.48, 0.5], 1.0, 0.3),
m("iron", "Iron Raw", METAL, [0.53, 0.53, 0.54], 1.0, 0.5),
m("cast_iron", "Cast Iron", METAL, [0.48, 0.48, 0.48], 1.0, 0.65),
m("copper", "Copper", METAL, [0.955, 0.638, 0.538], 1.0, 0.26),
m("copper_hammered", "Copper Hammered", METAL, [0.92, 0.6, 0.5], 1.0, 0.3),
m("brass", "Brass", METAL, [0.91, 0.778, 0.423], 1.0, 0.27),
m("bronze", "Bronze", METAL, [0.8, 0.56, 0.32], 1.0, 0.36),
m("gold_polished", "Gold Polished", METAL, [1.0, 0.766, 0.336], 1.0, 0.17),
m("silver", "Silver", METAL, [0.972, 0.96, 0.915], 1.0, 0.22),
m("aluminium", "Aluminium Raw", METAL, [0.913, 0.922, 0.924], 1.0, 0.42),
m("aluminium_brushed", "Aluminium Brushed", METAL, [0.913, 0.922, 0.924], 1.0, 0.32),
m("chrome", "Chrome", METAL, [0.55, 0.556, 0.554], 1.0, 0.05),
m("titanium", "Titanium", METAL, [0.542, 0.497, 0.449], 1.0, 0.32),
m("nickel", "Nickel", METAL, [0.66, 0.609, 0.526], 1.0, 0.25),
m("galvanized", "Steel Galvanized", METAL, [0.69, 0.71, 0.72], 1.0, 0.4),
// Woods.
m("wood", "Wood Varnished", WOOD, [0.29, 0.15, 0.06], 0.0, 0.26),
m("wood_oak", "Oak", WOOD, [0.33, 0.2, 0.09], 0.0, 0.62),
m("wood_walnut", "Walnut", WOOD, [0.12, 0.06, 0.03], 0.0, 0.5),
m("wood_pine", "Pine", WOOD, [0.52, 0.33, 0.16], 0.0, 0.65),
m("plywood", "Plywood", WOOD, [0.55, 0.38, 0.21], 0.0, 0.75),
m("wood_painted", "Wood Painted", WOOD, [0.61, 0.59, 0.54], 0.0, 0.48),
// Stone, masonry and earth.
m("concrete", "Concrete", STONE, [0.27, 0.26, 0.25], 0.0, 0.9),
m("brick", "Brick Red", STONE, [0.3, 0.075, 0.04], 0.0, 0.85),
m("tiles_ceramic", "Tiles Ceramic", STONE, [0.8, 0.8, 0.78], 0.0, 0.1),
m("marble", "Marble", STONE, [0.78, 0.78, 0.76], 0.0, 0.14),
m("marble_black", "Marble Black", STONE, [0.03, 0.03, 0.032], 0.0, 0.1),
m("granite", "Granite", STONE, [0.3, 0.27, 0.25], 0.0, 0.3),
m("asphalt", "Asphalt", STONE, [0.06, 0.06, 0.058], 0.0, 0.9),
m("clay", "Clay Earthenware", STONE, [0.45, 0.18, 0.09], 0.0, 0.8),
// Plastics, rubber, composites.
m("plastic_glossy", "Plastic Glossy", PLASTIC, [0.8, 0.12, 0.08], 0.0, 0.16),
m("plastic_matte", "Plastic Matte", PLASTIC, [0.18, 0.18, 0.19], 0.0, 0.6),
m("plastic_textured", "Plastic Textured", PLASTIC, [0.035, 0.035, 0.04], 0.0, 0.55),
m("rubber", "Rubber", PLASTIC, [0.03, 0.03, 0.03], 0.0, 0.88),
m("carbon_fiber", "Carbon Fiber", PLASTIC, [0.035, 0.035, 0.04], 0.0, 0.15),
// Fabric and leather.
m("fabric", "Fabric Cotton", FABRIC, [0.45, 0.47, 0.54], 0.0, 0.95),
m("denim", "Denim", FABRIC, [0.06, 0.09, 0.19], 0.0, 0.92),
m("leather", "Leather", FABRIC, [0.17, 0.08, 0.04], 0.0, 0.52),
m("leather_black", "Leather Black", FABRIC, [0.025, 0.025, 0.028], 0.0, 0.42),
// Ceramic and glass.
m("ceramic", "Ceramic White", GLASS, [0.8, 0.8, 0.78], 0.0, 0.08),
m("glass", "Glass Clear", GLASS, [0.02, 0.022, 0.022], 0.0, 0.03),
m("glass_frosted", "Glass Frosted", GLASS, [0.6, 0.64, 0.64], 0.0, 0.45),
// Smart materials.
sm("steel_painted_worn", "Steel Painted Worn", METAL, [0.42, 0.06, 0.04], 0.2, 0.45),
sm("steel_painted_rust", "Steel Painted Rust Leaks", METAL, [0.62, 0.62, 0.6], 0.1, 0.5),
sm("military_paint", "Military Paint", METAL, [0.07, 0.08, 0.035], 0.1, 0.6),
sm("iron_rusted", "Iron Rusted", METAL, [0.38, 0.14, 0.05], 0.3, 0.8),
sm("aluminium_scratched", "Aluminium Scratched", METAL, [0.913, 0.922, 0.924], 1.0, 0.3),
sm("copper_patina", "Copper Oxidized", METAL, [0.6, 0.45, 0.35], 0.6, 0.5),
sm("bronze_statue", "Bronze Statue", METAL, [0.35, 0.4, 0.3], 0.5, 0.6),
sm("brass_tarnished", "Brass Tarnished", METAL, [0.7, 0.58, 0.3], 0.8, 0.4),
sm("gold_dirty", "Gold Dirty", METAL, [0.9, 0.68, 0.3], 0.9, 0.3),
sm("chrome_smudged", "Chrome Smudged", METAL, [0.55, 0.556, 0.554], 1.0, 0.12),
sm("wood_weathered", "Wood Weathered", WOOD, [0.33, 0.3, 0.27], 0.0, 0.8),
sm("wood_chipped_paint", "Wood Chipped Paint", WOOD, [0.04, 0.22, 0.22], 0.0, 0.55),
sm("concrete_dirty", "Concrete Dirty", STONE, [0.28, 0.26, 0.23], 0.0, 0.92),
sm("brick_mossy", "Brick Mossy", STONE, [0.22, 0.12, 0.05], 0.0, 0.9),
sm("plastic_dusty", "Plastic Dusty", PLASTIC, [0.05, 0.2, 0.45], 0.0, 0.4),
sm("plastic_scuffed", "Plastic Scuffed", PLASTIC, [0.06, 0.06, 0.065], 0.0, 0.5),
sm("leather_worn", "Leather Worn", FABRIC, [0.22, 0.12, 0.07], 0.0, 0.5),
];
fn norm(x: &str) -> String {
x.to_ascii_lowercase().replace([' ', '_', '-'], "")
}
pub fn find(id: &str) -> Option<&'static SmartMaterial> {
MATERIALS.iter().find(|m| norm(m.id) == norm(id) || norm(m.label) == norm(id))
}
fn u(v: f32) -> Source {
Source::Uniform([v; 3])
}
fn rgb(c: [f32; 3]) -> Source {
Source::Uniform(c)
}
fn pat(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32, low: [f32; 3], high: [f32; 3]) -> Source {
Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low, high }
}
/// A scalar pattern between `lo` and `hi`.
fn gray(kind: ProceduralKind, scale: f32, seed: u32, lo: f32, hi: f32) -> Source {
pat(kind, scale, seed, 1.0, [lo; 3], [hi; 3])
}
type Sources = Vec<(Channel, Source)>;
fn surface(base: Source, metallic: f32, rough: Source) -> Sources {
vec![(Channel::BaseColor, base), (Channel::Metallic, u(metallic)), (Channel::Roughness, rough)]
}
fn metal(base: Source, rough: Source) -> Sources {
surface(base, 1.0, rough)
}
fn dielectric(base: Source, rough: Source) -> Sources {
surface(base, 0.0, rough)
}
/// `sources` plus `extra` channels (height, opacity…).
fn plus(mut sources: Sources, extra: impl IntoIterator<Item = (Channel, Source)>) -> Sources {
sources.extend(extra);
sources
}
fn height(s: Source) -> [(Channel, Source); 1] {
[(Channel::Height, s)]
}
pub(crate) struct Builder<'a> {
pub p: &'a mut Project,
/// Channels of the target texture set; layers only enable these.
pub channels: Vec<Channel>,
}
impl Builder<'_> {
fn fill(&mut self, name: &str, sources: Sources) -> Layer {
let id = self.p.alloc_id();
let enabled: Vec<Channel> = sources.iter().map(|(c, _)| *c).filter(|c| self.channels.contains(c)).collect();
let projection = Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] };
Layer::new(id, name, LayerKind::Fill(Fill { sources: sources.into_iter().collect(), projection }), &enabled)
}
/// A fill masked by smart mask preset `mask` (inverted: present where the preset is not).
fn preset(&mut self, name: &str, sources: Sources, mask: &str, invert: bool) -> Result<Layer> {
let mut l = self.fill(name, sources);
l.mask = Some(crate::smart_masks::mask(self.p, mask, invert)?);
Ok(l)
}
/// A fill with a custom black-background mask.
fn masked(&mut self, name: &str, sources: Sources, effects: Vec<(EffectKind, BlendMode)>) -> Layer {
let mut l = self.fill(name, sources);
l.mask = Some(build_mask(self.p, MaskBackground::Black, effects));
l
}
/// The common grime layer: dark dirt settled in cavities.
fn dirt(&mut self, color: [f32; 3]) -> Result<Layer> {
self.preset("Dirt", dielectric(rgb(color), u(0.9)), "dirt_cavities", false)
}
}
/// Layers (bottom → top) making up material `id`.
pub(crate) fn build(b: &mut Builder, id: &str) -> Result<Vec<Layer>> {
use BlendMode::{Lighten, Multiply, Normal};
use Channel::*;
use GeneratorKind as G;
use ProceduralKind as P;
let m = find(id).ok_or_else(|| EngineError::Other(format!("unknown material `{id}`")))?;
let one = |b: &mut Builder, s: Sources| -> Result<Vec<Layer>> { Ok(vec![b.fill(m.label, s)]) };
// A simple metal: subtle cloudy tone and roughness variation around the table values.
let plain_metal = |b: &mut Builder, rough: Source| {
let lo = m.base.map(|v| v * 0.94);
one(b, metal(pat(P::Clouds, 3.0, 5, 1.0, lo, m.base), rough))
};
let r = m.roughness;
let clouds_rough = |seed: u32| gray(P::Clouds, 6.0, seed, r * 0.85, (r * 1.2).min(1.0));
match m.id {
// ---- Metals -------------------------------------------------------------------------
"steel" | "steel_dark" | "iron" | "copper" | "brass" | "bronze" | "gold_polished" | "silver" | "aluminium" | "chrome" | "nickel" => {
plain_metal(b, clouds_rough(7))
}
"steel_stainless" | "aluminium_brushed" | "titanium" => plain_metal(b, gray(P::Brushed, 3.0, 3, r * 0.75, r * 1.25)),
"cast_iron" => one(
b,
plus(metal(pat(P::Noise, 1.0, 4, 1.0, [0.44; 3], [0.52; 3]), gray(P::Grunge, 3.0, 9, 0.55, 0.75)), height(gray(P::Pores, 14.0, 3, -0.02, 0.0))),
),
"copper_hammered" => one(
b,
plus(
metal(pat(P::Hammered, 6.0, 1, 1.0, [0.86, 0.55, 0.45], [0.955, 0.638, 0.538]), gray(P::Hammered, 6.0, 1, 0.38, 0.24)),
height(gray(P::Hammered, 6.0, 1, -0.04, 0.0)),
),
),
"galvanized" => one(b, metal(pat(P::Voronoi, 10.0, 4, 1.0, [0.6, 0.62, 0.63], [0.78, 0.8, 0.81]), gray(P::Voronoi, 10.0, 4, 0.5, 0.28))),
// ---- Woods (grain along X, rings across Y) ---------------------------------------------
"wood" => one(
b,
plus(dielectric(pat(P::Wood, 2.0, 7, 1.0, [0.12, 0.05, 0.018], [0.42, 0.22, 0.09]), clouds_rough(3)), height(gray(P::Wood, 2.0, 7, -0.004, 0.0))),
),
"wood_oak" => one(
b,
plus(
dielectric(pat(P::Wood, 2.0, 7, 1.0, [0.2, 0.11, 0.045], [0.46, 0.29, 0.14]), gray(P::Wood, 2.0, 7, 0.74, 0.56)),
height(gray(P::Wood, 2.0, 7, -0.012, 0.0)),
),
),
"wood_walnut" => one(
b,
plus(
dielectric(pat(P::Wood, 2.5, 21, 1.0, [0.05, 0.025, 0.012], [0.2, 0.1, 0.05]), gray(P::Wood, 2.5, 21, 0.56, 0.46)),
height(gray(P::Wood, 2.5, 21, -0.008, 0.0)),
),
),
"wood_pine" => one(
b,
plus(
dielectric(pat(P::Wood, 1.5, 4, 1.0, [0.33, 0.17, 0.065], [0.7, 0.48, 0.25]), gray(P::Wood, 1.5, 4, 0.72, 0.62)),
height(gray(P::Wood, 1.5, 4, -0.012, 0.0)),
),
),
"plywood" => one(b, dielectric(pat(P::Wood, 1.2, 15, 0.6, [0.42, 0.27, 0.13], [0.66, 0.47, 0.27]), gray(P::Wood, 1.2, 15, 0.8, 0.7))),
"wood_painted" => one(
b,
plus(
dielectric(pat(P::Clouds, 3.0, 4, 1.0, [0.57, 0.55, 0.5], [0.64, 0.62, 0.57]), gray(P::Wood, 2.0, 7, 0.56, 0.42)),
height(gray(P::Wood, 2.0, 7, -0.015, 0.0)),
),
),
// ---- Stone, masonry, earth ----------------------------------------------------------
"concrete" => one(
b,
plus(
dielectric(pat(P::Clouds, 6.0, 4, 1.3, [0.2, 0.19, 0.18], [0.35, 0.34, 0.32]), gray(P::Noise, 1.0, 6, 0.85, 0.95)),
height(gray(P::Pores, 14.0, 6, -0.03, 0.0)),
),
),
"brick" => one(
b,
plus(
dielectric(pat(P::Bricks, 3.0, 4, 1.0, [0.27, 0.26, 0.24], [0.3, 0.075, 0.04]), gray(P::Bricks, 3.0, 4, 0.95, 0.82)),
height(gray(P::Bricks, 3.0, 4, -0.04, 0.0)),
),
),
"tiles_ceramic" => one(
b,
plus(
dielectric(pat(P::Tiles, 4.0, 2, 1.0, [0.33, 0.32, 0.3], [0.82, 0.82, 0.8]), gray(P::Tiles, 4.0, 2, 0.85, 0.08)),
height(gray(P::Tiles, 4.0, 2, -0.03, 0.0)),
),
),
"marble" => one(b, dielectric(pat(P::Marble, 2.0, 12, 1.0, [0.38, 0.38, 0.37], [0.86, 0.86, 0.84]), clouds_rough(12))),
"marble_black" => one(b, dielectric(pat(P::Marble, 2.0, 5, 1.0, [0.55, 0.55, 0.53], [0.015, 0.015, 0.017]), clouds_rough(5))),
"granite" => one(b, dielectric(pat(P::Voronoi, 70.0, 8, 1.0, [0.1, 0.095, 0.09], [0.5, 0.47, 0.45]), gray(P::Voronoi, 70.0, 8, 0.25, 0.35))),
"asphalt" => one(
b,
plus(
dielectric(pat(P::Voronoi, 90.0, 3, 1.0, [0.025; 3], [0.11, 0.105, 0.1]), gray(P::Voronoi, 90.0, 3, 0.95, 0.75)),
height(gray(P::Pores, 10.0, 5, -0.02, 0.0)),
),
),
"clay" => one(
b,
plus(dielectric(pat(P::Clouds, 5.0, 2, 1.0, [0.4, 0.15, 0.07], [0.5, 0.21, 0.11]), clouds_rough(2)), height(gray(P::Noise, 0.8, 3, -0.005, 0.005))),
),
// ---- Plastics, rubber, composites ---------------------------------------------------
"plastic_glossy" | "plastic_matte" | "ceramic" => one(b, dielectric(rgb(m.base), clouds_rough(9))),
"plastic_textured" => one(b, plus(dielectric(rgb(m.base), gray(P::Leather, 40.0, 5, 0.66, 0.5)), height(gray(P::Leather, 40.0, 5, -0.01, 0.0)))),
"rubber" => one(b, dielectric(pat(P::Noise, 0.5, 3, 1.0, [0.025; 3], [0.035; 3]), gray(P::Noise, 0.5, 3, 0.84, 0.94))),
"carbon_fiber" => {
one(b, plus(dielectric(pat(P::Weave, 24.0, 1, 1.0, [0.01, 0.01, 0.012], [0.06, 0.06, 0.065]), u(r)), height(gray(P::Weave, 24.0, 1, 0.0, 0.006))))
}
// ---- Fabric and leather -------------------------------------------------------------
"fabric" => {
one(b, plus(dielectric(pat(P::Weave, 18.0, 2, 1.0, [0.27, 0.29, 0.34], [0.6, 0.62, 0.7]), u(r)), height(gray(P::Weave, 18.0, 2, -0.01, 0.0))))
}
"denim" => {
one(b, plus(dielectric(pat(P::Weave, 22.0, 5, 1.0, [0.02, 0.03, 0.08], [0.12, 0.16, 0.3]), u(r)), height(gray(P::Weave, 22.0, 5, -0.01, 0.0))))
}
"leather" => one(
b,
plus(
dielectric(pat(P::Leather, 42.0, 2, 1.0, [0.07, 0.03, 0.013], [0.25, 0.12, 0.06]), gray(P::Leather, 42.0, 2, 0.62, 0.46)),
height(gray(P::Leather, 42.0, 2, -0.02, 0.0)),
),
),
"leather_black" => one(
b,
plus(
dielectric(pat(P::Leather, 42.0, 6, 1.0, [0.01; 3], [0.04, 0.04, 0.045]), gray(P::Leather, 42.0, 6, 0.52, 0.36)),
height(gray(P::Leather, 42.0, 6, -0.02, 0.0)),
),
),
// ---- Glass (opaque approximation; uses Opacity when the texture set has it) ------------
"glass" => one(b, plus(dielectric(rgb(m.base), u(r)), [(Opacity, u(0.2))])),
"glass_frosted" => one(b, plus(dielectric(rgb(m.base), gray(P::Noise, 1.0, 2, 0.4, 0.5)), [(Opacity, u(0.6))])),
// ---- Smart materials ----------------------------------------------------------------
"steel_painted_worn" => {
let mut v = build(b, "steel")?;
v.push(b.preset("Paint", plus(dielectric(rgb(m.base), gray(P::Clouds, 3.0, 9, 0.38, 0.55)), height(u(0.004))), "edge_chipped", true)?);
v.push(b.dirt([0.12, 0.09, 0.06])?);
Ok(v)
}
"steel_painted_rust" => {
let mut v = build(b, "steel")?;
v.push(b.preset(
"Paint",
plus(dielectric(pat(P::Clouds, 4.0, 3, 1.0, [0.58, 0.58, 0.56], [0.66, 0.66, 0.64]), u(0.45)), height(u(0.004))),
"edge_wear",
true,
)?);
v.push(b.preset("Rust leaks", dielectric(pat(P::Grunge, 4.0, 2, 1.0, [0.1, 0.03, 0.01], [0.24, 0.08, 0.025]), u(0.85)), "rust_leaks", false)?);
Ok(v)
}
"military_paint" => {
let mut v = build(b, "steel_dark")?;
v.push(b.preset(
"Olive drab",
plus(dielectric(pat(P::Clouds, 3.0, 6, 1.0, [0.06, 0.07, 0.03], [0.085, 0.095, 0.042]), u(0.62)), height(u(0.004))),
"edge_chipped",
true,
)?);
v.push(b.dirt([0.06, 0.05, 0.035])?);
v.push(b.preset("Dust", dielectric(rgb([0.36, 0.31, 0.23]), u(0.95)), "dust_top", false)?);
Ok(v)
}
"iron_rusted" => {
let mut v = build(b, "cast_iron")?;
let rust =
plus(dielectric(pat(P::Grunge, 5.0, 3, 0.8, [0.045, 0.018, 0.008], [0.14, 0.05, 0.018]), u(0.88)), height(gray(P::Noise, 1.0, 1, 0.0, 0.04)));
v.push(b.masked("Rust", rust, vec![(pattern(P::Grunge, 2.0, 8, 1.2), Normal), (generator(G::Dirt, 0.5, 0.25, 0.3), Lighten)]));
v.push(b.preset("Rust leaks", dielectric(rgb([0.11, 0.04, 0.014]), u(0.8)), "rust_leaks", false)?);
Ok(v)
}
"aluminium_scratched" => {
let mut v = build(b, "aluminium_brushed")?;
v.push(b.preset("Polished edges", metal(rgb([0.95, 0.95, 0.95]), u(0.14)), "edge_wear", false)?);
v.push(b.preset("Scratches", plus(metal(rgb([0.95, 0.95, 0.95]), u(0.12)), height(u(-0.006))), "scratches", false)?);
Ok(v)
}
"copper_patina" => {
let mut v = build(b, "copper")?;
v.push(b.preset("Tarnish", dielectric(pat(P::Clouds, 4.0, 2, 1.0, [0.18, 0.07, 0.04], [0.3, 0.13, 0.07]), u(0.6)), "grunge", false)?);
let patina = plus(dielectric(pat(P::Clouds, 4.0, 11, 1.4, [0.15, 0.38, 0.32], [0.33, 0.6, 0.5]), u(0.85)), height(u(0.02)));
v.push(b.masked("Patina", patina, vec![(generator(G::Dirt, 0.65, 0.25, 0.6), Normal), (pattern(P::Streaks, 3.0, 9, 1.0), Lighten)]));
Ok(v)
}
"bronze_statue" => {
let mut v = build(b, "bronze")?;
v.push(b.preset("Dark oxide", dielectric(pat(P::Clouds, 4.0, 5, 1.0, [0.05, 0.035, 0.02], [0.12, 0.08, 0.04]), u(0.6)), "grunge", false)?);
v.push(b.preset(
"Verdigris",
plus(dielectric(pat(P::Clouds, 5.0, 8, 1.3, [0.1, 0.3, 0.24], [0.25, 0.5, 0.42]), u(0.88)), height(u(0.015))),
"rust_leaks",
false,
)?);
Ok(v)
}
"brass_tarnished" => {
let mut v = build(b, "brass")?;
v.push(b.masked(
"Tarnish",
dielectric(pat(P::Clouds, 4.0, 4, 1.0, [0.08, 0.06, 0.025], [0.16, 0.12, 0.05]), u(0.7)),
vec![(generator(G::Dirt, 0.6, 0.25, 0.5), Normal), (pattern(P::Grunge, 2.5, 3, 0.9), Lighten)],
));
v.push(b.preset("Fingerprints", metal(rgb([0.8, 0.68, 0.37]), u(0.45)), "fingerprints", false)?);
Ok(v)
}
"gold_dirty" => {
let mut v = build(b, "gold_polished")?;
v.push(b.preset("Smudges", metal(rgb([0.85, 0.64, 0.28]), u(0.4)), "fingerprints", false)?);
v.push(b.dirt([0.06, 0.045, 0.03])?);
Ok(v)
}
"chrome_smudged" => {
let mut v = build(b, "chrome")?;
v.push(b.preset("Smudges", metal(rgb([0.5, 0.505, 0.5]), u(0.3)), "fingerprints", false)?);
v.push(b.preset("Dust", dielectric(rgb([0.5, 0.48, 0.45]), u(0.9)), "dust_top", false)?);
Ok(v)
}
"wood_weathered" => {
let mut v = build(b, "wood_pine")?;
let gray_wood =
plus(dielectric(pat(P::Wood, 1.5, 4, 1.0, [0.17, 0.16, 0.14], [0.42, 0.4, 0.37]), u(0.85)), height(gray(P::Wood, 1.5, 4, -0.03, 0.0)));
v.push(b.masked(
"Weathered",
gray_wood,
vec![(pattern(P::Grunge, 2.0, 15, 0.8), Normal), (directional(G::Direction, [0.0, 1.0, 0.0], 0.45, 0.2, 0.4, false), Lighten)],
));
v.push(b.dirt([0.05, 0.04, 0.03])?);
Ok(v)
}
"wood_chipped_paint" => {
let mut v = build(b, "wood_oak")?;
v.push(b.preset(
"Paint",
plus(dielectric(pat(P::Clouds, 3.0, 2, 1.0, [0.035, 0.19, 0.19], [0.05, 0.25, 0.25]), u(0.55)), height(u(0.01))),
"paint_chips",
true,
)?);
v.push(b.dirt([0.05, 0.04, 0.03])?);
Ok(v)
}
"concrete_dirty" => {
let mut v = build(b, "concrete")?;
v.push(b.preset("Water stains", dielectric(rgb([0.13, 0.13, 0.12]), u(0.9)), "rust_leaks", false)?);
v.push(b.dirt([0.08, 0.065, 0.05])?);
v.push(b.preset("Ground mud", dielectric(rgb([0.12, 0.09, 0.06]), u(0.95)), "ground_dirt", false)?);
Ok(v)
}
"brick_mossy" => {
let mut v = build(b, "brick")?;
v.push(b.preset("Grime", dielectric(rgb([0.07, 0.06, 0.05]), u(0.95)), "ground_dirt", false)?);
let moss = plus(dielectric(pat(P::Noise, 1.0, 7, 1.0, [0.02, 0.035, 0.008], [0.05, 0.075, 0.015]), u(0.95)), height(u(0.02)));
v.push(b.masked(
"Moss",
moss,
vec![
(directional(G::Direction, [0.0, 1.0, 0.0], 0.45, 0.15, 0.3, false), Normal),
(pattern(P::Grunge, 2.0, 5, 1.0), Multiply),
(generator(G::Dirt, 0.4, 0.2, 0.5), Lighten),
],
));
Ok(v)
}
"plastic_dusty" => {
let mut v = one(b, dielectric(rgb(m.base), u(0.35)))?;
v.push(b.preset("Dust", dielectric(rgb([0.5, 0.46, 0.4]), u(0.95)), "dust_top", false)?);
v.push(b.dirt([0.1, 0.09, 0.08])?);
Ok(v)
}
"plastic_scuffed" => {
let mut v = one(b, dielectric(rgb(m.base), gray(P::Leather, 40.0, 5, 0.45, 0.35)))?;
v.push(b.preset("Scuffed edges", dielectric(rgb([0.2, 0.2, 0.21]), u(0.7)), "edge_wear", false)?);
v.push(b.preset("Scratches", dielectric(rgb([0.14, 0.14, 0.15]), u(0.6)), "scratches", false)?);
Ok(v)
}
"leather_worn" => {
let mut v = build(b, "leather")?;
v.push(b.preset("Worn", dielectric(rgb([0.3, 0.18, 0.1]), u(0.36)), "edge_wear", false)?);
v.push(b.dirt([0.035, 0.022, 0.014])?);
Ok(v)
}
other => Err(EngineError::Other(format!("material `{other}` has no definition"))),
}
}
/// Add material `id` above the selection: a single fill layer, or a folder for multi-layer
/// materials. Returns the new top-level layer id.
pub fn apply(s: &mut Session, id: &str) -> Result<LayerId> {
let m = find(id).ok_or_else(|| EngineError::Other(format!("unknown material `{id}`")))?;
let label = format!("Add {}", m.label);
s.edit(&label, |s| {
let channels = s.doc.project.texture_set(s.ts())?.channel_list();
let layers = build(&mut Builder { p: &mut s.doc.project, channels: channels.clone() }, m.id)?;
if layers.len() == 1 {
let l = layers.into_iter().next().ok_or_else(|| EngineError::Other("empty material".into()))?;
return crate::layer_cmds::insert_selected(s, l);
}
let gid = s.doc.project.alloc_id();
let mut group = Layer::new(gid, m.label, LayerKind::Group { children: Vec::new(), collapsed: false }, &channels);
for c in group.channels.values_mut() {
*c = ChannelBlend { mode: BlendMode::Passthrough, opacity: 1.0 };
}
let gid = crate::layer_cmds::insert_selected(s, group)?;
let ts = s.ts();
for l in layers {
s.doc.project.insert_layer(ts, l, Some(gid), true)?;
}
s.selected.insert(ts, gid);
Ok(gid)
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_and_labels_are_unique_and_values_physical() {
let (mut ids, mut labels) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
for m in MATERIALS {
assert!(ids.insert(norm(m.id)), "duplicate id {}", m.id);
assert!(labels.insert(norm(m.label)), "duplicate label {}", m.label);
assert_eq!(find(m.label).map(|f| f.id), Some(m.id));
if !m.smart {
// Metals: measured F0 is at least ~0.45 in some channel; dielectrics: 0.01..0.9.
let hi = m.base.iter().copied().fold(0.0, f32::max);
if m.metallic == 1.0 {
assert!(hi >= 0.45, "{} too dark for a metal", m.id);
} else {
assert_eq!(m.metallic, 0.0, "{} must be metal or dielectric", m.id);
assert!(m.base.iter().all(|v| (0.01..=0.9).contains(v)), "{} albedo out of range", m.id);
}
}
}
assert!(MATERIALS.iter().filter(|m| !m.smart).count() >= 40);
assert!(MATERIALS.iter().filter(|m| m.smart).count() >= 15);
assert!(find("Gold Polished").is_some());
assert!(find("nope").is_none());
}
/// Base color, roughness and metallic at a grid of texels of texture set `ts`.
fn snapshot(s: &Session, ts: usize) -> Vec<[f32; 3]> {
let c = &s.caches[ts].composite;
let n = c.resolution;
(0..n)
.step_by(3)
.flat_map(|y| (0..n).step_by(3).map(move |x| (x, y)))
.flat_map(|(x, y)| [Channel::BaseColor, Channel::Roughness, Channel::Metallic].map(|ch| c.value(ch, x, y)))
.collect()
}
#[test]
fn every_material_and_smart_mask_applies_on_the_sample() {
let mut s = crate::sample_session(256, 256).unwrap();
// A baseline no material matches, so every material must visibly change the composite.
crate::execute(&mut s, "layer.add.fill", &serde_json::json!({"color": [1.0, 0.0, 1.0], "roughness": 0.123})).unwrap();
s.update();
let before = snapshot(&s, 0);
for m in MATERIALS {
apply(&mut s, m.id).unwrap_or_else(|e| panic!("{}: {e}", m.id));
s.doc.project.validate().unwrap();
s.update();
let after = snapshot(&s, 0);
assert!(after.iter().flatten().all(|v| v.is_finite() && (-1.0..=1.0).contains(v)), "{} produced invalid values", m.id);
assert_ne!(after, before, "{} changed nothing", m.id);
s.undo().unwrap();
}
assert!(apply(&mut s, "nope").is_err());
// Smart masks on the pedestal: it has edges and cavities (the ball is a plain sphere).
s.active_set = 1;
apply(&mut s, "gold_polished").unwrap();
let layer = s.selected_layer().unwrap();
for sm in crate::smart_masks::SMART_MASKS {
crate::smart_masks::apply(&mut s, layer, sm.id).unwrap();
s.update();
let view = s.mask_view_rgba(layer, 64).unwrap();
assert!(view.chunks(4).any(|px| px[0] > 0), "{} is empty", sm.id);
assert!(snapshot(&s, 1).iter().flatten().all(|v| v.is_finite()), "{}", sm.id);
}
assert!(crate::smart_masks::apply(&mut s, layer, "nope").is_err());
}
}
+511
View File
@@ -0,0 +1,511 @@
//! Interactive painting on the session: strokes (begin / continue / end / cancel), polygon fill
//! and the color picker. The UI, CLI and agents all go through these.
use std::collections::{BTreeMap, BTreeSet};
use texturecraft_compose::PaintTarget;
use texturecraft_core::{Channel, Effect, EffectKind, LayerId, LayerKind, Mask, MaskBackground};
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{
CommitSource, EyeDepth, PickCtx, Pickup, PickupMode, RasterCtx, Shape, Stroke, StrokeCanvas, SurfaceHit, commit_layer, commit_mask, fill_triangles, pick,
rasterize,
};
use crate::session::{ActiveStroke, FillMode, Session, StackTarget, Tool};
use crate::{EngineError, Result};
impl Session {
pub fn pick(&self, screen: Vec2, viewport: Vec2) -> Option<SurfaceHit> {
let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &self.camera, viewport };
pick(&ctx, screen)
}
/// Resolve what a stroke on the selected layer paints into, creating the mask paint effect
/// when painting a mask. Must run inside the stroke's history snapshot.
fn paint_target(&mut self) -> Result<PaintTarget> {
let id = self.selected_layer().ok_or_else(|| EngineError::Other("select a layer to paint on".into()))?;
// Painting an instance paints its source (its own mask when it overrides the mask).
let p = &self.doc.project;
let id = if self.target == StackTarget::Mask { p.mask_owner(id) } else { p.content_layer(id).map_or(id, |l| l.id) };
match self.target {
StackTarget::Content => {
let l = self.doc.project.layer(id)?;
if matches!(l.kind, LayerKind::Paint) {
Ok(PaintTarget::Layer(id))
} else {
Err(EngineError::Other(format!("\"{}\" is a {} layer: paint on a paint layer or on its mask", l.name, l.kind.name())))
}
}
StackTarget::Effect(e) => match self.doc.project.effect(e) {
// Content paint effects hold channel pixels like a paint layer.
Some((owner, eff)) if matches!(eff.kind, EffectKind::Paint) => {
let content = self.doc.project.layer(owner)?.content_effects.iter().any(|x| x.id == e);
Ok(if content { PaintTarget::Layer(e) } else { PaintTarget::Mask(e) })
}
_ => Err(EngineError::Other("the selected effect is not a paint effect".into())),
},
StackTarget::Mask => {
let eid = self.doc.project.alloc_id();
let layer = self.doc.project.layer_mut(id)?;
let mask = layer.mask.get_or_insert_with(|| Mask::new(MaskBackground::Black));
if let Some(top) = mask.effects.last().filter(|e| matches!(e.kind, EffectKind::Paint)) {
return Ok(PaintTarget::Mask(top.id));
}
mask.effects.push(Effect::new(eid, EffectKind::Paint));
Ok(PaintTarget::Mask(eid))
}
}
}
fn stroke_values(&self, target: PaintTarget) -> BTreeMap<Channel, [f32; 3]> {
let ts = self.ts();
let Ok(set) = self.doc.project.texture_set(ts) else { return BTreeMap::new() };
let layer_channels = match target {
// A content paint effect paints its owner layer's channels.
PaintTarget::Layer(id) => {
let owner = self.doc.project.effect(id).map(|(owner, _)| owner).unwrap_or(id);
self.doc.project.layer(owner).map(|l| l.channels.keys().copied().collect::<BTreeSet<_>>()).unwrap_or_default()
}
PaintTarget::Mask(_) => BTreeSet::new(),
};
self.tool
.values
.iter()
.filter(|(c, _)| self.tool.enabled.contains(c) && set.has_channel(**c) && layer_channels.contains(c))
.map(|(c, v)| (*c, *v))
.collect()
}
/// Common setup of 3D and 2D strokes. `first_uv` is where the stroke starts on the mesh
/// (the Clone tool's destination anchor).
fn start_stroke(&mut self, viewport: Vec2, uv_mode: bool, first_uv: Option<Vec2>) -> Result<()> {
let tool = self.tool.tool;
let erase = tool == Tool::Eraser;
let quick_mask = self.quick_mask.editing;
let ts = self.ts();
let res = self.caches.get(ts).map(|c| c.resolution).unwrap_or(1024);
let pickup = if quick_mask { None } else { self.pickup_mode(first_uv)? };
if pickup.is_some() {
// Clone and smudge read the composite: bring it up to date first.
self.update();
}
let before = self.doc.clone();
let target = if quick_mask {
None
} else {
match self.paint_target() {
Ok(t) => Some(t),
Err(e) => {
self.doc = before;
return Err(e);
}
}
};
let values = target.map(|t| self.stroke_values(t)).unwrap_or_default();
let stencil = if tool == Tool::Projection && !quick_mask { self.capture_stencil(viewport) } else { None };
let problem = if !erase && values.is_empty() && matches!(target, Some(PaintTarget::Layer(_))) {
Some("no channel enabled to paint: enable channels in the tool's material")
} else if pickup.is_some() && matches!(target, Some(PaintTarget::Mask(_))) {
Some("the Clone and Smudge tools paint layer content: select the layer instead of its mask")
} else if tool == Tool::Projection && !quick_mask && stencil.is_none() && !uv_mode {
Some("the Projection tool needs a stencil: pick an image in the tool properties (tool.stencil)")
} else {
None
};
if let Some(msg) = problem {
self.doc = before;
return Err(EngineError::Other(msg.into()));
}
let depth = (!uv_mode).then(|| EyeDepth::render(&self.mesh, &self.camera, (viewport.x / 2.0).max(64.0) as u32, (viewport.y / 2.0).max(64.0) as u32));
let mut brush = self.tool.brush.clone();
if tool == Tool::Smudge {
// shortcut: smudge drags one stamp trail; mirrored trails would need one pickup each.
brush.symmetry = Default::default();
}
let stroke = Stroke::new(&brush, &self.mesh);
let mut canvas = StrokeCanvas::new(res);
if !quick_mask {
canvas.limit = self.stroke_limit(ts, res);
}
if let Some((mode, offset)) = pickup
&& let Some(cache) = self.caches.get(ts)
{
let r = res as f32;
let mode = match mode {
PickupMode::Clone { .. } => PickupMode::Clone { offset: [(offset[0] * r).round() as i64, (offset[1] * r).round() as i64] },
m => m,
};
canvas.pickup = Some(Pickup::new(mode, cache.composite.clone(), cache.gbuf.clone(), values.keys().copied()));
if tool == Tool::Clone
&& let Some(src) = self.tool.clone_source.as_mut()
{
src.offset.get_or_insert(offset);
}
}
let label = if quick_mask {
"Quick mask stroke"
} else if erase {
"Eraser stroke"
} else if matches!(target, Some(PaintTarget::Mask(_))) {
"Mask stroke"
} else {
"Paint stroke"
};
self.stroke = Some(ActiveStroke {
ts,
target,
stroke,
canvas,
depth,
uv: uv_mode.then_some((None, 0.0)),
camera: self.camera,
viewport,
values,
erase,
stencil,
before,
label: label.to_string(),
});
Ok(())
}
/// Clone / smudge pickup for the current tool, with the clone offset (source minus
/// destination) in texture coordinates.
fn pickup_mode(&self, first_uv: Option<Vec2>) -> Result<Option<(PickupMode, [f32; 2])>> {
match self.tool.tool {
Tool::Smudge => Ok(Some((PickupMode::Smudge { strength: self.tool.smudge_strength }, [0.0; 2]))),
Tool::Clone => {
let src =
self.tool.clone_source.ok_or_else(|| EngineError::Other("set a clone source first: V + click on the mesh (tool.cloneSource)".into()))?;
let offset = match (src.offset, first_uv) {
(Some(o), _) => o,
(None, Some(p)) => [src.uv[0] - p.x, src.uv[1] - p.y],
(None, None) => return Err(EngineError::Other("start the clone stroke on the mesh".into())),
};
Ok(Some((PickupMode::Clone { offset: [0; 2] }, offset)))
}
_ => Ok(None),
}
}
/// The brush shape: the alpha image when one is set and loaded, else the procedural alpha.
fn shape<'a>(images: &'a texturecraft_compose::ImageStore, b: &texturecraft_paint::BrushSettings) -> Shape<'a> {
Shape { alpha: b.alpha, image: b.alpha_image.as_ref().and_then(|n| images.get(n)).map(|i| &**i) }
}
/// The stencil placed for the current camera and viewport.
fn capture_stencil(&self, viewport: Vec2) -> Option<texturecraft_compose::Stencil> {
let st = self.tool.stencil.as_ref()?;
let image = self.images.get(&st.image)?.clone();
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
let (center, half, rotation) = st.placement(image.width as f32 / image.height.max(1) as f32, aspect);
Some(texturecraft_compose::Stencil { image, view_proj: self.camera.view_proj(aspect), center, half, rotation, tile: st.tile })
}
/// Start a stroke at `screen` (viewport pixels). Returns false when the cursor misses the
/// mesh (the stroke starts anyway and resumes when the cursor enters the mesh).
pub fn begin_stroke(&mut self, screen: Vec2, viewport: Vec2, pressure: f32) -> Result<bool> {
self.cancel_stroke();
match self.tool.tool {
Tool::PolygonFill => return self.polygon_fill(screen, viewport).map(|_| true),
Tool::ColorPicker => return self.color_pick(screen, viewport).map(|_| true),
_ => {}
}
let first_uv = if self.tool.tool == Tool::Clone { self.pick(screen, viewport).map(|h| h.uv) } else { None };
self.start_stroke(viewport, false, first_uv)?;
Ok(self.continue_stroke(screen, pressure))
}
/// Start a stroke in the 2D view at texture coordinate `uv`.
pub fn begin_stroke_uv(&mut self, uv: Vec2, pressure: f32) -> Result<()> {
self.cancel_stroke();
if matches!(self.tool.tool, Tool::PolygonFill | Tool::ColorPicker) {
return Err(EngineError::Other("use this tool in the 3D view".into()));
}
self.start_stroke(self.viewport, true, Some(uv))?;
self.continue_stroke_uv(uv, pressure);
Ok(())
}
/// Add a 2D view sample (texture coordinates). Brush size is relative to the UV square.
pub fn continue_stroke_uv(&mut self, uv: Vec2, pressure: f32) {
let Some(st) = self.stroke.as_mut() else { return };
let Some((last, carry)) = st.uv.as_mut() else { return };
let Some(cache) = self.caches.get_mut(st.ts) else { return };
let b = &st.stroke.settings;
let p = pressure.clamp(0.0, 1.0);
let radius = b.size * 2.0 * if p < 1.0 { b.min_size + (1.0 - b.min_size) * p } else { 1.0 };
let step = (b.spacing * 2.0 * radius).max(1e-5);
let mut points = Vec::new();
match *last {
None => points.push(uv),
Some(prev) => {
let seg = uv - prev;
let len = seg.length();
let mut t = step - *carry;
while t <= len && points.len() < 4096 {
points.push(prev + seg * (t / len.max(1e-9)));
t += step;
}
*carry = len - (t - step);
}
}
// Follow path: turn the stamp with the stroke direction (y up on screen, v grows down).
let angle = match *last {
Some(prev) if b.follow_path && uv != prev => b.angle + (prev.y - uv.y).atan2(uv.x - prev.x).to_degrees() - 90.0,
_ => b.angle,
};
*last = Some(uv);
let n0 = st.stroke.stamps.len() as u32;
let stamps: Vec<texturecraft_paint::UvStamp> = points
.iter()
.enumerate()
.map(|(i, c)| texturecraft_paint::UvStamp { center: *c, radius, angle, flow: b.flow, hardness: b.hardness, seed: n0 + i as u32 })
.collect();
texturecraft_paint::rasterize_uv(&mut st.canvas, &cache.gbuf, Self::shape(&self.images, b), &stamps);
let recent = std::mem::take(&mut st.canvas.recent);
let (ts, target) = (st.ts, st.target);
if target.is_some() {
self.mark_painted(ts, target, recent);
} else {
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
}
}
/// Add a pointer sample to the active stroke. Returns whether it hit the mesh.
pub fn continue_stroke(&mut self, screen: Vec2, pressure: f32) -> bool {
let Some(st) = self.stroke.as_mut() else { return false };
let Some(cache) = self.caches.get_mut(st.ts) else { return false };
let material = self.doc.project.texture_sets.get(st.ts).map(|t| t.material).unwrap_or(0);
let ctx = PickCtx { mesh: &self.mesh, bvh: &self.bvh, camera: &st.camera, viewport: st.viewport };
let stamps = st.stroke.add(&ctx, screen, pressure);
let hit = st.stroke.last_hit().is_some();
if stamps.is_empty() {
return hit;
}
let rctx = RasterCtx {
mesh: &self.mesh,
bvh: &self.bvh,
gbuf: &cache.gbuf,
material,
depth: st.depth.as_ref(),
eye: st.camera.eye(),
backface_culling: st.stroke.settings.backface_culling,
angle_fade: st.stroke.settings.angle_fade,
shape: Self::shape(&self.images, &st.stroke.settings),
};
rasterize(&mut st.canvas, &rctx, &stamps);
let recent = std::mem::take(&mut st.canvas.recent);
let (ts, target) = (st.ts, st.target);
if target.is_some() {
self.mark_painted(ts, target, recent);
} else {
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
}
hit
}
pub fn stroke_active(&self) -> bool {
self.stroke.is_some()
}
/// Commit the active stroke (one undo step).
pub fn end_stroke(&mut self) -> Result<()> {
let Some(st) = self.stroke.take() else { return Ok(()) };
let res = self.caches.get(st.ts).map(|c| c.resolution).unwrap_or(1024);
if st.canvas.dirty.is_empty() {
// Nothing painted: drop any mask effect the stroke created.
self.doc = st.before;
return Ok(());
}
let gbuf = self.caches.get(st.ts).map(|c| c.gbuf.clone());
let mesh = self.mesh.clone();
let stencil_fn = |x: u32, y: u32| -> Option<([f32; 3], f32)> {
let g = gbuf.as_ref()?;
let p = g.surface(&mesh, (y * g.width + x) as usize)?.pos;
st.stencil.as_ref()?.sample_world(p)
};
let per_texel: Option<texturecraft_paint::TexelFn> = if st.stencil.is_some() { Some(&stencil_fn) } else { None };
let carried = st.canvas.pickup.as_ref().map(|p| &p.values);
let src = CommitSource { alpha: &st.canvas.alpha, tiles: &st.canvas.dirty, opacity: st.stroke.settings.opacity, erase: st.erase, per_texel, carried };
match st.target {
Some(PaintTarget::Layer(id)) => commit_layer(&mut self.doc.pixels, id, res, &st.values, src),
Some(PaintTarget::Mask(eid)) => commit_mask(&mut self.doc.pixels, eid, res, self.tool.mask_value, src),
None => {
self.commit_quick_mask(st.ts, res, src);
return Ok(());
}
}
self.undo.push((st.label.clone(), st.before));
if self.undo.len() > crate::session::MAX_HISTORY {
self.undo.remove(0);
}
self.redo.clear();
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.mark_painted(st.ts, st.target, st.canvas.dirty.iter().copied());
Ok(())
}
/// Abandon the active stroke (Esc).
pub fn cancel_stroke(&mut self) {
if let Some(st) = self.stroke.take() {
self.mark_painted(st.ts, st.target, st.canvas.dirty.iter().copied());
if st.target.is_none() {
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
}
self.doc = st.before;
}
}
/// Paint a whole stroke through viewport points (scripted strokes from CLI/MCP).
pub fn stroke_points(&mut self, points: &[Vec2], viewport: Vec2) -> Result<usize> {
let Some(first) = points.first() else { return Err(EngineError::Other("a stroke needs at least one point".into())) };
self.begin_stroke(*first, viewport, 1.0)?;
let mut hits = 0;
for p in points.iter().skip(1) {
if self.continue_stroke(*p, 1.0) {
hits += 1;
}
}
let stamps = self.stroke.as_ref().map(|s| s.stroke.stamps.len()).unwrap_or(0);
self.end_stroke()?;
let _ = hits;
Ok(stamps)
}
/// Paint a whole 2D view stroke through texture coordinates. Returns the touched tiles.
pub fn stroke_uv_points(&mut self, points: &[Vec2]) -> Result<usize> {
let Some(first) = points.first() else { return Err(EngineError::Other("a stroke needs at least one point".into())) };
self.begin_stroke_uv(*first, 1.0)?;
for q in points.iter().skip(1) {
self.continue_stroke_uv(*q, 1.0);
}
let tiles = self.stroke_tiles();
self.end_stroke()?;
Ok(tiles)
}
/// Polygon fill: fill the triangle / UV island / whole mesh under `screen`.
pub fn polygon_fill(&mut self, screen: Vec2, viewport: Vec2) -> Result<usize> {
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
let ts = self.ts();
let material = self.doc.project.texture_set(ts)?.material;
if hit.material != material {
return Err(EngineError::Other("that surface belongs to another texture set".into()));
}
let tris = self.fill_set(hit.tri, material);
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
fill_triangles(&mut canvas, &gbuf, &tris);
self.commit_fill("Polygon fill", ts, &canvas)?;
Ok(tris.len())
}
/// The G-buffer of texture set `ts` and an empty canvas for a one-shot fill, limited by the
/// quick mask unless the fill edits it.
pub(crate) fn fill_canvas(&self, ts: usize) -> Result<(std::sync::Arc<texturecraft_geom::UvGBuffer>, StrokeCanvas)> {
let gbuf = self.caches.get(ts).map(|c| c.gbuf.clone()).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let mut canvas = StrokeCanvas::new(gbuf.width);
if !self.quick_mask.editing {
canvas.limit = self.stroke_limit(ts, gbuf.width);
}
Ok((gbuf, canvas))
}
/// Commit a one-shot fill with the tool's material (one undo step), or into the quick mask.
pub(crate) fn commit_fill(&mut self, label: &str, ts: usize, canvas: &StrokeCanvas) -> Result<()> {
let res = canvas.alpha.width();
let src = |opacity| CommitSource { alpha: &canvas.alpha, tiles: &canvas.dirty, opacity, erase: false, per_texel: None, carried: None };
if self.quick_mask.editing {
self.commit_quick_mask(ts, res, src(self.tool.brush.opacity));
return Ok(());
}
self.edit(label, |s| {
let target = s.paint_target()?;
let values = s.stroke_values(target);
match target {
PaintTarget::Layer(id) => commit_layer(&mut s.doc.pixels, id, res, &values, src(s.tool.brush.opacity)),
PaintTarget::Mask(eid) => commit_mask(&mut s.doc.pixels, eid, res, s.tool.mask_value, src(s.tool.brush.opacity)),
}
Ok(())
})
}
/// Triangles filled by the current fill mode starting from `tri`.
fn fill_set(&self, tri: u32, material: usize) -> BTreeSet<u32> {
let m = &self.mesh;
match self.tool.fill_mode {
FillMode::Triangle => [tri].into_iter().collect(),
FillMode::Mesh => m.triangles_of(material).map(|t| t as u32).collect(),
FillMode::UvIsland => {
// Triangles sharing vertex indices form a UV island (seams split vertices).
let mut by_vertex: BTreeMap<usize, Vec<u32>> = BTreeMap::new();
for t in m.triangles_of(material) {
if let Some(v) = m.tri(t) {
for i in v {
by_vertex.entry(i).or_default().push(t as u32);
}
}
}
let mut seen = BTreeSet::new();
let mut stack = vec![tri];
while let Some(t) = stack.pop() {
if !seen.insert(t) {
continue;
}
if let Some(v) = m.tri(t as usize) {
for i in v {
for n in by_vertex.get(&i).map(Vec::as_slice).unwrap_or(&[]) {
if !seen.contains(n) {
stack.push(*n);
}
}
}
}
}
seen
}
}
}
/// Color picker: copy the material under the cursor into the tool's paint values.
pub fn color_pick(&mut self, screen: Vec2, viewport: Vec2) -> Result<BTreeMap<Channel, [f32; 3]>> {
let hit = self.pick(screen, viewport).ok_or_else(|| EngineError::Other("nothing under the cursor".into()))?;
let ts = self.doc.project.texture_sets.iter().position(|t| t.material == hit.material).unwrap_or(self.ts());
let cache = self.caches.get(ts).ok_or_else(|| EngineError::Other("texture set not ready".into()))?;
let res = cache.resolution as f32;
let (x, y) = ((hit.uv.x * res).clamp(0.0, res - 1.0) as u32, (hit.uv.y * res).clamp(0.0, res - 1.0) as u32);
let mut out = BTreeMap::new();
for c in cache.composite.channels.keys() {
let v = cache.composite.value(*c, x, y);
self.tool.values.insert(*c, v);
out.insert(*c, v);
}
Ok(out)
}
/// The stroke canvas alpha of the active stroke (for overlays and tests).
pub fn stroke_tiles(&self) -> usize {
self.stroke.as_ref().map(|s| s.canvas.dirty.len()).unwrap_or(0)
}
/// Where the Clone tool reads for destination `at` (texture coordinates) as a surface
/// point: the source itself until the first stroke fixes the offset, or when `at` is None.
pub fn clone_source_point(&self, at: Option<Vec2>) -> Option<texturecraft_geom::glam::Vec3> {
let src = self.tool.clone_source?;
let uv = match (src.offset, at) {
(Some(o), Some(p)) => Vec2::new(p.x + o[0], p.y + o[1]),
_ => Vec2::from(src.uv),
};
if !((0.0..1.0).contains(&uv.x) && (0.0..1.0).contains(&uv.y)) {
return None;
}
let g = &self.caches.get(self.ts())?.gbuf;
let (x, y) = ((uv.x * g.width as f32) as usize, (uv.y * g.height as f32) as usize);
Some(g.surface(&self.mesh, y * g.width as usize + x)?.pos)
}
pub fn selected_layer_id(&self) -> Option<LayerId> {
self.selected_layer()
}
}
+184
View File
@@ -0,0 +1,184 @@
//! The Path tool: control points placed on the surface (3D view) or in texture space (2D view)
//! and a smooth curve through them, committed as one brush stroke, or, when closed and filled,
//! as an antialiased lasso fill of the visible surface (3D) or of the UV region (2D).
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use texturecraft_geom::glam::{Vec2, Vec3};
use texturecraft_paint::{Lasso, fill_coverage, spline};
use crate::commands::{CommandSpec, always, bad, boolp};
use crate::session::Tool;
use crate::tool_cmds::{points_param, set_tool, viewport_of};
use crate::{EngineError, Result, Session, cmd};
/// Control points kept at most.
pub const MAX_PATH_POINTS: usize = 4096;
/// Curve sampling step in viewport pixels (3D view) and texture units (2D view).
const STEP_PX: f32 = 2.0;
const STEP_UV: f32 = 0.001;
/// The curve being edited with the Path tool.
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
pub struct PathState {
/// Control points: surface positions (3D view) or texture coordinates with z = 0 (2D view).
pub points: Vec<Vec3>,
/// The points are texture coordinates (placed in the 2D view).
pub uv: bool,
/// The curve loops back to its first point.
pub closed: bool,
/// A closed path fills its interior instead of stroking the curve.
pub fill: bool,
}
impl PathState {
/// Append a control point; a point placed in the other view starts a new path.
pub fn push(&mut self, p: Vec3, uv: bool) {
if uv != self.uv {
self.points.clear();
self.uv = uv;
}
if self.points.len() < MAX_PATH_POINTS {
self.points.push(p);
}
}
}
pub fn specs() -> Vec<CommandSpec> {
vec![cmd!(
"tool.path",
"Path",
["Tools"],
Some("7"),
"{points?: [[x,y],...] viewport pixels on the mesh | uvPoints?: [[u,v],...], viewport?: [w,h], closed?, fill?, commit?: bool, clear?: bool} — selects the Path tool and edits its curve; commit paints the curve with the current brush, or fills a closed, filled path",
always,
path
)]
}
fn path(s: &mut Session, p: &Value) -> Result<Value> {
const CMD: &str = "tool.path";
if s.tool.tool != Tool::Path {
set_tool(s, Tool::Path)?;
}
let vp = viewport_of(s, p);
if boolp(p, "clear") == Some(true) {
s.tool.path.points.clear();
}
let placed = match (points_param(CMD, p, "points")?, points_param(CMD, p, "uvPoints")?) {
(Some(pts), _) => Some((
pts.iter()
.enumerate()
.map(|(i, q)| s.pick(*q, vp).map(|h| h.pos).ok_or_else(|| bad(CMD, format!("point {i} misses the mesh"))))
.collect::<Result<Vec<_>>>()?,
false,
)),
(None, Some(pts)) => Some((pts.iter().map(|q| q.clamp(Vec2::ZERO, Vec2::ONE).extend(0.0)).collect(), true)),
(None, None) => None,
};
if let Some((points, uv)) = placed {
if points.len() > MAX_PATH_POINTS {
return Err(bad(CMD, format!("at most {MAX_PATH_POINTS} control points")));
}
s.tool.path.points = points;
s.tool.path.uv = uv;
}
if let Some(v) = boolp(p, "closed") {
s.tool.path.closed = v;
}
if let Some(v) = boolp(p, "fill") {
s.tool.path.fill = v;
}
s.revision = s.revision.wrapping_add(1);
let committed = if boolp(p, "commit") == Some(true) {
let r = s.commit_path(vp)?;
s.update();
r
} else {
Value::Null
};
let st = &s.tool.path;
Ok(json!({ "points": st.points.len(), "uv": st.uv, "closed": st.closed, "fill": st.fill, "committed": committed }))
}
/// NDC (y up) to viewport pixels (origin top-left).
fn to_pixels(ndc: Vec2, viewport: Vec2) -> Vec2 {
Vec2::new((ndc.x * 0.5 + 0.5) * viewport.x, (0.5 - ndc.y * 0.5) * viewport.y)
}
impl Session {
/// The path's control points in view space: viewport pixels for a 3D path (None behind the
/// camera), texture coordinates for a 2D one.
pub fn path_view_points(&self, viewport: Vec2) -> Vec<Option<Vec2>> {
let path = &self.tool.path;
if path.uv {
return path.points.iter().map(|p| Some(p.truncate())).collect();
}
let aspect = viewport.x.max(1.0) / viewport.y.max(1.0);
path.points.iter().map(|p| self.camera.project(*p, aspect).map(|n| to_pixels(n.truncate(), viewport))).collect()
}
/// Paint the path with the current brush (or fill it when closed and filled), then clear it.
pub fn commit_path(&mut self, viewport: Vec2) -> Result<Value> {
let (uv, closed) = (self.tool.path.uv, self.tool.path.closed);
let fill = closed && self.tool.path.fill;
let pts: Vec<Vec2> = self.path_view_points(viewport).into_iter().flatten().collect();
if pts.is_empty() {
return Err(EngineError::Other("the path has no points: click the surface to add some".into()));
}
if fill && pts.len() < 3 {
return Err(EngineError::Other("a filled path needs at least three points".into()));
}
let curve = spline(&pts, closed, if uv { STEP_UV } else { STEP_PX });
let out = if fill {
json!({ "filledTiles": self.lasso_fill(curve, uv, viewport)? })
} else if uv {
json!({ "tiles": self.stroke_uv_points(&curve)? })
} else {
json!({ "stamps": self.stroke_points(&curve, viewport)? })
};
self.tool.path.points.clear();
Ok(out)
}
/// Fill the inside of `poly`: viewport pixels over the visible surface, or texture
/// coordinates. Returns the touched tiles.
fn lasso_fill(&mut self, poly: Vec<Vec2>, uv: bool, viewport: Vec2) -> Result<usize> {
let ts = self.ts();
let (gbuf, mut canvas) = self.fill_canvas(ts)?;
let w = gbuf.width.max(1);
if uv {
let lasso = Lasso::new(poly.iter().map(|p| *p * w as f32).collect());
fill_coverage(&mut canvas, &gbuf, |i, _| lasso.coverage(Vec2::new((i as u32 % w) as f32 + 0.5, (i as u32 / w) as f32 + 0.5)));
} else {
let lasso = Lasso::new(poly);
let view_proj = self.camera.view_proj(viewport.x.max(1.0) / viewport.y.max(1.0));
let inv = view_proj.inverse();
let (cull, mesh, bvh) = (self.tool.brush.backface_culling, &self.mesh, &self.bvh);
fill_coverage(&mut canvas, &gbuf, |i, _| {
let Some(s) = gbuf.surface(mesh, i) else { return 0.0 };
let c = view_proj * s.pos.extend(1.0);
if c.w <= 1e-6 {
return 0.0;
}
let ndc = Vec2::new(c.x, c.y) / c.w;
let a = lasso.coverage(to_pixels(ndc, viewport));
if a <= 0.0 {
return 0.0;
}
// Exact visibility (a depth buffer flickers on grazing surfaces): nothing between
// the near plane and the texel.
let o = inv * ndc.extend(0.0).extend(1.0);
let origin = o.truncate() / o.w;
let to = s.pos - origin;
let d = to.length();
let dir = to / d.max(1e-9);
let hidden = (cull && s.nrm.dot(dir) >= 0.0) || bvh.closest(origin, dir, d * 0.999).is_some();
if hidden { 0.0 } else { a }
});
}
let tiles = canvas.dirty.len();
self.commit_fill("Path fill", ts, &canvas)?;
Ok(tiles)
}
}
+143
View File
@@ -0,0 +1,143 @@
//! Shelf previews: built-in materials and smart masks evaluated on a unit sphere seen from +Z,
//! without a mesh or baked maps (generators that need mesh maps are approximated with world-space
//! noise). Cheap enough for lazily rendered thumbnails.
use texturecraft_compose::pattern::{Coords, procedural, world_noise};
use texturecraft_core::{Channel, EffectKind, Filter, Generator, GeneratorKind, LayerKind, Mask, MaskBackground, Project, Projection, Source, blend1};
use texturecraft_geom::glam::{Vec2, Vec3};
use crate::materials::{Builder, build};
/// Linear material values of one preview pixel.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct Sample {
pub base: [f32; 3],
pub metallic: f32,
pub roughness: f32,
pub height: f32,
}
/// The view-space normal (= position on the unit sphere) of each pixel of a `size²` image,
/// row-major, None outside the sphere.
pub fn sphere_normals(size: usize) -> impl Iterator<Item = Option<Vec3>> {
let r = (size as f32 * 0.5 - 1.0).max(0.5);
(0..size * size).map(move |i| {
let (x, y) = ((i % size) as f32 + 0.5 - size as f32 * 0.5, size as f32 * 0.5 - (i / size) as f32 - 0.5);
let (dx, dy) = (x / r, y / r);
let d2 = dx * dx + dy * dy;
(d2 <= 1.0).then(|| Vec3::new(dx, dy, (1.0 - d2).max(0.0).sqrt()))
})
}
fn coords(n: Vec3) -> Coords {
let uv = Vec2::new(n.z.atan2(n.x) / std::f32::consts::TAU + 0.5, n.y.clamp(-1.0, 1.0).acos() / std::f32::consts::PI);
Coords { uv, pos: n, nrm: n }
}
fn source(s: &Source, proj: &Projection, c: &Coords) -> Option<[f32; 3]> {
match s {
Source::Uniform(v) => Some(*v),
Source::Procedural { pattern, low, high } => {
let t = procedural(pattern, proj, c);
Some([0, 1, 2].map(|k| low[k] + (high[k] - low[k]) * t))
}
_ => None,
}
}
/// Approximate generator: mesh-map signals become world noise (a sphere has no edges or cavities).
fn generator(g: &Generator, c: &Coords) -> f32 {
let dir = Vec3::from(g.direction).try_normalize().unwrap_or(Vec3::Y);
let wear = (world_noise(c.pos, 3.0, 91) - 0.5) * 2.2;
let cavity = (world_noise(c.pos, 3.0, 57) - 0.3).clamp(0.0, 1.0) + (1.0 - c.nrm.y) * 0.1;
let s = match g.kind {
GeneratorKind::Position => c.pos.dot(dir) * 0.5 + 0.5,
GeneratorKind::Direction => c.nrm.dot(dir) * 0.5 + 0.5,
GeneratorKind::EdgeWear => wear,
GeneratorKind::Curvature => 0.5 + wear * 0.5,
GeneratorKind::AmbientOcclusion => 1.0 - cavity,
_ => cavity,
};
// Same thresholding as the compositor.
let s = if g.noise_amount > 0.0 { s + (world_noise(c.pos, g.noise_scale, g.seed) - 0.5) * g.noise_amount } else { s };
let soft = g.softness.max(1e-3);
let t = ((s - (1.0 - g.level.clamp(0.0, 1.0) - soft)) / (2.0 * soft)).clamp(0.0, 1.0);
let v = t * t * (3.0 - 2.0 * t);
if g.invert { 1.0 - v } else { v }
}
fn mask(m: &Mask, c: &Coords) -> f32 {
if !m.enabled {
return 1.0;
}
let mut v = if m.background == MaskBackground::White { 1.0 } else { 0.0 };
for e in m.effects.iter().filter(|e| e.visible) {
let val = match &e.kind {
EffectKind::Fill { source: s, projection } => source(s, projection, c).map(|x| x[0]),
EffectKind::Generator(g) => Some(generator(g, c)),
EffectKind::Levels(l) => Some(l.apply(v)),
EffectKind::Filter(Filter::Invert) => Some(1.0 - v),
_ => None,
};
if let Some(val) = val {
let blended = if matches!(e.kind, EffectKind::Levels(_) | EffectKind::Filter(_)) { val } else { blend1(e.blend, v, val) };
v += (blended - v) * e.opacity.clamp(0.0, 1.0);
}
}
v.clamp(0.0, 1.0)
}
const CHANNELS: [Channel; 4] = [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height];
/// Preview of built-in material `id` (None for an unknown id).
pub fn material(id: &str, size: usize) -> Option<Vec<Option<Sample>>> {
let mut p = Project::new("preview", "");
let layers = build(&mut Builder { p: &mut p, channels: CHANNELS.to_vec() }, id).ok()?;
Some(
sphere_normals(size)
.map(|n| {
let c = coords(n?);
let mut acc = CHANNELS.map(Channel::default_value);
for l in layers.iter().filter(|l| l.visible) {
let LayerKind::Fill(f) = &l.kind else { continue };
let w = l.mask.as_ref().map_or(1.0, |m| mask(m, &c));
for (a, ch) in acc.iter_mut().zip(CHANNELS) {
if let (Some(b), Some(v)) = (l.blend(ch), f.sources.get(&ch).and_then(|s| source(s, &f.projection, &c))) {
let t = w * b.opacity.clamp(0.0, 1.0);
*a = [0, 1, 2].map(|k| a[k] + (v[k] - a[k]) * t);
}
}
}
let [base, metal, rough, height] = acc;
Some(Sample { base, metallic: metal[0], roughness: rough[0], height: height[0] })
})
.collect(),
)
}
/// Preview of smart mask `id`: the mask value per pixel (None for an unknown id).
pub fn smart_mask(id: &str, size: usize) -> Option<Vec<Option<f32>>> {
let (bg, fx) = crate::smart_masks::preset(id)?;
let m = crate::smart_masks::build_mask(&mut Project::new("preview", ""), bg, fx);
Some(sphere_normals(size).map(|n| n.map(|n| mask(&m, &coords(n)))).collect())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn previews_cover_the_sphere_with_finite_values() {
for m in crate::materials::MATERIALS {
let px = material(m.id, 16).unwrap_or_else(|| panic!("{}", m.id));
let center = px[8 * 16 + 8].unwrap_or_else(|| panic!("{}", m.id));
assert!(center.base.iter().chain([&center.metallic, &center.roughness, &center.height]).all(|v| v.is_finite()), "{}", m.id);
assert!(px[0].is_none(), "corners are outside the sphere");
}
for sm in crate::smart_masks::SMART_MASKS {
let px = smart_mask(sm.id, 16).unwrap_or_else(|| panic!("{}", sm.id));
assert!(px.iter().flatten().all(|v| (0.0..=1.0).contains(v)), "{}", sm.id);
}
assert!(material("nope", 8).is_none() && smart_mask("nope", 8).is_none());
}
}
+77
View File
@@ -0,0 +1,77 @@
//! Project-level commands: new project, sample project, smart materials, inspection.
use serde_json::{Value, json};
use texturecraft_compose::BakedMaps;
use texturecraft_geom::primitives;
use crate::commands::{CommandSpec, always, bad, strp, u64p};
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"project.new",
"New project from a built-in mesh",
[],
None,
"{mesh?: material_ball|sphere|cube|rounded_cube|cylinder|torus|plane|crate, resolution?: 1024, name?}",
always,
new
),
cmd!("project.sample", "Open sample project", ["File"], None, "{}", always, sample),
cmd!("project.inspect", "Inspect project", [], None, "{}", always, |s, _| Ok(crate::inspect::session(s))),
cmd!("material.apply", "Add smart material", [], None, "{material: id or label}", always, material),
cmd!("material.list", "List materials", [], None, "{}", always, |_, _| Ok(json!(
crate::materials::MATERIALS.iter().map(|m| json!({"id": m.id, "label": m.label, "smart": m.smart})).collect::<Vec<_>>()
))),
]
}
fn new(s: &mut Session, p: &Value) -> Result<Value> {
let mesh_id = strp(p, "mesh").unwrap_or("material_ball");
let mesh = primitives::builtin(mesh_id).ok_or_else(|| bad("project.new", format!("unknown built-in mesh `{mesh_id}`")))?;
let res = u64p(p, "resolution").unwrap_or(1024);
let name = strp(p, "name").unwrap_or("Untitled");
let mut next = Session::new_project(name, mesh, &format!("builtin:{mesh_id}"), None, u32::try_from(res).unwrap_or(0))?;
next.viewport = s.viewport;
*s = next;
Ok(crate::inspect::session(s))
}
fn material(s: &mut Session, p: &Value) -> Result<Value> {
let id = strp(p, "material").ok_or_else(|| bad("material.apply", "`material` is required"))?;
let l = crate::materials::apply(s, id)?;
Ok(json!({ "layer": l.0 }))
}
/// The sample project: the material ball, baked, with smart materials on both texture sets.
pub fn sample_session(resolution: u32, bake_resolution: u32) -> Result<Session> {
let mut s = Session::new_project("Material Ball", primitives::material_ball(), "builtin:material_ball", None, resolution)?;
for ts in 0..s.set_count() {
let set = s.doc.project.texture_set_mut(ts)?;
set.bake.resolution = bake_resolution;
set.bake.rays = 24;
s.bake_now(ts)?;
}
s.active_set = 1;
crate::materials::apply(&mut s, "iron_rusted")?;
s.active_set = 0;
crate::materials::apply(&mut s, "steel_painted_worn")?;
s.undo.clear();
s.modified = false;
Ok(s)
}
fn sample(s: &mut Session, _: &Value) -> Result<Value> {
let mut next = sample_session(2048, 1024)?;
next.viewport = s.viewport;
*s = next;
Ok(crate::inspect::session(s))
}
pub(crate) fn baked_json(b: Option<&BakedMaps>) -> Value {
match b {
Some(b) => json!({ "resolution": b.resolution, "maps": b.maps.keys().map(|m| m.id()).collect::<Vec<_>>() }),
None => Value::Null,
}
}
+137
View File
@@ -0,0 +1,137 @@
//! Quick mask (Painter: Y enables, U edits, Ctrl+Shift+I inverts): a temporary texel mask per
//! texture set, painted with the normal brush while editing, that limits every paint stroke
//! while enabled. Session state only: not saved and not in the undo history.
use std::collections::BTreeMap;
use rayon::prelude::*;
use serde_json::{Value, json};
use texturecraft_core::Channel;
use texturecraft_paint::{CommitSource, commit_coverage};
use texturecraft_texel::{TileImage, from_u16, srgb_lut};
use crate::commands::{CommandSpec, always, boolp};
use crate::{Result, Session, cmd};
#[derive(Clone, Debug, Default)]
pub struct QuickMask {
/// Strokes are limited to the mask.
pub enabled: bool,
/// Strokes paint the mask instead of the layer stack.
pub editing: bool,
/// Strokes are limited to where the mask is not painted.
pub inverted: bool,
/// Painted coverage per texture set (1 component).
pub masks: BTreeMap<usize, TileImage>,
/// Bumps on every change (overlay refresh).
pub revision: u64,
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("viewport.quickMask", "Enable quick mask", ["Viewport"], Some("Y"), "{enabled?: bool} — toggles when omitted", always, enable),
cmd!(
"viewport.quickMask.edit",
"Edit quick mask",
["Viewport"],
Some("U"),
"{editing?: bool} — toggles when omitted; editing enables the mask",
always,
edit
),
cmd!("viewport.quickMask.invert", "Invert quick mask", ["Viewport"], Some("Ctrl+Shift+I"), "{}", always, invert),
]
}
fn state(s: &Session) -> Value {
let q = &s.quick_mask;
json!({
"enabled": q.enabled, "editing": q.editing, "inverted": q.inverted,
"paintedTiles": q.masks.get(&s.ts()).map(TileImage::allocated_count).unwrap_or(0),
})
}
fn changed(s: &mut Session) -> Result<Value> {
s.quick_mask.revision = s.quick_mask.revision.wrapping_add(1);
s.revision = s.revision.wrapping_add(1);
Ok(state(s))
}
fn enable(s: &mut Session, p: &Value) -> Result<Value> {
s.quick_mask.enabled = boolp(p, "enabled").unwrap_or(!s.quick_mask.enabled);
changed(s)
}
fn edit(s: &mut Session, p: &Value) -> Result<Value> {
s.cancel_stroke();
let q = &mut s.quick_mask;
q.editing = boolp(p, "editing").unwrap_or(!q.editing);
q.enabled |= q.editing;
changed(s)
}
fn invert(s: &mut Session, _: &Value) -> Result<Value> {
s.quick_mask.inverted = !s.quick_mask.inverted;
changed(s)
}
impl Session {
/// The quick mask of texture set `ts` at resolution `res` (empty when never painted).
fn quick_mask_image(&self, ts: usize, res: u32) -> TileImage {
match self.quick_mask.masks.get(&ts) {
Some(m) if m.width() == res => m.clone(),
Some(m) => m.resampled(res, res, &[0]),
None => TileImage::new(res, res, 1),
}
}
/// What limits a paint stroke on `ts`: the mask and whether it is inverted (None when the
/// quick mask is off or being edited).
pub(crate) fn stroke_limit(&self, ts: usize, res: u32) -> Option<(TileImage, bool)> {
let q = &self.quick_mask;
(q.enabled && !q.editing).then(|| (self.quick_mask_image(ts, res), q.inverted))
}
/// Commit a stroke into the quick mask of `ts`.
pub(crate) fn commit_quick_mask(&mut self, ts: usize, res: u32, src: CommitSource) {
let mut mask = self.quick_mask_image(ts, res);
commit_coverage(&mut mask, src);
self.quick_mask.masks.insert(ts, mask);
self.quick_mask.revision = self.quick_mask.revision.wrapping_add(1);
}
/// RGBA8 overlay of texture set `ts` while editing the quick mask (`size²`, display-encoded):
/// the base color, tinted red where painting is blocked. Includes the stroke in progress.
pub fn quick_mask_rgba(&self, ts: usize, size: u32) -> Option<Vec<u8>> {
let cache = self.caches.get(ts)?;
let res = cache.resolution;
let size = size.clamp(1, res);
let mask = self.quick_mask_image(ts, res);
let live = self.stroke.as_ref().filter(|s| s.ts == ts && s.target.is_none()).map(|s| (&s.canvas.alpha, s.stroke.settings.opacity, s.erase));
let base = cache.composite.channels.get(&Channel::BaseColor);
let lut = srgb_lut();
let inverted = self.quick_mask.inverted;
let mut out = vec![255u8; size as usize * size as usize * 4];
out.par_chunks_mut(size as usize * 4).enumerate().for_each(|(y, row)| {
let ty = (y as u64 * u64::from(res) / u64::from(size)) as u32;
for (x, px) in row.chunks_exact_mut(4).enumerate() {
let tx = (x as u64 * u64::from(res) / u64::from(size)) as u32;
let mut m = from_u16(mask.get(tx, ty)[0]);
if let Some((alpha, opacity, erase)) = live {
let a = from_u16(alpha.get(tx, ty)[0]) * opacity;
m = if erase { m * (1.0 - a) } else { a + m * (1.0 - a) };
}
let blocked = if inverted { m } else { 1.0 - m };
let raw = base.map(|b| b.get(tx, ty)).unwrap_or([32768; 4]);
let t = 0.55 * blocked;
for (k, tint) in [0.9, 0.1, 0.15].into_iter().enumerate() {
let c = f32::from(lut.get(usize::from(raw[k] >> 4)).copied().unwrap_or(0)) / 255.0;
if let Some(slot) = px.get_mut(k) {
*slot = ((c + (tint - c) * t).clamp(0.0, 1.0) * 255.0 + 0.5) as u8;
}
}
}
});
Some(out)
}
}
+152
View File
@@ -0,0 +1,152 @@
//! Image resources: import (PNG, JPEG, TGA, TIFF, BMP, WEBP, EXR, HDR), list, remove, and use as
//! fill sources.
use std::sync::Arc;
use serde_json::{Value, json};
use texturecraft_compose::ImageRes;
use texturecraft_core::{Channel, Fill, Layer, LayerKind, Projection, Source};
use crate::commands::{CommandSpec, always, bad, channel_param, strp};
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("resource.import", "Import resources", ["File"], None, "{path} — an image file (png, jpg, tga, tif, bmp, webp, exr, hdr)", always, import),
cmd!("resource.list", "List resources", [], None, "{}", always, |s, _| Ok(list(s))),
cmd!("resource.remove", "Remove resource", [], None, "{name}", always, remove),
cmd!("file.removeUnused", "Remove unused resources...", ["File"], None, "{}", always, remove_unused),
cmd!("layer.add.image", "Add fill layer from image", [], None, "{name, channel?: baseColor, projection?: uv|triplanar|planar, scale?}", always, add_image_fill),
]
}
/// Largest accepted resource file.
const MAX_BYTES: usize = 512 << 20;
fn decoded(d: texturecraft_formats::DecodedImage) -> Arc<ImageRes> {
Arc::new(ImageRes { width: d.width, height: d.height, rgba: d.rgba, srgb: d.srgb })
}
impl Session {
/// Add an image resource from bytes (one undo step); returns its unique, sanitized name.
pub fn import_resource_bytes(&mut self, file_name: &str, bytes: Vec<u8>) -> Result<String> {
if bytes.len() > MAX_BYTES {
return Err(EngineError::Other(format!("{file_name} is larger than {} MB", MAX_BYTES >> 20)));
}
let image = texturecraft_formats::decode_image(&bytes).map_err(|e| EngineError::Other(format!("{file_name}: {e}")))?;
let leaf = std::path::Path::new(file_name).file_name().and_then(|n| n.to_str()).unwrap_or("image");
let base = texturecraft_formats::sanitize_resource_name(leaf);
let mut name = base.clone();
let mut n = 2;
while self.doc.resources.contains_key(&name) {
name = format!("{n}_{base}");
n += 1;
}
let key = name.clone();
self.edit("Import resource", |s| {
s.doc.resources.insert(key, Arc::new(bytes));
Ok(())
})?;
self.images.insert(name.clone(), decoded(image));
Ok(name)
}
/// Decode resources that are not decoded yet and forget removed ones (after undo, redo, load).
pub fn sync_images(&mut self) {
let keep: Vec<String> = self.doc.resources.keys().cloned().collect();
self.images.retain(|k, _| keep.contains(k));
let missing: Vec<(String, Arc<Vec<u8>>)> = self.doc.resources.iter().filter(|(k, _)| !self.images.contains_key(*k)).map(|(k, v)| (k.clone(), v.clone())).collect();
for (k, bytes) in missing {
match texturecraft_formats::decode_image(&bytes) {
Ok(d) => {
self.images.insert(k, decoded(d));
}
Err(e) => self.log.push(format!("resource {k}: {e}")),
}
}
}
}
fn list(s: &Session) -> Value {
json!(
s.doc
.resources
.iter()
.map(|(k, v)| {
let (w, h) = s.images.get(k).map(|i| (i.width, i.height)).unwrap_or((0, 0));
json!({"name": k, "bytes": v.len(), "width": w, "height": h})
})
.collect::<Vec<_>>()
)
}
#[cfg(not(target_arch = "wasm32"))]
fn import(s: &mut Session, p: &Value) -> Result<Value> {
let path = strp(p, "path").ok_or_else(|| bad("resource.import", "`path` is required"))?;
let meta = std::fs::metadata(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
if meta.len() > MAX_BYTES as u64 {
return Err(bad("resource.import", format!("{path} is too large")));
}
let bytes = std::fs::read(path).map_err(|e| bad("resource.import", format!("cannot read {path}: {e}")))?;
let name = s.import_resource_bytes(path, bytes)?;
Ok(json!({ "name": name }))
}
#[cfg(target_arch = "wasm32")]
fn import(_: &mut Session, _: &Value) -> Result<Value> {
Err(EngineError::Other("file paths are not available in the browser; use File > Import resources".into()))
}
fn remove(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "name").ok_or_else(|| bad("resource.remove", "`name` is required"))?.to_string();
if !s.doc.resources.contains_key(&name) {
return Err(bad("resource.remove", format!("no resource `{name}`")));
}
s.edit("Remove resource", |s| {
s.doc.resources.remove(&name);
Ok(())
})?;
s.sync_images();
Ok(Value::Null)
}
/// Drop resources no layer, mask effect, the projection stencil or the environment uses (one undo
/// step).
fn remove_unused(s: &mut Session, _: &Value) -> Result<Value> {
let mut used = Vec::new();
for set in &s.doc.project.texture_sets {
for root in &set.stack {
crate::material_lib::images_used(&s.doc.project, *root, &mut used, 0);
}
}
used.extend(s.tool.stencil.as_ref().map(|st| st.image.clone()));
used.extend(s.doc.project.display.environment_resource().map(str::to_string));
let unused: Vec<String> = s.doc.resources.keys().filter(|k| !used.contains(k)).cloned().collect();
if !unused.is_empty() {
s.edit("Remove unused resources", |s| {
s.doc.resources.retain(|k, _| !unused.contains(k));
Ok(())
})?;
s.sync_images();
}
Ok(json!({ "removed": unused }))
}
fn add_image_fill(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "name").ok_or_else(|| bad("layer.add.image", "`name` is required"))?.to_string();
if !s.doc.resources.contains_key(&name) {
return Err(bad("layer.add.image", format!("no resource `{name}`")));
}
let ch = channel_param("layer.add.image", p, "channel")?.unwrap_or(Channel::BaseColor);
let projection = if p.get("projection").is_some() { crate::layer_cmds::projection_from(p, "layer.add.image")? } else { Projection::default() };
let ts = s.ts();
let label = std::path::Path::new(&name).file_stem().and_then(|n| n.to_str()).unwrap_or("Image").to_string();
let layer_name = s.doc.project.next_layer_name(ts, &label);
let id = s.edit("Add image fill", |s| {
let id = s.doc.project.alloc_id();
let mut fill = Fill { projection, ..Fill::default() };
fill.sources.insert(ch, Source::Image { name: name.clone() });
crate::layer_cmds::insert_selected(s, Layer::new(id, layer_name, LayerKind::Fill(fill), &[ch]))
})?;
Ok(json!({ "layer": id.0 }))
}
+698
View File
@@ -0,0 +1,698 @@
//! The editing session: document, mesh, per-texture-set caches, history, tool state.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use serde::{Deserialize, Serialize};
use texturecraft_compose::{BakedMaps, BelowCache, Composite, PaintTarget, PixelStore, StackKey, StrokePreview, covered_tiles, pad_tiles};
use texturecraft_core::{Channel, Layer, LayerId, LayerKind, Project, TextureSet};
use texturecraft_geom::glam::Vec2;
use texturecraft_geom::{Bvh, Mesh, OrbitCamera, UvGBuffer};
use texturecraft_paint::{BrushSettings, EyeDepth, Stroke, StrokeCanvas};
use texturecraft_texel::DilationMap;
use crate::{EngineError, Result};
/// Padding (texels) applied to composites for display.
pub const DISPLAY_PADDING: u32 = 8;
/// Undo steps kept.
pub const MAX_HISTORY: usize = 200;
/// Everything that undo/redo restores. Pixel data is copy-on-write, so snapshots are cheap.
#[derive(Clone, Debug)]
pub struct Document {
pub project: Project,
pub pixels: PixelStore,
pub baked: BTreeMap<usize, BakedMaps>,
/// Imported image resources by name: original file bytes.
pub resources: BTreeMap<String, Arc<Vec<u8>>>,
}
/// Derived per-texture-set data (rebuilt when the mesh or resolution changes).
pub struct SetCache {
pub resolution: u32,
pub gbuf: Arc<UvGBuffer>,
pub dilation: Arc<DilationMap>,
pub covered_tiles: Arc<Vec<(u32, u32)>>,
pub composite: Composite,
/// Tiles to recomposite.
pub dirty: BTreeSet<(u32, u32)>,
/// Tiles whose display textures must be re-uploaded.
pub upload: BTreeSet<(u32, u32)>,
/// Bumps on every composite change (thumbnails, exports, caches).
pub revision: u64,
/// The stack below the layer being edited, per tile (repaints skip it).
pub below: BelowCache,
}
impl SetCache {
fn new(mesh: &Mesh, ts: &TextureSet) -> SetCache {
let res = ts.resolution;
let gbuf = UvGBuffer::new(mesh, ts.material, res, res);
let dilation = DilationMap::new(&gbuf.coverage_mask(), res, res, Some(DISPLAY_PADDING));
let covered = covered_tiles(&gbuf);
let all: BTreeSet<(u32, u32)> = texturecraft_compose::all_tiles(res).into_iter().collect();
SetCache {
resolution: res,
gbuf: Arc::new(gbuf),
dilation: Arc::new(dilation),
covered_tiles: Arc::new(covered),
composite: Composite::new(&ts.channel_list(), res),
dirty: all.clone(),
upload: all,
revision: 0,
below: BelowCache::default(),
}
}
pub fn invalidate_all(&mut self) {
self.dirty.extend(self.covered_tiles.iter().copied());
}
}
/// Active tool.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum Tool {
#[default]
Paint,
Eraser,
Projection,
PolygonFill,
Smudge,
Clone,
ColorPicker,
/// Paint along an editable curve (or fill a closed one).
Path,
}
impl Tool {
pub const ALL: [Tool; 8] = [Tool::Paint, Tool::Eraser, Tool::Projection, Tool::PolygonFill, Tool::Smudge, Tool::Clone, Tool::ColorPicker, Tool::Path];
pub fn label(self) -> &'static str {
match self {
Tool::Paint => "Paint",
Tool::Eraser => "Eraser",
Tool::Projection => "Projection",
Tool::PolygonFill => "Polygon fill",
Tool::Smudge => "Smudge",
Tool::Clone => "Clone",
Tool::ColorPicker => "Color picker",
Tool::Path => "Path",
}
}
pub fn id(self) -> &'static str {
match self {
Tool::Paint => "paint",
Tool::Eraser => "eraser",
Tool::Projection => "projection",
Tool::PolygonFill => "polygonFill",
Tool::Smudge => "smudge",
Tool::Clone => "clone",
Tool::ColorPicker => "colorPicker",
Tool::Path => "path",
}
}
pub fn parse(s: &str) -> Option<Tool> {
let n = |x: &str| x.to_ascii_lowercase().replace([' ', '_', '-'], "");
Tool::ALL.into_iter().find(|t| n(t.id()) == n(s) || n(t.label()) == n(s))
}
}
/// What the viewport displays.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ViewMode {
/// The lit material.
#[default]
Material,
/// One channel, unlit.
Channel(Channel),
/// A baked mesh map.
MeshMap(texturecraft_core::BakedMap),
/// UV checker (texel density and seams).
UvChecker,
/// One layer's mask, in grayscale (Painter: Alt+click a mask).
Mask(LayerId),
}
impl ViewMode {
pub fn label(&self) -> String {
match self {
ViewMode::Material => "Material".into(),
ViewMode::Channel(c) => c.label().into(),
ViewMode::MeshMap(m) => m.label().into(),
ViewMode::UvChecker => "UV checker".into(),
ViewMode::Mask(_) => "Layer mask".into(),
}
}
}
/// Polygon fill granularity.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum FillMode {
#[default]
Triangle,
UvIsland,
Mesh,
}
/// A screen-pinned image for the Projection tool (Painter's stencil).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct StencilState {
/// Image resource name.
pub image: String,
/// Center in normalized device coordinates (-1..1, y up).
pub center: [f32; 2],
/// Height of the image as a fraction of the viewport height (1 = full height).
pub scale: f32,
/// Rotation in degrees.
pub rotation: f32,
/// Repeat the image across the screen.
pub tile: bool,
/// Overlay opacity in the viewport (display only).
pub opacity: f32,
}
impl StencilState {
pub fn new(image: &str) -> StencilState {
StencilState { image: image.to_string(), center: [0.0, 0.0], scale: 0.8, rotation: 0.0, tile: false, opacity: 0.5 }
}
/// Placement for a viewport aspect (width / height): center, half extents in NDC, radians.
pub fn placement(&self, image_aspect: f32, viewport_aspect: f32) -> ([f32; 2], [f32; 2], f32) {
let hy = self.scale.max(0.01);
let hx = hy * image_aspect / viewport_aspect.max(1e-3);
(self.center, [hx, hy], self.rotation.to_radians())
}
}
/// Tool settings shared by the UI, CLI and agents.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ToolState {
pub tool: Tool,
pub brush: BrushSettings,
/// Material painted per channel (linear values) and whether each channel is painted.
pub values: BTreeMap<Channel, [f32; 3]>,
pub enabled: BTreeSet<Channel>,
/// Gray painted into masks.
pub mask_value: f32,
pub fill_mode: FillMode,
/// Stencil used by the Projection tool.
#[serde(default)]
pub stencil: Option<StencilState>,
/// Smudge tool: how much of the picked-up values each stamp deposits (0..1).
#[serde(default = "default_smudge_strength")]
pub smudge_strength: f32,
/// Clone tool source (Painter: V + click).
#[serde(default)]
pub clone_source: Option<CloneSource>,
/// The Path tool's curve being edited.
#[serde(default)]
pub path: crate::path_tool::PathState,
}
fn default_smudge_strength() -> f32 {
0.5
}
/// Where the Clone tool copies from, in texture coordinates.
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct CloneSource {
pub uv: [f32; 2],
/// Source minus destination, fixed by the first stroke after the source was set and kept
/// for the following strokes (aligned cloning).
pub offset: Option<[f32; 2]>,
}
impl Default for ToolState {
fn default() -> Self {
let values = Channel::ALL.iter().map(|c| (*c, c.default_value())).collect();
let mut t = ToolState {
tool: Tool::Paint,
brush: BrushSettings::default(),
values,
enabled: [Channel::BaseColor, Channel::Metallic, Channel::Roughness, Channel::Height, Channel::Normal].into_iter().collect(),
mask_value: 1.0,
fill_mode: FillMode::Triangle,
stencil: None,
smudge_strength: default_smudge_strength(),
clone_source: None,
path: Default::default(),
};
t.values.insert(Channel::BaseColor, [0.8, 0.8, 0.8]);
t.values.insert(Channel::Roughness, [0.3; 3]);
t
}
}
/// What is selected in the layer stack.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum StackTarget {
#[default]
Content,
/// The layer's mask (painting adds/uses a paint effect).
Mask,
/// A specific effect.
Effect(LayerId),
}
pub(crate) struct ActiveStroke {
pub ts: usize,
/// None: the stroke edits the quick mask.
pub target: Option<PaintTarget>,
pub stroke: Stroke,
pub canvas: StrokeCanvas,
/// Camera visibility for 3D strokes (None for strokes in the 2D view).
pub depth: Option<EyeDepth>,
/// 2D view strokes: last UV point and the distance carried to the next stamp.
pub uv: Option<(Option<Vec2>, f32)>,
pub camera: OrbitCamera,
pub viewport: Vec2,
pub values: BTreeMap<Channel, [f32; 3]>,
pub erase: bool,
/// Projection tool: the stencil captured with the stroke's camera.
pub stencil: Option<texturecraft_compose::Stencil>,
/// History snapshot taken when the stroke began.
pub before: Document,
pub label: String,
}
pub struct Session {
pub doc: Document,
pub mesh: Arc<Mesh>,
/// Unique per loaded mesh (GPU caches compare it).
pub mesh_id: u64,
pub bvh: Arc<Bvh>,
/// Original mesh file (saved inside the project); None for built-in meshes.
pub mesh_source: Option<(String, Vec<u8>)>,
/// High-definition meshes and cage for baking (saved inside the project).
pub bake_meshes: crate::BakeMeshes,
pub caches: Vec<SetCache>,
pub(crate) undo: Vec<(String, Document)>,
pub(crate) redo: Vec<(String, Document)>,
pub tool: ToolState,
pub active_set: usize,
/// Selected layer per texture set.
pub selected: BTreeMap<usize, LayerId>,
pub target: StackTarget,
pub camera: OrbitCamera,
pub view: ViewMode,
/// Viewport size (pixels) used by scripted strokes.
pub viewport: Vec2,
pub(crate) stroke: Option<ActiveStroke>,
/// Layer clipboard: a document snapshot and the copied layer.
pub clipboard: Option<(Document, LayerId)>,
/// Decoded image resources (rebuilt from `doc.resources` by `Session::sync_images`).
pub images: texturecraft_compose::ImageStore,
/// Temporary texel mask limiting paint strokes (not saved, not in the history).
pub quick_mask: crate::quick_mask::QuickMask,
pub path: Option<String>,
pub modified: bool,
/// Bumps on every document change.
pub revision: u64,
/// Messages for the UI (status bar / toasts).
pub log: Vec<String>,
}
impl Session {
/// A session for `project` on `mesh` (texture sets must reference mesh materials).
pub fn new(doc: Document, mesh: Mesh, mesh_source: Option<(String, Vec<u8>)>) -> Result<Session> {
mesh.validate().map_err(|e| EngineError::Other(e.to_string()))?;
let bvh = Bvh::new(&mesh);
let mut camera = OrbitCamera { yaw: 0.6, pitch: 0.25, ..OrbitCamera::default() };
let (lo, hi) = mesh.bounds();
camera.frame(lo, hi);
let caches = doc.project.texture_sets.iter().map(|ts| SetCache::new(&mesh, ts)).collect();
let selected = doc.project.texture_sets.iter().enumerate().filter_map(|(i, ts)| ts.stack.last().map(|id| (i, *id))).collect();
static NEXT_MESH: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
Ok(Session {
doc,
mesh_id: NEXT_MESH.fetch_add(1, std::sync::atomic::Ordering::Relaxed),
mesh: Arc::new(mesh),
bvh: Arc::new(bvh),
mesh_source,
bake_meshes: Default::default(),
caches,
undo: Vec::new(),
redo: Vec::new(),
tool: ToolState::default(),
active_set: 0,
selected,
target: StackTarget::Content,
camera,
view: ViewMode::Material,
viewport: Vec2::new(1280.0, 800.0),
stroke: None,
clipboard: None,
images: Default::default(),
quick_mask: Default::default(),
path: None,
modified: false,
revision: 1,
log: Vec::new(),
})
}
/// A new project: one texture set per mesh material, each with an empty paint layer.
pub fn new_project(name: &str, mesh: Mesh, mesh_ref: &str, mesh_source: Option<(String, Vec<u8>)>, resolution: u32) -> Result<Session> {
let res = check_resolution(resolution)?;
let mut project = Project::new(name, mesh_ref);
let mats = if mesh.materials.is_empty() { vec!["Default".to_string()] } else { mesh.materials.clone() };
for (i, m) in mats.iter().enumerate() {
let mut ts = TextureSet::new(m.clone(), i, res);
let id = project.alloc_id();
let layer = Layer::new(id, "Layer 1", LayerKind::Paint, &ts.channel_list());
project.layers.insert(id, layer);
ts.stack.push(id);
project.texture_sets.push(ts);
}
Session::new(Document { project, pixels: PixelStore::default(), baked: BTreeMap::new(), resources: BTreeMap::new() }, mesh, mesh_source)
}
pub fn project(&self) -> &Project {
&self.doc.project
}
pub fn set_count(&self) -> usize {
self.doc.project.texture_sets.len()
}
/// The active texture set index, clamped.
pub fn ts(&self) -> usize {
self.active_set.min(self.set_count().saturating_sub(1))
}
pub fn selected_layer(&self) -> Option<LayerId> {
let ts = self.ts();
self.selected.get(&ts).copied().filter(|id| self.doc.project.locate(*id).is_some_and(|(t, _, _)| t == ts))
}
// -----------------------------------------------------------------------------------------
// History
/// Run an undoable edit. On error the document is left untouched.
pub fn edit<T>(&mut self, label: &str, f: impl FnOnce(&mut Session) -> Result<T>) -> Result<T> {
let before = self.doc.clone();
let result = f(self).and_then(|v| match self.doc.project.instance_cycle() {
Some(id) => Err(EngineError::Other(format!("instance layer {} would draw itself", id.0))),
None => Ok(v),
});
match result {
Ok(v) => {
self.push_history(label, before);
Ok(v)
}
Err(e) => {
self.doc = before;
Err(e)
}
}
}
pub(crate) fn push_history(&mut self, label: &str, before: Document) {
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(&before);
self.undo.push((label.to_string(), before));
if self.undo.len() > MAX_HISTORY {
self.undo.remove(0);
}
self.redo.clear();
}
/// Mark dirty every texture set whose composite differs between `other` and the current
/// document (after an edit, undo or redo).
fn invalidate_changed(&mut self, other: &Document) {
self.sync_caches();
let resources = |d: &Document| d.resources.iter().map(|(n, b)| (n.clone(), Arc::as_ptr(b))).collect::<Vec<_>>();
let all = resources(other) != resources(&self.doc);
let (empty, images) = (BakedMaps::default(), Default::default());
let key = |d: &Document, ts: usize| {
let stack = d.project.texture_sets.get(ts).map(|s| s.stack.as_slice()).unwrap_or_default();
StackKey::new(&d.project, &d.pixels, d.baked.get(&ts).unwrap_or(&empty), &images, ts, stack)
};
for ts in 0..self.caches.len() {
if (all || key(other, ts) != key(&self.doc, ts))
&& let Some(c) = self.caches.get_mut(ts)
{
c.invalidate_all();
}
}
}
/// Mark the document changed and every texture set dirty.
pub fn touched(&mut self) {
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.sync_caches();
for c in &mut self.caches {
c.invalidate_all();
}
}
/// Make caches agree with the project's texture sets (resolution or channel changes).
pub fn sync_caches(&mut self) {
let sets = self.doc.project.texture_sets.clone();
self.caches.truncate(sets.len());
for (i, ts) in sets.iter().enumerate() {
match self.caches.get_mut(i) {
Some(c) if c.resolution == ts.resolution => {
let want = ts.channel_list();
if c.composite.channels.keys().copied().collect::<Vec<_>>() != want {
c.composite = Composite::new(&want, ts.resolution);
c.upload.extend(texturecraft_compose::all_tiles(ts.resolution));
c.invalidate_all();
}
}
_ => {
let cache = SetCache::new(&self.mesh, ts);
if i < self.caches.len() {
self.caches[i] = cache;
} else {
self.caches.push(cache);
}
}
}
}
}
pub fn can_undo(&self) -> bool {
!self.undo.is_empty()
}
pub fn can_redo(&self) -> bool {
!self.redo.is_empty()
}
pub fn undo_label(&self) -> Option<&str> {
self.undo.last().map(|(l, _)| l.as_str())
}
pub fn redo_label(&self) -> Option<&str> {
self.redo.last().map(|(l, _)| l.as_str())
}
pub fn history_labels(&self) -> Vec<String> {
self.undo.iter().map(|(l, _)| l.clone()).collect()
}
pub fn undo(&mut self) -> Result<String> {
self.cancel_stroke();
let (label, doc) = self.undo.pop().ok_or_else(|| EngineError::Other("nothing to undo".into()))?;
let now = std::mem::replace(&mut self.doc, doc);
self.after_history(&now);
self.redo.push((label.clone(), now));
self.sync_images();
Ok(label)
}
pub fn redo(&mut self) -> Result<String> {
self.cancel_stroke();
let (label, doc) = self.redo.pop().ok_or_else(|| EngineError::Other("nothing to redo".into()))?;
let now = std::mem::replace(&mut self.doc, doc);
self.after_history(&now);
self.undo.push((label.clone(), now));
self.sync_images();
Ok(label)
}
fn after_history(&mut self, other: &Document) {
self.modified = true;
self.revision = self.revision.wrapping_add(1);
self.invalidate_changed(other);
}
// -----------------------------------------------------------------------------------------
// Compositing
/// Recomposite dirty tiles of every texture set (with the live stroke preview). Returns
/// whether anything changed.
pub fn update(&mut self) -> bool {
self.update_for(f64::INFINITY, || 0.0)
}
/// [`Session::update`] within about `budget_ms` of `clock` (milliseconds): tiles go in
/// chunks sized from the time the previous chunk took, and what is left stays dirty for the
/// next call (at least one chunk runs). The UI calls this every frame so a full recomposite
/// of a large texture set spreads over frames instead of freezing. The active texture set
/// goes first.
pub fn update_for(&mut self, budget_ms: f64, clock: impl Fn() -> f64) -> bool {
let start = clock();
let mut chunk = if budget_ms.is_finite() { rayon::current_num_threads().clamp(1, CHUNK) } else { CHUNK };
// The layer being edited: the stack below it is cached per tile.
let hot = self.stroke.as_ref().and_then(|s| s.target).map(|t| self.paint_owner(t)).or_else(|| self.selected_layer());
let stroke_res = self.stroke.as_ref().and_then(|s| self.caches.get(s.ts)).map(|c| c.resolution);
let preview = self.stroke.as_ref().and_then(|s| {
Some(StrokePreview {
target: s.target?,
alpha: s.canvas.alpha.clone(),
opacity: s.stroke.settings.opacity,
erase: s.erase,
values: s.values.clone(),
mask_value: self.tool.mask_value,
stencil: s.stencil.clone(),
carried: s.canvas.pickup.as_ref().map(|p| p.values.clone()).unwrap_or_default(),
})
});
let active = self.ts();
let order = std::iter::once(active).chain((0..self.caches.len()).filter(|ts| *ts != active));
let mut changed = false;
for ts in order {
let Some(cache) = self.caches.get_mut(ts) else { continue };
cache.below.set_hot(hot);
cache.below.pass = cache.dirty.len();
// Instances in sets of the stroke's size show the live stroke too.
let preview = preview.as_ref().filter(|_| Some(cache.resolution) == stroke_res);
while !cache.dirty.is_empty() {
let t0 = clock();
let tiles = next_chunk(&mut cache.dirty, chunk);
let empty = BakedMaps::default();
let inputs = texturecraft_compose::Inputs {
project: &self.doc.project,
ts,
mesh: &self.mesh,
gbuf: &cache.gbuf,
pixels: &self.doc.pixels,
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
preview,
images: &self.images,
bounds: self.mesh.bounds(),
};
texturecraft_compose::composite_tiles_cached(&inputs, &mut cache.composite, &tiles, Some(&mut cache.below));
// The composited tiles and the neighbours their padding reached change.
let padded = pad_tiles(&mut cache.composite, &cache.dilation, &tiles);
cache.upload.extend(tiles.iter().copied().chain(padded));
cache.revision = cache.revision.wrapping_add(1);
changed = true;
let now = clock();
let left = budget_ms - (now - start);
if left <= 0.0 {
return changed;
}
// As many tiles as fit in what is left, at the pace of this chunk.
let per_tile = (now - t0) / tiles.len().max(1) as f64;
let fit = if per_tile > 0.0 { (left / per_tile) as usize } else { CHUNK };
if fit == 0 {
return changed;
}
chunk = fit.min(CHUNK);
}
}
changed
}
/// Tiles still waiting to be composited, over every texture set.
pub fn pending_tiles(&self) -> usize {
self.caches.iter().map(|c| c.dirty.len()).sum()
}
/// The layer a stroke target belongs to (an effect's owner).
pub(crate) fn paint_owner(&self, t: PaintTarget) -> LayerId {
let (PaintTarget::Layer(id) | PaintTarget::Mask(id)) = t;
self.doc.project.effect(id).map_or(id, |(owner, _)| owner)
}
/// Mark `tiles` of texture set `ts` dirty after painting `target`, and the same tiles of
/// other sets of that size drawing it through an instance.
pub(crate) fn mark_painted(&mut self, ts: usize, target: Option<PaintTarget>, tiles: impl IntoIterator<Item = (u32, u32)>) {
let res = self.caches.get(ts).map(|c| c.resolution);
let sets = target.map(|t| self.doc.project.sets_drawing(self.paint_owner(t))).unwrap_or_default();
let tiles: Vec<(u32, u32)> = tiles.into_iter().collect();
for (i, c) in self.caches.iter_mut().enumerate() {
if i == ts || (sets.contains(&i) && Some(c.resolution) == res) {
c.dirty.extend(tiles.iter().copied());
}
}
}
/// Drain tiles needing upload for texture set `ts`.
pub fn take_uploads(&mut self, ts: usize) -> Vec<(u32, u32)> {
self.caches.get_mut(ts).map(|c| std::mem::take(&mut c.upload).into_iter().collect()).unwrap_or_default()
}
/// Grayscale RGBA8 of layer `id`'s mask at `size²` for the mask view (None without a mask).
pub fn mask_view_rgba(&self, id: LayerId, size: u32) -> Option<Vec<u8>> {
let (ts, _, _) = self.doc.project.locate(id)?;
let cache = self.caches.get(ts)?;
let empty = BakedMaps::default();
let inputs = texturecraft_compose::Inputs {
project: &self.doc.project,
ts,
mesh: &self.mesh,
gbuf: &cache.gbuf,
pixels: &self.doc.pixels,
baked: self.doc.baked.get(&ts).unwrap_or(&empty),
preview: None,
images: &self.images,
bounds: self.mesh.bounds(),
};
let gray = texturecraft_compose::mask_image(&inputs, id, size)?;
Some(gray.iter().flat_map(|g| [*g, *g, *g, 255]).collect())
}
pub fn baked(&self, ts: usize) -> Option<&BakedMaps> {
self.doc.baked.get(&ts)
}
/// Bytes held by painted layer pixels, the composites of every texture set and their
/// below-stack caches.
pub fn memory(&self) -> Memory {
let composites = self.caches.iter().flat_map(|c| c.composite.channels.values()).map(texturecraft_texel::TileImage::bytes).sum();
Memory { pixels: self.doc.pixels.bytes(), composites, cache: self.caches.iter().map(|c| c.below.bytes()).sum() }
}
}
/// Memory use reported by [`Session::memory`].
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Memory {
pub pixels: usize,
pub composites: usize,
pub cache: usize,
}
impl Memory {
pub fn total(self) -> usize {
self.pixels + self.composites + self.cache
}
}
/// Most tiles per composite chunk (a 1024² region).
const CHUNK: usize = 256;
/// Take up to `n` dirty tiles, block by block (16 × 16 tiles) so neighbourhood filters
/// evaluate compact regions.
fn next_chunk(dirty: &mut BTreeSet<(u32, u32)>, n: usize) -> Vec<(u32, u32)> {
if dirty.len() <= n {
return std::mem::take(dirty).into_iter().collect();
}
let mut tiles: Vec<(u32, u32)> = dirty.iter().copied().collect();
tiles.sort_by_key(|&(x, y)| (y / 16, x / 16, y, x));
tiles.truncate(n);
for t in &tiles {
dirty.remove(t);
}
tiles
}
/// Valid texture set resolutions: powers of two from 128 to 8192.
pub fn check_resolution(r: u32) -> Result<u32> {
if (128..=8192).contains(&r) && r.is_power_of_two() {
Ok(r)
} else {
Err(EngineError::Other(format!("resolution {r} must be a power of two between 128 and 8192")))
}
}
+127
View File
@@ -0,0 +1,127 @@
//! Texture set commands (Texture Set List / Texture Set Settings).
use serde_json::{Value, json};
use texturecraft_core::{Channel, ChannelBlend, ChannelFormat, NormalFormat};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, f32p, strp, u64p};
use crate::session::{StackTarget, check_resolution};
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("textureSet.select", "Select texture set", [], None, "{ts}", always, select),
cmd!("textureSet.list", "List texture sets", [], None, "{}", always, |s, _| Ok(crate::inspect::texture_sets(s))),
cmd!("textureSet.resolution", "Texture set size", [], None, "{ts?, resolution: 128..8192 (power of two)}", always, resolution),
cmd!("textureSet.channel.add", "Add channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, true)),
cmd!("textureSet.channel.remove", "Remove channel", [], None, "{ts?, channel}", always, |s, p| channel(s, p, false)),
cmd!("textureSet.visible", "Toggle texture set visibility", [], None, "{ts?, visible?}", always, visible),
cmd!("textureSet.rename", "Rename texture set", [], None, "{ts?, name}", always, rename),
cmd!("textureSet.settings", "Texture set settings", [], None, "{ts?, description?, heightStrength?, normalFormat?: openGl|directX}", always, settings),
]
}
fn ts_param(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
match u64p(p, "ts") {
Some(t) if (t as usize) < s.set_count() => Ok(t as usize),
Some(t) => Err(bad(cmd, format!("no texture set {t}"))),
None => Ok(s.ts()),
}
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let ts = u64p(p, "ts").map(|t| t as usize).filter(|t| *t < s.set_count()).ok_or_else(|| bad("textureSet.select", "valid `ts` index required"))?;
s.cancel_stroke();
s.active_set = ts;
s.target = StackTarget::Content;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "ts": ts }))
}
fn resolution(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.resolution")?;
let r = u64p(p, "resolution").ok_or_else(|| bad("textureSet.resolution", "`resolution` is required"))?;
let r = check_resolution(u32::try_from(r).unwrap_or(0))?;
s.edit("Texture set size", |s| {
s.doc.project.texture_set_mut(ts)?.resolution = r;
// Painted pixels are resampled (bilinear); strokes are not replayed.
crate::layer_ops::resample_set(s, ts, r);
Ok(())
})?;
Ok(json!({ "ts": ts, "resolution": r }))
}
fn channel(s: &mut Session, p: &Value, add: bool) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.channel")?;
let c = channel_param("textureSet.channel", p, "channel")?.ok_or_else(|| bad("textureSet.channel", "`channel` is required"))?;
s.edit(if add { "Add channel" } else { "Remove channel" }, |s| {
let set = s.doc.project.texture_set_mut(ts)?;
if add {
if !set.has_channel(c) {
set.channels.push((c, ChannelFormat::default_for(c)));
set.channels.sort_by_key(|(c, _)| c.index());
}
// Existing layers get the new channel enabled.
let ids: Vec<_> = s.doc.project.walk(ts).into_iter().map(|(id, _)| id).collect();
for id in ids {
if let Ok(l) = s.doc.project.layer_mut(id) {
let mode = if l.is_group() { texturecraft_core::BlendMode::Passthrough } else { texturecraft_core::BlendMode::Normal };
l.channels.entry(c).or_insert(ChannelBlend { mode, opacity: 1.0 });
}
}
} else {
if c == Channel::BaseColor {
return Err(bad("textureSet.channel.remove", "base color can't be removed"));
}
set.channels.retain(|(x, _)| *x != c);
}
Ok(())
})?;
Ok(Value::Null)
}
fn visible(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.visible")?;
let set = s.doc.project.texture_set_mut(ts)?;
set.visible = boolp(p, "visible").unwrap_or(!set.visible);
let v = set.visible;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "visible": v }))
}
fn rename(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.rename")?;
let name = strp(p, "name")
.map(str::trim)
.filter(|n| !n.is_empty() && n.chars().count() <= 128)
.ok_or_else(|| bad("textureSet.rename", "`name` is required"))?
.to_string();
s.edit("Rename texture set", |s| {
s.doc.project.texture_set_mut(ts)?.name = name;
Ok(())
})?;
Ok(Value::Null)
}
fn settings(s: &mut Session, p: &Value) -> Result<Value> {
let ts = ts_param(s, p, "textureSet.settings")?;
let nf = match strp(p, "normalFormat") {
Some("openGl") | Some("opengl") => Some(NormalFormat::OpenGl),
Some("directX") | Some("directx") => Some(NormalFormat::DirectX),
Some(o) => return Err(bad("textureSet.settings", format!("unknown normal format `{o}`"))),
None => None,
};
s.edit("Texture set settings", |s| {
if let Some(n) = nf {
s.doc.project.normal_format = n;
}
let set = s.doc.project.texture_set_mut(ts)?;
if let Some(d) = strp(p, "description") {
set.description = d.chars().take(4096).collect();
}
if let Some(h) = f32p(p, "heightStrength") {
set.height_strength = h.clamp(0.0, 100.0);
}
Ok(())
})?;
Ok(Value::Null)
}
+152
View File
@@ -0,0 +1,152 @@
//! Smart masks: procedural mask presets (generators and patterns driven by the baked mesh maps)
//! that replace a layer's mask in one step. Smart materials build their masks from the same
//! presets.
use serde_json::{Value, json};
use texturecraft_core::{
BlendMode, Effect, EffectKind, Filter, Generator, GeneratorKind, LayerId, Mask, MaskBackground, Procedural, ProceduralKind, Project, Projection, Source,
};
use crate::commands::{CommandSpec, always, bad, has_layer, layer_param, strp};
use crate::session::StackTarget;
use crate::{EngineError, Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("mask.smart.apply", "Apply smart mask", [], None, "{name: smart mask id or label, layer?}", has_layer, apply_cmd),
cmd!("mask.smart.list", "List smart masks", [], None, "{}", always, |_, _| Ok(json!(
SMART_MASKS.iter().map(|m| json!({"id": m.id, "label": m.label})).collect::<Vec<_>>()
))),
]
}
pub struct SmartMask {
pub id: &'static str,
pub label: &'static str,
}
pub const SMART_MASKS: &[SmartMask] = &[
SmartMask { id: "edge_wear", label: "Edges Worn" },
SmartMask { id: "edge_chipped", label: "Edges Chipped" },
SmartMask { id: "dirt_cavities", label: "Dirt in Cavities" },
SmartMask { id: "dust_top", label: "Dust from Top" },
SmartMask { id: "ground_dirt", label: "Ground Dirt" },
SmartMask { id: "rust_leaks", label: "Rust Leaks" },
SmartMask { id: "scratches", label: "Scratches" },
SmartMask { id: "grunge", label: "Grunge Blotches" },
SmartMask { id: "paint_chips", label: "Paint Chips" },
SmartMask { id: "fingerprints", label: "Fingerprints" },
];
fn norm(x: &str) -> String {
x.to_ascii_lowercase().replace([' ', '_', '-'], "")
}
pub fn find(name: &str) -> Option<&'static SmartMask> {
SMART_MASKS.iter().find(|m| norm(m.id) == norm(name) || norm(m.label) == norm(name))
}
const UP: [f32; 3] = [0.0, 1.0, 0.0];
/// A mesh-map generator with explicit threshold, softness and noise breakup.
pub(crate) fn generator(kind: GeneratorKind, level: f32, softness: f32, noise: f32) -> EffectKind {
EffectKind::Generator(Generator { level, softness, noise_amount: noise, ..Generator::new(kind) })
}
/// A direction or position generator (`invert` flips the result).
pub(crate) fn directional(kind: GeneratorKind, direction: [f32; 3], level: f32, softness: f32, noise: f32, invert: bool) -> EffectKind {
EffectKind::Generator(Generator { level, softness, noise_amount: noise, direction, invert, ..Generator::new(kind) })
}
/// A triplanar grayscale pattern fill.
pub(crate) fn pattern(kind: ProceduralKind, scale: f32, seed: u32, contrast: f32) -> EffectKind {
EffectKind::Fill {
source: Source::Procedural { pattern: Procedural { kind, scale, seed, contrast, balance: 0.0, invert: false }, low: [0.0; 3], high: [1.0; 3] },
projection: Projection::Triplanar { scale: 1.0, sharpness: 8.0, offset: [0.0; 3] },
}
}
/// Background and effects (bottom → top) of preset `id`.
pub(crate) fn preset(id: &str) -> Option<(MaskBackground, Vec<(EffectKind, BlendMode)>)> {
use BlendMode::*;
use GeneratorKind as G;
use ProceduralKind as P;
let fx = match find(id)?.id {
"edge_wear" => vec![(generator(G::EdgeWear, 0.55, 0.12, 0.5), Normal)],
// Wide edge band cut by chips, plus a thin solid line right on the edge.
"edge_chipped" => vec![
(generator(G::EdgeWear, 0.8, 0.2, 0.3), Normal),
(pattern(P::Chips, 3.0, 5, 1.0), Multiply),
(generator(G::EdgeWear, 0.45, 0.06, 0.6), Lighten),
],
"dirt_cavities" => vec![(generator(G::Dirt, 0.55, 0.25, 0.4), Normal)],
"dust_top" => vec![(directional(G::Direction, UP, 0.3, 0.15, 0.3, false), Normal), (pattern(P::Clouds, 3.0, 9, 1.4), Multiply)],
"ground_dirt" => vec![(directional(G::Position, [0.0, -1.0, 0.0], 0.35, 0.25, 0.5, false), Normal), (pattern(P::Grunge, 2.0, 12, 0.8), Multiply)],
// Streaks on surfaces that don't face up, fed by the crevices they run out of.
"rust_leaks" => vec![
(pattern(P::Streaks, 3.0, 4, 1.2), Normal),
(directional(G::Direction, UP, 0.2, 0.1, 0.0, true), Multiply),
(generator(G::Dirt, 0.45, 0.2, 0.5), Lighten),
],
"scratches" => vec![(pattern(P::Scratches, 3.0, 6, 1.0), Normal)],
"grunge" => vec![(pattern(P::Grunge, 2.0, 8, 1.0), Normal)],
"paint_chips" => vec![(pattern(P::Chips, 5.0, 2, 1.0), Normal), (generator(G::EdgeWear, 0.6, 0.12, 0.5), Lighten)],
"fingerprints" => vec![(pattern(P::Smudges, 4.0, 3, 1.0), Normal)],
_ => return None,
};
Some((MaskBackground::Black, fx))
}
/// Build a mask from a background and effects, allocating effect ids in `p`.
pub(crate) fn build_mask(p: &mut Project, bg: MaskBackground, effects: Vec<(EffectKind, BlendMode)>) -> Mask {
let mut m = Mask::new(bg);
for (k, blend) in effects {
m.effects.push(Effect { blend, ..Effect::new(p.alloc_id(), k) });
}
m
}
/// Preset `id` as a mask, optionally inverted (e.g. paint that survives where wear is not).
pub(crate) fn mask(p: &mut Project, id: &str, invert: bool) -> Result<Mask> {
let (bg, mut fx) = preset(id).ok_or_else(|| EngineError::Other(format!("unknown smart mask `{id}`")))?;
if invert {
fx.push((EffectKind::Filter(Filter::Invert), BlendMode::Normal));
}
Ok(build_mask(p, bg, fx))
}
/// Replace layer `layer`'s mask with smart mask `name` (one undo step).
pub fn apply(s: &mut Session, layer: LayerId, name: &str) -> Result<()> {
let sm = find(name).ok_or_else(|| EngineError::Other(format!("unknown smart mask `{name}`")))?;
s.edit(&format!("Apply smart mask {}", sm.label), |s| {
let m = mask(&mut s.doc.project, sm.id, false)?;
let old = s.doc.project.layer_mut(layer)?.mask.replace(m);
for e in old.map(|m| m.effects).unwrap_or_default() {
s.doc.pixels.masks.remove(&e.id);
}
s.target = StackTarget::Mask;
Ok(())
})
}
fn apply_cmd(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "name").ok_or_else(|| bad("mask.smart.apply", "`name` is required"))?;
let layer = layer_param(s, "mask.smart.apply", p)?;
apply(s, layer, name)?;
Ok(json!({ "layer": layer.0 }))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn every_preset_resolves_and_ids_are_unique() {
let (mut ids, mut labels) = (std::collections::BTreeSet::new(), std::collections::BTreeSet::new());
for m in SMART_MASKS {
assert!(preset(m.id).is_some(), "{}", m.id);
assert!(ids.insert(norm(m.id)) && labels.insert(norm(m.label)), "duplicate {}", m.id);
assert_eq!(find(m.label).map(|f| f.id), Some(m.id));
}
}
}
+322
View File
@@ -0,0 +1,322 @@
//! Tool commands: pick a tool, set brush and material values, and paint scripted strokes (the
//! way agents and the CLI paint).
use serde_json::{Value, json};
use texturecraft_core::Channel;
use texturecraft_geom::glam::Vec2;
use texturecraft_paint::{Alignment, BrushAlpha};
use crate::commands::{CommandSpec, always, bad, boolp, channel_param, color_param, f32p, strp};
use crate::session::{CloneSource, FillMode, Tool};
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("tool.paint", "Paint", ["Tools"], Some("1"), "{}", always, |s, _| set_tool(s, Tool::Paint)),
cmd!("tool.eraser", "Eraser", ["Tools"], Some("2"), "{}", always, |s, _| set_tool(s, Tool::Eraser)),
cmd!("tool.projection", "Projection", ["Tools"], Some("3"), "{}", always, |s, _| set_tool(s, Tool::Projection)),
cmd!("tool.polygonFill", "Polygon fill", ["Tools"], Some("4"), "{}", always, |s, _| set_tool(s, Tool::PolygonFill)),
cmd!("tool.smudge", "Smudge", ["Tools"], Some("5"), "{}", always, |s, _| set_tool(s, Tool::Smudge)),
cmd!("tool.clone", "Clone", ["Tools"], Some("6"), "{}", always, |s, _| set_tool(s, Tool::Clone)),
cmd!("tool.colorPicker", "Color picker", ["Tools"], Some("P"), "{}", always, |s, _| set_tool(s, Tool::ColorPicker)),
cmd!("tool.select", "Select tool", [], None, "{tool: paint|eraser|projection|polygonFill|smudge|clone|colorPicker|path}", always, select),
cmd!(
"tool.brush",
"Brush settings",
[],
None,
"{size?: 0..100, flow?: 0..100, opacity?: 0..100, spacing?: 1..1000, hardness?: 0..100, angle?, followPath?, alignment?: tangent|camera, lazy?, jitterSize?, jitterAngle?, jitterFlow?, jitterPosition?, alpha?: name | {image: resource name}, backfaceCulling?, symmetryX?, symmetryY?, symmetryZ?, minSize?, smudgeStrength?: 0..100, particles?: {enabled?, count?: 1..16, lifetime?: 1..128 steps, gravity?: 0..2}}",
always,
brush
),
cmd!("tool.material", "Tool material", [], None, "{channel, color?|value?, enabled?} or {maskValue?: 0..1}", always, material),
cmd!("tool.stencil", "Projection stencil", [], None, "{image?: resource name, center?: [x,y] NDC, scale?: 0.01..10, rotation?: degrees, tile?, opacity?, clear?: bool}", always, stencil),
cmd!(
"tool.cloneSource",
"Set clone source",
[],
None,
"{x, y, viewport?: [w,h]} a point on the mesh, or {uv: [u,v]}, or {clear: true} — the Clone tool copies from here (V + click)",
always,
clone_source
),
cmd!("tool.fillMode", "Polygon fill mode", [], None, "{mode: triangle|uvIsland|mesh}", always, fill_mode),
cmd!("tool.stroke", "Paint stroke", [], None, "{points: [[x,y],...] viewport pixels, viewport?: [w,h]} — paints with the current tool", always, stroke),
cmd!("tool.strokeUv", "Paint stroke in the 2D view", [], None, "{points: [[u,v],...] texture coordinates 0..1} — paints in UV space like the 2D view", always, stroke_uv),
cmd!("tool.click", "Tool click", [], None, "{x, y, viewport?: [w,h]} — polygon fill / color picker / single dab", always, click),
cmd!("tool.state", "Tool state", [], None, "{}", always, |s, _| Ok(serde_json::to_value(&s.tool).unwrap_or(Value::Null))),
]
}
pub(crate) fn set_tool(s: &mut Session, t: Tool) -> Result<Value> {
s.cancel_stroke();
s.tool.tool = t;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "tool": t.id() }))
}
fn select(s: &mut Session, p: &Value) -> Result<Value> {
let name = strp(p, "tool").ok_or_else(|| bad("tool.select", "`tool` is required"))?;
let t = Tool::parse(name).ok_or_else(|| bad("tool.select", format!("unknown tool `{name}`")))?;
set_tool(s, t)
}
/// Brush values use the UI's 0–100 scales, so agents and the sliders speak the same numbers.
fn brush(s: &mut Session, p: &Value) -> Result<Value> {
let b = &mut s.tool.brush;
let pct = |k: &str| f32p(p, k).map(|v| v / 100.0);
if let Some(v) = pct("size") {
b.size = v * 0.25;
}
if let Some(v) = pct("minSize") {
b.min_size = v;
}
if let Some(v) = pct("flow") {
b.flow = v;
}
if let Some(v) = pct("opacity") {
b.opacity = v;
}
if let Some(v) = pct("spacing") {
b.spacing = v;
}
if let Some(v) = pct("hardness") {
b.hardness = v;
}
if let Some(v) = f32p(p, "angle") {
b.angle = v;
}
if let Some(v) = boolp(p, "followPath") {
b.follow_path = v;
}
if let Some(a) = strp(p, "alignment") {
b.alignment = match a {
"camera" => Alignment::Camera,
"tangent" | "uv" => Alignment::Tangent,
other => return Err(bad("tool.brush", format!("unknown alignment `{other}`"))),
};
}
if let Some(v) = f32p(p, "lazy") {
b.lazy = v;
}
for (k, slot) in [("jitterSize", &mut b.jitter_size), ("jitterAngle", &mut b.jitter_angle), ("jitterFlow", &mut b.jitter_flow)] {
if let Some(v) = f32p(p, k) {
*slot = v / 100.0;
}
}
if let Some(v) = f32p(p, "jitterPosition") {
b.jitter_position = v / 100.0;
}
if let Some(a) = strp(p, "alpha") {
b.alpha = BrushAlpha::parse(a).ok_or_else(|| bad("tool.brush", format!("unknown alpha `{a}`")))?;
b.alpha_image = None;
} else if let Some(name) = p.get("alpha").and_then(|a| a.get("image")).and_then(Value::as_str) {
if !s.images.contains_key(name) {
return Err(bad("tool.brush", format!("no image resource `{name}` (import it first)")));
}
b.alpha_image = Some(name.to_string());
}
if let Some(v) = boolp(p, "backfaceCulling") {
b.backface_culling = v;
}
for (k, slot) in [("symmetryX", &mut b.symmetry.x), ("symmetryY", &mut b.symmetry.y), ("symmetryZ", &mut b.symmetry.z)] {
if let Some(v) = boolp(p, k) {
*slot = v;
}
}
if let Some(v) = boolp(p, "screenSpace") {
b.screen_space = v;
}
if let Some(q) = p.get("particles") {
let pt = &mut b.particles;
pt.enabled = boolp(q, "enabled").unwrap_or(pt.enabled);
pt.count = f32p(q, "count").map_or(pt.count, |v| v as u32);
pt.lifetime = f32p(q, "lifetime").map_or(pt.lifetime, |v| v as u32);
pt.gravity = f32p(q, "gravity").unwrap_or(pt.gravity);
}
*b = b.sanitized();
if let Some(v) = f32p(p, "smudgeStrength") {
s.tool.smudge_strength = (v / 100.0).clamp(0.0, 1.0);
}
s.revision = s.revision.wrapping_add(1);
Ok(brush_json(s))
}
pub(crate) fn brush_json(s: &Session) -> Value {
let b = &s.tool.brush;
json!({
"size": b.size / 0.25 * 100.0, "minSize": b.min_size * 100.0, "flow": b.flow * 100.0, "opacity": b.opacity * 100.0,
"spacing": b.spacing * 100.0, "hardness": b.hardness * 100.0, "angle": b.angle, "followPath": b.follow_path,
"alignment": format!("{:?}", b.alignment).to_lowercase(), "lazy": b.lazy,
"alpha": match &b.alpha_image { Some(name) => json!({ "image": name }), None => json!(b.alpha.label()) },
"backfaceCulling": b.backface_culling, "symmetry": [b.symmetry.x, b.symmetry.y, b.symmetry.z],
"smudgeStrength": s.tool.smudge_strength * 100.0, "particles": b.particles,
})
}
fn material(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(v) = f32p(p, "maskValue") {
s.tool.mask_value = v.clamp(0.0, 1.0);
}
if let Some(c) = channel_param("tool.material", p, "channel")? {
if let Some(v) = color_param(p, "color").or_else(|| color_param(p, "value")) {
let v = if c == Channel::Height { v.map(|x| x.clamp(-1.0, 1.0)) } else { v.map(|x| x.clamp(0.0, 1.0)) };
s.tool.values.insert(c, v);
s.tool.enabled.insert(c);
}
match boolp(p, "enabled") {
Some(true) => {
s.tool.enabled.insert(c);
}
Some(false) => {
s.tool.enabled.remove(&c);
}
None => {}
}
}
s.revision = s.revision.wrapping_add(1);
Ok(json!({
"values": s.tool.values.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::<serde_json::Map<_, _>>(),
"enabled": s.tool.enabled.iter().map(|c| c.id()).collect::<Vec<_>>(),
"maskValue": s.tool.mask_value,
}))
}
fn stencil(s: &mut Session, p: &Value) -> Result<Value> {
if boolp(p, "clear") == Some(true) {
s.tool.stencil = None;
return Ok(Value::Null);
}
if let Some(name) = strp(p, "image") {
if !s.doc.resources.contains_key(name) {
return Err(bad("tool.stencil", format!("no resource `{name}` (import it first)")));
}
let keep = s.tool.stencil.take();
let mut st = crate::session::StencilState::new(name);
if let Some(k) = keep {
st = crate::session::StencilState { image: name.to_string(), ..k };
}
s.tool.stencil = Some(st);
}
let st = s.tool.stencil.as_mut().ok_or_else(|| bad("tool.stencil", "no stencil: give `image`"))?;
if let Some(c) = color_param(p, "center").map(|c| [c[0], c[1]]).or_else(|| pair(p, "center")) {
st.center = c.map(|v| v.clamp(-4.0, 4.0));
}
if let Some(v) = f32p(p, "scale") {
st.scale = v.clamp(0.01, 10.0);
}
if let Some(v) = f32p(p, "rotation") {
st.rotation = v.rem_euclid(360.0);
}
if let Some(v) = boolp(p, "tile") {
st.tile = v;
}
if let Some(v) = f32p(p, "opacity") {
st.opacity = v.clamp(0.0, 1.0);
}
s.revision = s.revision.wrapping_add(1);
Ok(serde_json::to_value(&s.tool.stencil).unwrap_or(Value::Null))
}
/// A `[a, b]` param of two finite numbers.
fn pair(p: &Value, key: &str) -> Option<[f32; 2]> {
let a = p.get(key)?.as_array()?;
let v: Vec<f32> = a.iter().filter_map(Value::as_f64).map(|x| x as f32).filter(|x| x.is_finite()).collect();
match v.as_slice() {
[x, y] => Some([*x, *y]),
_ => None,
}
}
fn clone_source(s: &mut Session, p: &Value) -> Result<Value> {
if boolp(p, "clear") == Some(true) {
s.tool.clone_source = None;
return Ok(Value::Null);
}
let uv = match (pair(p, "uv"), f32p(p, "x"), f32p(p, "y")) {
(Some(uv), _, _) => uv.map(|v| v.clamp(0.0, 1.0)),
(None, Some(x), Some(y)) => {
let hit = s.pick(Vec2::new(x, y), viewport_of(s, p)).ok_or_else(|| bad("tool.cloneSource", "nothing under that point"))?;
if s.doc.project.texture_set(s.ts()).ok().map(|t| t.material) != Some(hit.material) {
return Err(bad("tool.cloneSource", "that surface belongs to another texture set"));
}
[hit.uv.x, hit.uv.y]
}
_ => return Err(bad("tool.cloneSource", "give `uv: [u, v]` or `x` and `y`")),
};
s.tool.clone_source = Some(CloneSource { uv, offset: None });
s.revision = s.revision.wrapping_add(1);
Ok(serde_json::to_value(s.tool.clone_source).unwrap_or(Value::Null))
}
fn fill_mode(s: &mut Session, p: &Value) -> Result<Value> {
s.tool.fill_mode = match strp(p, "mode").unwrap_or("triangle") {
"triangle" => FillMode::Triangle,
"uvIsland" | "island" => FillMode::UvIsland,
"mesh" => FillMode::Mesh,
other => return Err(bad("tool.fillMode", format!("unknown fill mode `{other}`"))),
};
Ok(Value::Null)
}
pub(crate) fn viewport_of(s: &Session, p: &Value) -> Vec2 {
match p.get("viewport").and_then(Value::as_array) {
Some(a) if a.len() == 2 => {
let w = a[0].as_f64().unwrap_or(0.0) as f32;
let h = a[1].as_f64().unwrap_or(0.0) as f32;
if w.is_finite() && h.is_finite() && w >= 16.0 && h >= 16.0 { Vec2::new(w.min(16384.0), h.min(16384.0)) } else { s.viewport }
}
_ => s.viewport,
}
}
/// A `[[x, y], ...]` param of at most 100000 finite points, None when the key is absent.
pub(crate) fn points_param(cmd: &str, p: &Value, key: &str) -> Result<Option<Vec<Vec2>>> {
let Some(v) = p.get(key) else { return Ok(None) };
let pts = v.as_array().ok_or_else(|| bad(cmd, format!("`{key}` must be an array of [x, y]")))?;
if pts.len() > 100_000 {
return Err(bad(cmd, "at most 100000 points"));
}
let points: Vec<Vec2> = pts
.iter()
.filter_map(|v| {
let a = v.as_array()?;
let (x, y) = (a.first()?.as_f64()? as f32, a.get(1)?.as_f64()? as f32);
(x.is_finite() && y.is_finite()).then_some(Vec2::new(x, y))
})
.collect();
if points.is_empty() {
return Err(bad(cmd, "no valid points"));
}
Ok(Some(points))
}
fn stroke(s: &mut Session, p: &Value) -> Result<Value> {
let points = points_param("tool.stroke", p, "points")?.ok_or_else(|| bad("tool.stroke", "`points` must be an array of [x, y]"))?;
let vp = viewport_of(s, p);
let stamps = s.stroke_points(&points, vp)?;
s.update();
Ok(json!({ "stamps": stamps }))
}
fn click(s: &mut Session, p: &Value) -> Result<Value> {
let (Some(x), Some(y)) = (f32p(p, "x"), f32p(p, "y")) else { return Err(bad("tool.click", "`x` and `y` are required")) };
let vp = viewport_of(s, p);
let out = match s.tool.tool {
Tool::PolygonFill => json!({ "triangles": s.polygon_fill(Vec2::new(x, y), vp)? }),
Tool::ColorPicker => {
let v = s.color_pick(Vec2::new(x, y), vp)?;
json!(v.iter().map(|(c, v)| (c.id().to_string(), json!(v))).collect::<serde_json::Map<_, _>>())
}
_ => json!({ "stamps": s.stroke_points(&[Vec2::new(x, y)], vp)? }),
};
s.update();
Ok(out)
}
fn stroke_uv(s: &mut Session, p: &Value) -> Result<Value> {
let points = points_param("tool.strokeUv", p, "points")?.ok_or_else(|| bad("tool.strokeUv", "`points` must be an array of [u, v]"))?;
let tiles = s.stroke_uv_points(&points)?;
s.update();
Ok(json!({ "tiles": tiles }))
}
+227
View File
@@ -0,0 +1,227 @@
//! Edit, viewport and display commands.
use serde_json::{Value, json};
use texturecraft_core::{BakedMap, Channel, ToneMapping};
use texturecraft_geom::glam::Vec3;
use crate::commands::{CommandSpec, always, bad, boolp, can_redo, can_undo, f32p, strp};
use crate::session::ViewMode;
use crate::{Result, Session, cmd};
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("viewport.frame", "Show entire mesh", ["Viewport"], Some("F"), "{}", always, frame),
cmd!("viewport.displayMaterial", "Display material", ["Viewport"], Some("M"), "{}", always, |s, _| set_view(s, ViewMode::Material)),
cmd!("viewport.nextChannel", "Display next channel", ["Viewport"], Some("C"), "{}", always, |s, _| cycle_channel(s, 1)),
cmd!("viewport.previousChannel", "Display previous channel", ["Viewport"], Some("Shift+C"), "{}", always, |s, _| cycle_channel(s, -1)),
cmd!("viewport.nextMeshMap", "Display next mesh map", ["Viewport"], Some("B"), "{}", always, |s, _| cycle_map(s, 1)),
cmd!("viewport.previousMeshMap", "Display previous mesh map", ["Viewport"], Some("Shift+B"), "{}", always, |s, _| cycle_map(s, -1)),
cmd!("viewport.view", "Set view mode", [], None, "{mode: material|uvChecker|mask|<channel id>|map:<mesh map id>, layer? (for mask)}", always, view),
cmd!("camera.set", "Set camera", [], None, "{yaw?, pitch? (degrees), distance?, fov?, target?: [x,y,z], ortho?}", always, camera_set),
cmd!("camera.get", "Get camera", [], None, "{}", always, |s, _| Ok(camera_json(s))),
cmd!("camera.orbit", "Orbit camera", [], None, "{dx?, dy? (degrees)}", always, orbit),
cmd!(
"display.set",
"Display settings",
[],
None,
"{environment?: <built-in>|resource:<image resource>, exposure?, blur?, rotation?, opacity?, toneMapping?: linear|aces, fov?, shadows?, aoIntensity?, bloom?, vignette?, sharpen?, grain?, postEffects?, taa?, specGloss?, parallax?}",
always,
display
),
]
}
pub(crate) fn edit_specs() -> Vec<CommandSpec> {
vec![
cmd!("edit.undo", "Undo", ["Edit"], Some("Ctrl+Z"), "{}", can_undo, |s, _| Ok(json!({ "undone": s.undo()? }))),
cmd!("edit.redo", "Redo", ["Edit"], Some("Ctrl+Y"), "{}", can_redo, |s, _| Ok(json!({ "redone": s.redo()? }))),
cmd!("edit.history", "History", [], None, "{}", always, |s, _| Ok(
json!({ "undo": s.history_labels(), "redo": s.redo.iter().rev().map(|(l, _)| l.clone()).collect::<Vec<_>>() })
)),
]
}
fn frame(s: &mut Session, _: &Value) -> Result<Value> {
let (lo, hi) = s.mesh.bounds();
s.camera.frame(lo, hi);
s.revision = s.revision.wrapping_add(1);
Ok(camera_json(s))
}
fn set_view(s: &mut Session, v: ViewMode) -> Result<Value> {
s.view = v;
s.revision = s.revision.wrapping_add(1);
Ok(json!({ "view": v.label() }))
}
fn cycle_channel(s: &mut Session, d: i64) -> Result<Value> {
let chans = s.doc.project.texture_set(s.ts()).map(|t| t.channel_list()).unwrap_or_default();
if chans.is_empty() {
return set_view(s, ViewMode::Material);
}
let n = chans.len() as i64;
let i = match s.view {
ViewMode::Channel(c) => chans.iter().position(|x| *x == c).map(|i| (i as i64 + d).rem_euclid(n)).unwrap_or(0),
_ => {
if d > 0 {
0
} else {
n - 1
}
}
};
set_view(s, ViewMode::Channel(chans[i as usize]))
}
fn cycle_map(s: &mut Session, d: i64) -> Result<Value> {
let maps = BakedMap::ALL;
let n = maps.len() as i64;
let i = match s.view {
ViewMode::MeshMap(m) => maps.iter().position(|x| *x == m).map(|i| (i as i64 + d).rem_euclid(n)).unwrap_or(0),
_ => {
if d > 0 {
0
} else {
n - 1
}
}
};
set_view(s, ViewMode::MeshMap(maps[i as usize]))
}
fn view(s: &mut Session, p: &Value) -> Result<Value> {
let m = strp(p, "mode").ok_or_else(|| bad("viewport.view", "`mode` is required"))?;
let v = match m {
"material" => ViewMode::Material,
"uvChecker" | "uv" | "checker" => ViewMode::UvChecker,
"mask" => {
let id = crate::commands::layer_param(s, "viewport.view", p)?;
if s.doc.project.layer(id)?.mask.is_none() {
return Err(bad("viewport.view", "the layer has no mask"));
}
ViewMode::Mask(id)
}
_ => match m.strip_prefix("map:") {
Some(id) => ViewMode::MeshMap(BakedMap::parse(id).ok_or_else(|| bad("viewport.view", format!("unknown mesh map `{id}`")))?),
None => ViewMode::Channel(Channel::parse(m).ok_or_else(|| bad("viewport.view", format!("unknown view mode `{m}`")))?),
},
};
set_view(s, v)
}
pub(crate) fn camera_json(s: &Session) -> Value {
let c = &s.camera;
json!({
"yaw": c.yaw.to_degrees(), "pitch": c.pitch.to_degrees(), "distance": c.distance, "fov": c.fov,
"target": c.target.to_array(), "eye": c.eye().to_array(), "ortho": c.ortho,
})
}
fn camera_set(s: &mut Session, p: &Value) -> Result<Value> {
let c = &mut s.camera;
if let Some(v) = f32p(p, "yaw") {
c.yaw = v.to_radians();
}
if let Some(v) = f32p(p, "pitch") {
c.pitch = v.clamp(-89.0, 89.0).to_radians();
}
if let Some(v) = f32p(p, "distance") {
c.distance = v.clamp(c.scene_radius * 0.05, c.scene_radius * 200.0);
}
if let Some(v) = f32p(p, "fov") {
c.fov = v.clamp(5.0, 150.0);
}
if let Some(t) = p.get("target").and_then(Value::as_array) {
let v: Vec<f32> = t.iter().filter_map(Value::as_f64).map(|x| x as f32).collect();
if v.len() == 3 && v.iter().all(|x| x.is_finite()) {
c.target = Vec3::new(v[0], v[1], v[2]);
}
}
if let Some(o) = boolp(p, "ortho") {
c.ortho = o;
}
s.revision = s.revision.wrapping_add(1);
Ok(camera_json(s))
}
fn orbit(s: &mut Session, p: &Value) -> Result<Value> {
s.camera.orbit(f32p(p, "dx").unwrap_or(0.0).to_radians(), f32p(p, "dy").unwrap_or(0.0).to_radians());
s.revision = s.revision.wrapping_add(1);
Ok(camera_json(s))
}
fn display(s: &mut Session, p: &Value) -> Result<Value> {
let tm = match strp(p, "toneMapping") {
Some("linear") => Some(ToneMapping::Linear),
Some("aces") | Some("acesFilmic") => Some(ToneMapping::AcesFilmic),
Some(o) => return Err(bad("display.set", format!("unknown tone mapping `{o}`"))),
None => None,
};
let env = strp(p, "environment").map(str::to_string);
if let Some(name) = env.as_deref().and_then(|e| e.strip_prefix(texturecraft_core::project::ENV_RESOURCE_PREFIX))
&& !s.images.contains_key(name)
{
return Err(bad("display.set", format!("no image resource `{name}` (import it with resource.import)")));
}
let d = &mut s.doc.project.display;
if let Some(e) = env {
d.environment = e;
}
for (k, slot, lo, hi) in [
("exposure", &mut d.env_exposure, -10.0, 10.0),
("blur", &mut d.env_blur, 0.0, 1.0),
("rotation", &mut d.env_rotation, -360.0, 360.0),
("opacity", &mut d.env_opacity, 0.0, 1.0),
("fov", &mut d.fov, 5.0, 150.0),
("aoIntensity", &mut d.ao_intensity, 0.0, 1.0),
("bloom", &mut d.bloom, 0.0, 1.0),
("vignette", &mut d.vignette, 0.0, 1.0),
("sharpen", &mut d.sharpen, 0.0, 1.0),
("grain", &mut d.grain, 0.0, 1.0),
] {
if let Some(v) = f32p(p, k) {
*slot = v.clamp(lo, hi);
}
}
if let Some(t) = tm {
d.tone_mapping = t;
}
if let Some(b) = boolp(p, "shadows") {
d.shadows = b;
}
for (k, slot) in [("postEffects", &mut d.post_effects), ("taa", &mut d.taa), ("specGloss", &mut d.spec_gloss), ("parallax", &mut d.parallax)] {
if let Some(b) = boolp(p, k) {
*slot = b;
}
}
s.camera.fov = s.doc.project.display.fov;
s.revision = s.revision.wrapping_add(1);
Ok(serde_json::to_value(&s.doc.project.display).unwrap_or(Value::Null))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::execute;
#[test]
fn hdr_resources_become_the_environment() {
let mut s = Session::new_project("t", texturecraft_geom::primitives::sphere(1.0, 16, 8), "builtin:sphere", None, 128).unwrap();
assert!(execute(&mut s, "display.set", &json!({"environment": "resource:sky.hdr"})).is_err(), "unknown resources are rejected");
let img = image::Rgb32FImage::from_fn(64, 32, |_, y| image::Rgb([if y < 8 { 40.0 } else { 0.5 }; 3]));
let mut hdr = Vec::new();
image::DynamicImage::ImageRgb32F(img).write_to(&mut std::io::Cursor::new(&mut hdr), image::ImageFormat::Hdr).unwrap();
let name = s.import_resource_bytes("sky.hdr", hdr).unwrap();
let res = &s.images[&name];
assert!(!res.srgb && res.rgba[0][0] > 30.0, "HDR keeps values above 1");
let env = format!("resource:{name}");
let r = execute(&mut s, "display.set", &json!({"environment": env, "specGloss": true, "parallax": true, "taa": false})).unwrap();
assert_eq!(r["environment"], json!(env));
let d = &s.doc.project.display;
assert!(d.spec_gloss && d.parallax && !d.taa);
assert_eq!(d.environment_resource(), Some(name.as_str()));
execute(&mut s, "file.removeUnused", &Value::Null).unwrap();
assert!(s.doc.resources.contains_key(&name), "the environment's image counts as used");
}
}
Loaded 100 of 229 files, more files were not shown because too many files have changed in this diff. Show more