Free, open-source 3D sculpting for Linux, macOS and Windows: dense meshes, remeshing, painting, built-in AI (image/text to 3D), Send to Unreal, game-ready LODs, Gaussian splats and OpenUSD.
C++ 3d3d-sculptingcppdear-imguidigital-sculptingfbxgame-developmentgaussian-splattinggltfimage-to-3dmcpopenglopenusdsculptingtext-to-3dunreal-engine
Insider daily drops: generator, quality gate, workflow (WIP)
islandmedb4fc666aead4
diff --git a/.github/workflows/insider-drop.yml b/.github/workflows/insider-drop.ymlnew file mode 100644index 00000000..4627a6c0--- /dev/null+++ b/.github/workflows/insider-drop.yml@@ -0,0 +1,139 @@+# Insider daily drop (tools/drops/drops.py): every day it builds sculptforge, makes the day's candidates (seeded by+# the date), gates them on the standard test sculpt, packs the best one as an .sfpack and+# - posts it to #insiders (DISCORD_INSIDERS_WEBHOOK; skipped quietly when unset),+# - commits it to the private repo islandmed/sculptforge-insiders under drops/YYYY/MM/<date>/ (INSIDERS_REPO_TOKEN:+# a fine-grained token for that one repository with Contents: Read and write; skipped when unset).+# On the 1st it also bundles last month's drops into "Insider Pack YYYY-MM" for Supporters (#members through+# DISCORD_MEMBERS_WEBHOOK, kept under bundles/ in the private repo) and schedules it in the public pack listing+# (listing.json on this repository's `packs` branch) for three months after the month ends. Each run publishes+# the bundles whose public date has come: their .sfpack goes next to the listing and is marked released.+# Only this repository's own code runs; no pull request or issue input reaches it.+name: Insider drop++on:+ schedule:+ - cron: "23 14 * * *"+ workflow_dispatch:+ inputs:+ date:+ description: "Drop date YYYY-MM-DD (default today, UTC)"+ required: false+ month:+ description: "Also bundle this month YYYY-MM (default: last month, on the 1st only)"+ required: false++permissions:+ contents: write # the `packs` branch (public listing)++concurrency:+ group: insider-drop++jobs:+ drop:+ runs-on: ubuntu-24.04+ timeout-minutes: 60+ env:+ HAS_INSIDERS: ${{ secrets.INSIDERS_REPO_TOKEN != '' }}+ CCACHE_DIR: ${{ github.workspace }}/.ccache+ CCACHE_BASEDIR: ${{ github.workspace }}+ CCACHE_MAXSIZE: 500M+ CCACHE_DEPEND: 'true'+ steps:+ - uses: actions/checkout@v7+ - name: Dates+ env:+ IN_DATE: ${{ inputs.date }}+ IN_MONTH: ${{ inputs.month }}+ run: |+ DATE="${IN_DATE:-$(date -u +%F)}"+ [[ "$DATE" =~ ^20[0-9][0-9]-[01][0-9]-[0-3][0-9]$ ]] || { echo "bad date '$DATE'"; exit 1; }+ MONTH="$IN_MONTH"+ if [ -z "$MONTH" ] && [ "${DATE:8:2}" = "01" ]; then MONTH=$(date -u -d "$DATE -1 day" +%Y-%m); fi+ [ -z "$MONTH" ] || [[ "$MONTH" =~ ^20[0-9][0-9]-[01][0-9]$ ]] || { echo "bad month '$MONTH'"; exit 1; }+ echo "DATE=$DATE" >> "$GITHUB_ENV"+ echo "DROP_DIR=drops/${DATE:0:4}/${DATE:5:2}/$DATE" >> "$GITHUB_ENV"+ echo "MONTH=$MONTH" >> "$GITHUB_ENV"+ - name: Insider repository+ if: env.HAS_INSIDERS == 'true'+ uses: actions/checkout@v7+ with:+ repository: islandmed/sculptforge-insiders+ token: ${{ secrets.INSIDERS_REPO_TOKEN }}+ path: insiders+ - name: Already done today?+ run: |+ if [ -f "insiders/$DROP_DIR/drop.json" ]; then echo "SKIP_DROP=1" >> "$GITHUB_ENV"; echo "$DATE already dropped"; fi+ - name: Dependencies+ run: |+ sudo ./packaging/linux/install-build-deps.sh+ sudo apt-get install -y --no-install-recommends ccache xvfb libgl1-mesa-dri+ - name: Compiler cache (restore; CI's Linux cache)+ uses: actions/cache/restore@v5+ with:+ path: .ccache+ key: ccache-ci-linux-x86_64.${{ github.sha }}+ restore-keys: ccache-ci-linux-x86_64.+ - name: Build sculptforge and sculptforge-cli+ run: |+ cmake -S . -B build -DCMAKE_BUILD_TYPE=Release -DSCULPTFORGE_USE_SYSTEM_SDL=OFF -DSCULPTFORGE_BUILD_TESTS=OFF \+ -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache+ cmake --build build --target sculptforge sculptforge-cli --parallel 4+ - name: Make the drop+ if: env.SKIP_DROP != '1'+ run: |+ mkdir -p insiders/drops+ xvfb-run -a -s "-screen 0 1280x1024x24" env LIBGL_ALWAYS_SOFTWARE=1 \+ python3 tools/drops/drops.py daily --date "$DATE" --out "$RUNNER_TEMP/out" \+ --history insiders/drops/history.json --app build/sculptforge --cli build/sculptforge-cli+ - name: Post to #insiders+ if: env.SKIP_DROP != '1'+ env:+ DISCORD_INSIDERS_WEBHOOK: ${{ secrets.DISCORD_INSIDERS_WEBHOOK }}+ run: |+ [ -f "$RUNNER_TEMP/out/$DATE/drop.json" ] || { echo "no drop today"; exit 0; }+ python3 tools/drops/drops.py post "$RUNNER_TEMP/out/$DATE" --webhook-env DISCORD_INSIDERS_WEBHOOK+ - name: Bundle the month for Supporters+ if: env.MONTH != '' && env.HAS_INSIDERS == 'true'+ env:+ DISCORD_MEMBERS_WEBHOOK: ${{ secrets.DISCORD_MEMBERS_WEBHOOK }}+ run: |+ B="insiders/bundles/$MONTH"+ if [ -f "$B/bundle.json" ]; then echo "$MONTH already bundled"; exit 0; fi+ python3 tools/drops/drops.py monthly --month "$MONTH" --drops insiders/drops --out "$B" --cli build/sculptforge-cli+ python3 tools/drops/drops.py post "$B" --webhook-env DISCORD_MEMBERS_WEBHOOK+ - name: Commit to the insider repository+ if: env.HAS_INSIDERS == 'true'+ run: |+ if [ -f "$RUNNER_TEMP/out/$DATE/drop.json" ] || [ -f "$RUNNER_TEMP/out/$DATE/gate.json" ]; then+ mkdir -p "insiders/$DROP_DIR" && cp -r "$RUNNER_TEMP/out/$DATE/." "insiders/$DROP_DIR/"+ fi+ cd insiders+ git add -A .+ if git diff --cached --quiet; then echo "nothing to commit"; exit 0; fi+ git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \+ commit -qm "Drop $DATE${MONTH:+, Insider Pack $MONTH}"+ git push -q+ - name: Public pack listing (schedule and release)+ if: env.HAS_INSIDERS == 'true'+ run: |+ P="$RUNNER_TEMP/packs"+ mkdir -p "$P/insider"+ if git fetch --depth=1 origin packs 2>/dev/null; then git --work-tree="$P" checkout FETCH_HEAD -- . && git reset -q; fi+ for b in insiders/bundles/*/bundle.json; do+ [ -f "$b" ] || continue+ id=$(python3 -c "import json,sys; print(json.load(open(sys.argv[1]))['id'])" "$b")+ grep -q "\"$id\"" "$P/listing.json" 2>/dev/null || python3 tools/drops/drops.py schedule --listing "$P/listing.json" --bundle "$(dirname "$b")"+ done+ [ -f "$P/listing.json" ] || exit 0+ for id in $(python3 tools/drops/drops.py due --listing "$P/listing.json" --today "$DATE"); do+ cp "insiders/bundles/${id#insider-pack-}/$id.sfpack" "$P/insider/"+ cp "insiders/bundles/${id#insider-pack-}/$id.png" "$P/insider/" 2>/dev/null || true+ python3 tools/drops/drops.py release --listing "$P/listing.json" --id "$id"+ echo "released $id"+ done+ cd "$P"+ git init -q -b packs+ git add -A+ git -c user.name="github-actions[bot]" -c user.email="41898282+github-actions[bot]@users.noreply.github.com" \+ commit -qm "Pack listing $DATE"+ git push -qf "https://x-access-token:${{ github.token }}@github.com/${{ github.repository }}" packsdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex f29c9447..fa292197 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -31,6 +31,10 @@ All notable changes to SculptForge are listed here. The format followsbuilt-in brushes do since #60: the stamp reaches its square's corners instead of being cut by the preset's roundtip (#75, reported by rodrigomoretto). At the default Focal Shift presets look as before; saved presets are unchanged.### Added+- Insider daily drops: almost every day a new alpha, brush, VDM or Kelvinlet preset, made by SculptForge's own+ procedural tools and checked on a test sculpt (too faint, seams, torn surfaces and near-duplicates are left out),+ posted to Insiders as an .sfpack. Supporters get the month's drops as one Insider Pack at month end, and everyone+ gets that pack free three months later (`tools/drops/`, `.github/workflows/insider-drop.yml`).- A new default look: new installs start in **Forge Terminal** with the **Tokyo Night** colours and the**SculptForge layout** (menus by task: File, Edit, Sculpt, Paint, Mesh, View, Render, Help, whose sections are thepalettes; a status bar; a one-row tool shelf). Existing installs keep their look and layout, and see a one-time card,diff --git a/CMakeLists.txt b/CMakeLists.txtindex a54b9989..6b8f14c0 100644--- a/CMakeLists.txt+++ b/CMakeLists.txt@@ -601,6 +601,11 @@ if(SCULPTFORGE_BUILD_TESTS)add_test(NAME release_smoke COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tests/release_smoke.py--cli ${SCULPTFORGE_CLI_RUNNER} --out ${CMAKE_CURRENT_BINARY_DIR}/release-smoke)# Proof mode results: the validator and website list tool (tools/benchmark/submit.py, docs/benchmark.md).+ # Insider daily drops (tools/drops): the generator is deterministic, the gate rejects blank, seamed, torn and+ # duplicate candidates, and every kind makes a pack that passes the install checks.+ add_test(NAME insider_drops COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/drops/drops.py selftest+ --cli ${SCULPTFORGE_CLI_RUNNER})+ set_tests_properties(insider_drops PROPERTIES TIMEOUT 300)add_test(NAME benchmark_submit COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/benchmark/submit.py selftest)add_test(NAME guide_site COMMAND ${Python3_EXECUTABLE} ${CMAKE_CURRENT_SOURCE_DIR}/tools/guide/build_site.py --check--out ${CMAKE_CURRENT_BINARY_DIR}/guide-site)diff --git a/tools/drops/drops.py b/tools/drops/drops.pynew file mode 100644index 00000000..9d9808f6--- /dev/null+++ b/tools/drops/drops.py@@ -0,0 +1,683 @@+#!/usr/bin/env python3+# SculptForge - open source digital sculpting+# SPDX-License-Identifier: GPL-3.0-or-later+"""Insider daily drops: make the day's candidates, gate them, pack the best one, post it.++ drops.py daily --date 2026-11-02 --out OUT --history H.json # OUT/<date>/: .sfpack, preview.png, drop.json+ drops.py post OUT/2026-11-02 --webhook-env DISCORD_INSIDERS_WEBHOOK+ drops.py monthly --month 2026-11 --drops DROPS_ROOT --out OUT # "Insider Pack 2026-11" for Supporters+ drops.py schedule --listing L.json --pack OUT/insider-pack-2026-11.sfpack --month 2026-11+ drops.py due --listing L.json --today 2027-03-01 # ids whose public date has come+ drops.py dryrun --start 2026-11-02 --days 14 --out ~/Work/look-mockups/drops+ drops.py selftest --cli build/sculptforge-cli # ctest: determinism, gate, pack validity++Tiers: Insiders get the daily drop, Supporters the month's bundle at month end, everyone the bundle free three+months after the month ends. Candidates come only from tools/drops/generate.py (our own procedural code).+The renders need the `sculptforge` app (--app or $SCULPTFORGE; under xvfb-run on a headless box); without it the+gate still runs every check that needs no render.+"""++import argparse+import calendar+import datetime+import json+import os+import shutil+import subprocess+import sys+import tempfile+import urllib.request+import uuid+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parent))+import generate # noqa: E402+import sfimage # noqa: E402++AUTHOR = "The SculptForge developer"+LICENSE_ID = "CC-BY-4.0"+LICENSE_TEXT = """These brushes, alphas, VDMs and presets were made by the SculptForge developer with SculptForge's own+procedural tools. They are licensed under the Creative Commons Attribution 4.0 International License+(CC BY 4.0): https://creativecommons.org/licenses/by/4.0/++You may use them in any work, commercial or not, and share or adapt them, with credit to SculptForge.+"""+FOLDER = {"alpha": ("alphas", ".png"), "brush": ("brushes", ".sfbrush"), "vdm": ("vdms", ".sfvdm"),+ "macro": ("macros", ".sfmacro")}+DUPLICATE_BITS = 10 # perceptual hashes this close (of 64 bits) count as the same drop+MIN_RANGE, MIN_STD = 0.15, 0.04+MAX_SEAM = 1.5 # tileable: the wrap-around jump against the largest jump inside+MAX_BORDER = 0.06 # stamps must fade out at their edges+MAX_CLIPPED = 0.30+MIN_RENDER_CHANGE = 0.004 # mean luminance change on the test sculpt+ROOT = Path(__file__).resolve().parents[2]+PUBLIC_DELAY_MONTHS = 3+++# --- Tools ---++def find_exe(explicit, env, names):+ cands = [explicit, os.environ.get(env)]+ for b in ("build", "build-release"):+ cands += [ROOT / b / n for n in names]+ cands += [shutil.which(n) for n in names]+ for c in cands:+ if c and Path(c).is_file():+ return str(c)+ return None+++def quote(text):+ return '"' + str(text).replace("\\", "\\\\").replace('"', '\\"') + '"'+++def run_cli(cli, command):+ r = subprocess.run([cli, "-c", command], capture_output=True, text=True, timeout=300)+ return r.returncode == 0, (r.stdout + r.stderr).strip()+++# --- Candidates on disk ---++def item_name(c):+ folder, ext = FOLDER[c["type"]]+ return f"{folder}/{c['name']}{ext}"+++def rename(c, name):+ """Gives the candidate a new name everywhere it is stored (the brush JSON, the macro header, the VDM header)."""+ old = c["name"]+ c["name"] = name+ if c["type"] == "brush":+ j = json.loads(c["data"])+ j["name"] = name+ c["data"] = (json.dumps(j, indent=2) + "\n").encode()+ elif c["type"] == "macro":+ c["data"] = c["data"].decode().replace(f"# name: {old}\n", f"# name: {name}\n", 1).encode()+ elif c["type"] == "vdm":+ import struct+ w, h, n = struct.unpack("<III", c["data"][8:20])+ c["data"] = generate.vdm_bytes(name, w, h, []) + c["data"][20 + n:]+++def write_item(c, folder):+ """Writes the candidate's file under FOLDER in the pack layout; returns its path."""+ path = Path(folder) / item_name(c)+ path.parent.mkdir(parents=True, exist_ok=True)+ if c["type"] == "alpha":+ sfimage.write_gray(path, c["grid"])+ else:+ path.write_bytes(c["data"])+ return path+++# --- Rendering on the standard test sculpt ---++CURVES = [[(-0.75, 0.42), (-0.25, 0.58), (0.25, 0.30), (0.75, 0.45)],+ [(-0.90, 0.00), (-0.30, 0.15), (0.30, -0.15), (0.90, 0.00)],+ [(-0.75, -0.45), (-0.25, -0.30), (0.25, -0.58), (0.75, -0.42)]]+++def render_setup(c, item, check=False):+ """(script, view, zoom): the candidate on the standard test sculpt; item None = the bare sculpt (baseline).+ check: the fold test's strokes (a Kelvinlet twist curls the surface over on purpose; the test grabs it instead)."""+ if c["type"] == "alpha":+ lines = ["new_plane resolution=1024"]+ if item:+ carve = "true" if c.get("kind") in ("pores", "wrinkles") else "false"+ lines += [f"brush_set_alpha path={quote(item)}",+ f"stroke brush=Standard points=\"0,0,0\" view=0,-1,0 radius=0.85 strength=0.8 invert={carve}"]+ return "; ".join(lines + ["set_material name=Clay"]), "0,-60", "2.2"+ if c["type"] == "vdm":+ lines = ["new_sphere subdivisions=8"]+ if item:+ lines += [f"vdm_set path={quote(item)}", "vdm_stamp point=0,0,0 view=0,0,-1 radius=0.7 strength=0.6"]+ return "; ".join(lines + ["set_material name=Clay"]), "30,-25", "1.6"+ lines = ["new_sphere subdivisions=8"]+ pts = [" ".join(f"{x},{y},0" for x, y in cv) for cv in CURVES]+ if item and c["type"] == "brush":+ lines.append(f"brush_load path={quote(item)}")+ lines += [f"stroke points={quote(p)} view=0,0,-1 radius=0.12 seed={i + 1}" for i, p in enumerate(pts)]+ elif item: # a Kelvinlet preset: its settings, then the Kelvinlet brush along the same curves+ lines += [ln for ln in Path(item).read_text().splitlines() if ln and not ln.startswith("#")]+ if check:+ lines.append("stroke brush=KelvinGrab points=\"-0.15,0.1,0 0.2,0.25,0\" view=0,0,-1 radius=0.4 strength=0.8 "+ "curve=false")+ else:+ lines += [f"stroke brush=KelvinTwist points={quote(pts[0])} view=0,0,-1 radius=0.3 strength=0.7",+ f"stroke brush=KelvinGrab points={quote(pts[2])} view=0,0,-1 radius=0.35 strength=0.5"]+ return "; ".join(lines + ["set_material name=Clay"]), "0,0", "1.75"+++MAX_FOLDED = 0.0001 # a torn surface folds over: at most 1 in 10,000 triangles may turn their face around+++def _face_normals(obj):+ v, normals = [], []+ with open(obj) as f:+ for line in f:+ if line.startswith("v "):+ v.append(tuple(map(float, line.split()[1:4])))+ elif line.startswith("f "):+ i = [int(t.split("/")[0]) - 1 for t in line.split()[1:4]]+ a, b, c = v[i[0]], v[i[1]], v[i[2]]+ e1 = (b[0] - a[0], b[1] - a[1], b[2] - a[2])+ e2 = (c[0] - a[0], c[1] - a[1], c[2] - a[2])+ normals.append((e1[1] * e2[2] - e1[2] * e2[1], e1[2] * e2[0] - e1[0] * e2[2], e1[0] * e2[1] - e1[1] * e2[0]))+ return normals+++def folded_fraction(cli, c, item):+ """Runs the candidate on the test sphere in sculptforge-cli; the share of triangles whose normal turned around."""+ script = render_setup(c, item, check=True)[0].rsplit("; set_material", 1)[0]+ first, rest = script.split("; ", 1)+ with tempfile.TemporaryDirectory() as t:+ before, after = Path(t) / "before.obj", Path(t) / "after.obj"+ ok, log = run_cli(cli, f"{first}; save_obj path={quote(before)}; {rest}; save_obj path={quote(after)}")+ if not ok or not after.is_file():+ return None, log[-300:]+ n0, n1 = _face_normals(before), _face_normals(after)+ if len(n0) != len(n1):+ return None, "the stroke changed the topology"+ bad = sum(1 for a, b in zip(n0, n1) if a[0] * b[0] + a[1] * b[1] + a[2] * b[2] < 0)+ return bad / max(len(n0), 1), None+++def render(app, c, item, out, size="512x384"):+ script, view, zoom = render_setup(c, item)+ out = Path(out)+ out.unlink(missing_ok=True)+ env = dict(os.environ, SDL_APP_ID=os.environ.get("SDL_APP_ID", "sculptforge-agent"))+ cmd = [app, "--render", str(out), "--size", size, "--view", view, "--zoom", zoom, "--run", script]+ r = subprocess.run(cmd, capture_output=True, text=True, timeout=300, env=env)+ if r.returncode != 0 or not out.is_file():+ return (r.stdout + r.stderr).strip()[-400:] or f"exit code {r.returncode}"+ return None+++# --- The gate ---++def check_data(c):+ """Checks that need no render. Returns (reasons to reject, measurements)."""+ reasons, m = [], {}+ if c["type"] in ("alpha", "vdm"):+ s = sfimage.stats(c["grid"])+ m.update({k: round(v, 4) for k, v in s.items()})+ if s["bad"]:+ reasons.append("broken: non-finite values")+ elif s["range"] < MIN_RANGE or s["std"] < MIN_STD:+ reasons.append(f"too faint (range {s['range']:.3f}, spread {s['std']:.3f})")+ elif s["high"] > MAX_CLIPPED or (c["tileable"] and s["low"] > MAX_CLIPPED + 0.2):+ reasons.append(f"broken: clipped (white {s['high']:.0%}, black {s['low']:.0%})")+ if not reasons and c["tileable"]:+ m["seam"] = round(sfimage.seam_ratio(c["grid"]), 3)+ if m["seam"] > MAX_SEAM:+ reasons.append(f"tiling seam ({m['seam']:.2f} x the largest inner step)")+ if not reasons and not c["tileable"]:+ m["border"] = round(sfimage.border_mean(c["grid"]), 4)+ if m["border"] > MAX_BORDER:+ reasons.append(f"hard edge: the stamp doesn't fade out (border {m['border']:.3f})")+ if c["type"] == "vdm" and not reasons:+ import struct+ w, h, n = struct.unpack("<III", c["data"][8:20])+ if len(c["data"]) != 20 + n + w * h * 12:+ reasons.append("broken: VDM size doesn't match its header")+ return reasons, m+++def gate(c, history, app=None, work=None, baselines=None, cli=None):+ """Rejects or scores one candidate. history: earlier drops' {"phash": int, ...}. Fills c["gate"]."""+ reasons, m = check_data(c)+ signature = c["grid"]+ if not reasons and cli and work and c["type"] in ("brush", "macro"):+ item = write_item(c, Path(work) / "items" / c["kind"])+ frac, err = folded_fraction(cli, c, str(item))+ if frac is None:+ reasons.append(f"broken: the test stroke failed ({err})")+ else:+ m["folded"] = round(frac, 6)+ if frac > MAX_FOLDED:+ reasons.append(f"broken: tears the surface ({frac:.2%} of triangles fold over)")+ if not reasons and app:+ item = write_item(c, Path(work) / "items" / c["kind"])+ shot = Path(work) / f"{c['kind']}.png"+ err = render(app, c, str(item), shot)+ if err:+ reasons.append(f"broken: render failed ({err.splitlines()[-1] if err else ''})")+ else:+ c["preview"] = str(shot)+ lum = sfimage.luminance(shot)+ base = baselines.get(render_setup(c, None))+ m["render_change"] = round(sfimage.mean_abs_diff(lum, base), 4) if base else 0.0+ if base and m["render_change"] < MIN_RENDER_CHANGE:+ reasons.append(f"too faint on the test sculpt (change {m['render_change']:.4f})")+ if signature is None:+ signature = lum+ if not reasons and signature is not None and c["type"] in ("alpha", "vdm"): # renders of brushes look alike+ h = sfimage.phash(signature)+ m["phash"] = f"{h:016x}"+ for d in history:+ if d.get("kind") == c["kind"] and d.get("phash") and \+ sfimage.hamming(h, int(d["phash"], 16)) <= DUPLICATE_BITS:+ reasons.append(f"near-duplicate of {d.get('date')} {d.get('name')}")+ break+ if not reasons and c["type"] in ("brush", "macro"): # no image of its own and no render: compare the numbers+ for d in history:+ if d.get("kind") == c["kind"] and d.get("params") and _param_distance(d["params"], c["params"]) < 0.05:+ reasons.append(f"near-duplicate settings of {d.get('date')} {d.get('name')}")+ break+ score = 0.0+ if not reasons:+ detail = m.get("detail", 0.02)+ score = (min(m.get("std", 0.2), 0.3) / 0.3 + min(detail, 0.06) / 0.06 ++ min(m.get("render_change", 0.02), 0.05) / 0.05)+ recent = [d.get("kind") for d in history[-7:]] # variety: a kind not seen this week wins over a nicer repeat+ score += 2.0 if c["kind"] not in recent else -1.5 * recent.count(c["kind"])+ c["gate"] = {"ok": not reasons, "reasons": reasons, "score": round(score, 3), "metrics": m}+ return c["gate"]+++def _param_distance(a, b):+ keys = [k for k in a if isinstance(a.get(k), (int, float)) and isinstance(b.get(k), (int, float))+ and not isinstance(a.get(k), bool)]+ if any(a.get(k) != b.get(k) for k in a if isinstance(a.get(k), (str, bool))):+ return 1.0+ return sum(abs(a[k] - b[k]) for k in keys) / max(1, len(keys))+++# --- Packs ---++def make_pack(cli, folder, out, pack_id, name, description):+ ok, log = run_cli(cli, f"pack_create folder={quote(folder)} path={quote(out)} id={pack_id} name={quote(name)} "+ f"version=1.0 author={quote(AUTHOR)} license={LICENSE_ID} "+ f"description={quote(description)} channel=insider")+ if not ok:+ raise RuntimeError(f"pack_create failed: {log}")+ return log+++def unique_name(c, history):+ used = {d.get("name") for d in history}+ if c["name"] in used:+ n = 2+ while f"{c['name']} {n}" in used:+ n += 1+ rename(c, f"{c['name']} {n}")+++def daily(date, out, history, app, cli, keep_rejects=None):+ """Builds the drop for DATE in OUT/<date>/ and appends it to `history`. Returns the drop or None."""+ work = Path(tempfile.mkdtemp(prefix=f"drop-{date}-"))+ try:+ baselines = {}+ if app:+ for kind_type in ("alpha", "vdm", "brush"):+ setup = render_setup({"type": kind_type}, None)+ shot = work / f"baseline-{kind_type}.png"+ if render(app, {"type": kind_type}, None, shot) is None:+ baselines[setup] = sfimage.luminance(shot)+ cands = generate.candidates(date)+ for c in cands:+ gate(c, history, app, work, baselines, cli)+ log = [{"kind": c["kind"], "name": c["name"], **c["gate"]} for c in cands]+ good = sorted((c for c in cands if c["gate"]["ok"]), key=lambda c: -c["gate"]["score"])+ day = Path(out) / date.isoformat()+ day.mkdir(parents=True, exist_ok=True)+ (day / "gate.json").write_text(json.dumps(log, indent=2) + "\n")+ if keep_rejects:+ for c in cands:+ if not c["gate"]["ok"] and c.get("preview"):+ shutil.copy(c["preview"], Path(keep_rejects) / f"{date}-rejected-{c['kind']}.png")+ if not good:+ return None+ best = good[0]+ unique_name(best, history)+ stage = work / "stage"+ write_item(best, stage)+ write_item(best, day) # the item on its own, for the month's bundle+ (stage / "LICENSE.txt").write_text(LICENSE_TEXT)+ preview = day / "preview.png"+ if best.get("preview"):+ shutil.copy(best["preview"], preview)+ shutil.copy(preview, stage / "preview.png")+ elif best["grid"] is not None:+ sfimage.write_gray(preview, sfimage.resample(best["grid"], 256))+ shutil.copy(preview, stage / "preview.png")+ pack_id = f"insider-drop-{date.isoformat()}"+ pack = day / f"{pack_id}.sfpack"+ if cli:+ make_pack(cli, stage, pack, pack_id, f"Insider Drop {date.isoformat()}", best["description"])+ drop = {"date": date.isoformat(), "kind": best["kind"], "type": best["type"], "name": best["name"],+ "description": best["description"], "item": item_name(best), "pack": pack.name if cli else None,+ "preview": preview.name if preview.is_file() else None, "phash": best["gate"]["metrics"].get("phash"),+ "params": best["params"], "score": best["gate"]["score"]}+ (day / "drop.json").write_text(json.dumps(drop, indent=2) + "\n")+ history.append(drop)+ return drop+ finally:+ shutil.rmtree(work, ignore_errors=True)+++# --- Delivery ---++def post_discord(webhook, content, files, username="SculptForge Insiders", image=None):+ """A message with attachments (multipart/form-data). files: paths."""+ embed = None+ if image:+ embed = {"image": {"url": f"attachment://{Path(image).name}"}}+ payload = {"content": content, "username": username, "allowed_mentions": {"parse": []},+ "attachments": [{"id": i, "filename": Path(f).name} for i, f in enumerate(files)]}+ if embed:+ payload["embeds"] = [embed]+ boundary = uuid.uuid4().hex+ parts = [f"--{boundary}\r\nContent-Disposition: form-data; name=\"payload_json\"\r\n"+ f"Content-Type: application/json\r\n\r\n{json.dumps(payload)}\r\n".encode()]+ for i, f in enumerate(files):+ kind = "image/png" if str(f).endswith(".png") else "application/zip"+ parts.append(f"--{boundary}\r\nContent-Disposition: form-data; name=\"files[{i}]\"; "+ f"filename=\"{Path(f).name}\"\r\nContent-Type: {kind}\r\n\r\n".encode() ++ Path(f).read_bytes() + b"\r\n")+ parts.append(f"--{boundary}--\r\n".encode())+ req = urllib.request.Request(webhook, data=b"".join(parts), method="POST",+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}",+ "User-Agent": "SculptForge-drops"})+ with urllib.request.urlopen(req, timeout=60) as r:+ return r.status+++def cmd_post(args):+ hook = os.environ.get(args.webhook_env, "")+ if not hook:+ print(f"{args.webhook_env} is not set; nothing posted.")+ return 0+ day = Path(args.drop)+ meta = json.loads((day / ("bundle.json" if (day / "bundle.json").is_file() else "drop.json")).read_text())+ files = [day / meta["preview"]] if meta.get("preview") else []+ files.append(day / meta["pack"])+ if meta.get("date"):+ kind = {"alpha": "alpha", "brush": "brush", "vdm": "VDM", "macro": "Kelvinlet preset"}[meta["type"]]+ text = (f"**Today's drop: {meta['name']}** (new {kind})\n{meta['description']}\n"+ "Install: File > Install Pack... and pick the attached .sfpack.")+ else:+ text = (f"**{meta['name']}** is here: this month's {meta['count']} Insider drops in one pack.\n"+ f"{meta['description']}\nInstall: File > Install Pack... and pick the attached .sfpack. "+ f"It goes free for everyone on {meta['publicDate']}.")+ status = post_discord(hook, text, files, image=files[0] if meta.get("preview") else None)+ print(f"posted {meta['name']}: {status}")+ return 0+++def month_drops(root, month):+ y, m = month.split("-")+ found = [(json.loads(p.read_text()), p.parent) for p in Path(root, y, m).glob("*/drop.json")]+ return sorted(found, key=lambda d: d[0]["date"])+++def public_date(month):+ y, m = map(int, month.split("-"))+ m += 1 + PUBLIC_DELAY_MONTHS # the first day after the month, plus three months+ y, m = y + (m - 1) // 12, (m - 1) % 12 + 1+ return datetime.date(y, m, 1).isoformat()+++def monthly(month, root, out, cli):+ drops = month_drops(root, month)+ if not drops:+ raise RuntimeError(f"no drops for {month} under {root}")+ stage = Path(tempfile.mkdtemp(prefix=f"bundle-{month}-"))+ try:+ seen, previews = set(), []+ for meta, folder in drops:+ src = folder / meta["item"]+ folder_name, ext = meta["item"].split("/")[0], Path(meta["item"]).suffix+ name = meta["item"]+ if name.lower() in seen: # two days with the same item name: the later one gets its date+ name = f"{folder_name}/{meta['name']} {meta['date'][5:]}{ext}"+ seen.add(name.lower())+ (stage / folder_name).mkdir(parents=True, exist_ok=True)+ shutil.copy(src, stage / name)+ if meta.get("preview"):+ previews.append(folder / meta["preview"])+ (stage / "LICENSE.txt").write_text(LICENSE_TEXT)+ if previews:+ sfimage.contact_sheet(stage / "preview.png", previews[:20], cols=5, cell=(192, 144))+ label = datetime.date(*map(int, month.split("-")), 1).strftime("%B %Y")+ counts = {}+ for meta, _ in drops:+ counts[meta["type"]] = counts.get(meta["type"], 0) + 1+ words = {"alpha": "alphas", "brush": "brushes", "vdm": "VDMs", "macro": "Kelvinlet presets"}+ desc = f"Every Insider drop from {label}: " + ", ".join(f"{n} {words[t] if n > 1 else words[t][:-1]}"+ for t, n in sorted(counts.items())) + "."+ out = Path(out)+ out.mkdir(parents=True, exist_ok=True)+ pack_id = f"insider-pack-{month}"+ pack = out / f"{pack_id}.sfpack"+ make_pack(cli, stage, pack, pack_id, f"Insider Pack {month}", desc)+ if (stage / "preview.png").is_file():+ shutil.copy(stage / "preview.png", out / f"{pack_id}.png")+ bundle = {"id": pack_id, "name": f"Insider Pack {month}", "month": month, "count": len(drops),+ "description": desc, "pack": pack.name, "preview": f"{pack_id}.png" if previews else None,+ "publicDate": public_date(month), "items": [m["name"] for m, _ in drops]}+ (out / "bundle.json").write_text(json.dumps(bundle, indent=2) + "\n")+ return bundle+ finally:+ shutil.rmtree(stage, ignore_errors=True)+++def schedule(listing, bundle):+ """Adds (or updates) the bundle in the public pack listing; `url` stays empty until its public date."""+ path = Path(listing)+ data = json.loads(path.read_text()) if path.is_file() else {"format": "sculptforge-pack-listing", "version": 1,+ "packs": []}+ entry = {k: bundle[k] for k in ("id", "name", "description", "publicDate")}+ entry["file"] = f"insider/{bundle['pack']}"+ entry["preview"] = f"insider/{bundle['preview']}" if bundle.get("preview") else None+ entry["released"] = False+ data["packs"] = [p for p in data["packs"] if p["id"] != entry["id"]] + [entry]+ data["packs"].sort(key=lambda p: p["publicDate"])+ path.write_text(json.dumps(data, indent=2) + "\n")+ return entry+++def due(listing, today):+ path = Path(listing)+ if not path.is_file():+ return []+ return [p for p in json.loads(path.read_text())["packs"] if not p["released"] and p["publicDate"] <= today]+++# --- Commands ---++def load_history(path):+ p = Path(path) if path else None+ return json.loads(p.read_text()) if p and p.is_file() else []+++def cmd_daily(args):+ app = None if args.no_render else find_exe(args.app, "SCULPTFORGE", ["sculptforge", "sculptforge.exe"])+ cli = find_exe(args.cli, "SCULPTFORGE_CLI", ["sculptforge-cli", "sculptforge-cli.exe"])+ if not cli:+ sys.exit("error: cannot find sculptforge-cli (--cli)")+ if not app and not args.no_render:+ sys.exit("error: cannot find the sculptforge app for the renders (--app, or --no-render)")+ history = load_history(args.history)+ drop = daily(generate.parse_date(args.date), args.out, history, app, cli)+ if args.history:+ Path(args.history).write_text(json.dumps(history, indent=2) + "\n")+ if not drop:+ print(f"{args.date}: every candidate was rejected; no drop today (see gate.json)")+ return 0+ print(f"{args.date}: {drop['name']} ({drop['kind']}): {drop['description']}")+ return 0+++def cmd_monthly(args):+ cli = find_exe(args.cli, "SCULPTFORGE_CLI", ["sculptforge-cli", "sculptforge-cli.exe"])+ b = monthly(args.month, args.drops, args.out, cli)+ print(f"{b['name']}: {b['count']} drops, public on {b['publicDate']}")+ return 0+++def cmd_schedule(args):+ bundle = json.loads((Path(args.bundle) / "bundle.json").read_text())+ e = schedule(args.listing, bundle)+ print(f"scheduled {e['id']} for {e['publicDate']}")+ return 0+++def cmd_due(args):+ for p in due(args.listing, args.today or datetime.date.today().isoformat()):+ print(p["id"])+ return 0+++def cmd_release(args):+ """Marks a pack released in the listing (the workflow copies its files next to the listing first)."""+ path = Path(args.listing)+ data = json.loads(path.read_text())+ for p in data["packs"]:+ if p["id"] == args.id:+ p["released"] = True+ path.write_text(json.dumps(data, indent=2) + "\n")+ return 0+++def cmd_dryrun(args):+ app = find_exe(args.app, "SCULPTFORGE", ["sculptforge", "sculptforge.exe"])+ cli = find_exe(args.cli, "SCULPTFORGE_CLI", ["sculptforge-cli", "sculptforge-cli.exe"])+ out = Path(args.out).expanduser()+ out.mkdir(parents=True, exist_ok=True)+ rejects = out / "rejected"+ rejects.mkdir(exist_ok=True)+ work = out / "build"+ history, start, rows = [], generate.parse_date(args.start), []+ for i in range(args.days):+ date = start + datetime.timedelta(days=i)+ drop = daily(date, work, history, app, cli, keep_rejects=rejects)+ if drop:+ shutil.copy(work / drop["date"] / "preview.png", out / f"{drop['date']}-{drop['kind']}.png")+ rows.append(f"{drop['date']} {drop['kind']:<9} {drop['name']}: {drop['description']}")+ else:+ rows.append(f"{date} (no drop: every candidate rejected)")+ print(rows[-1], flush=True)+ previews = sorted(out.glob("20*.png"))+ if previews:+ sfimage.contact_sheet(out / "overview.png", previews, cols=7, cell=(256, 192))+ (out / "README.txt").write_text("Insider daily drops, dry run (nothing posted).\n\n" + "\n".join(rows) + "\n")+ return 0+++def cmd_selftest(args):+ """Determinism, the gate rejecting a blank alpha, and pack validity (through sculptforge-cli's own checks)."""+ failures = []+ d = datetime.date(2026, 11, 2)+ a, b = generate.candidates(d), generate.candidates(d)+ for x, y in zip(a, b):+ bx = x["data"] if x["grid"] is None else repr(x["grid"]).encode()+ by = y["data"] if y["grid"] is None else repr(y["grid"]).encode()+ if bx != by or x["name"] != y["name"]:+ failures.append(f"not deterministic: {x['kind']}")+ if [c["name"] for c in generate.candidates(d + datetime.timedelta(days=1))] == [c["name"] for c in a]:+ failures.append("the next day gave the same candidates")+ for c in a: # the written files are byte-identical too+ with tempfile.TemporaryDirectory() as t1, tempfile.TemporaryDirectory() as t2:+ p1, p2 = write_item(c, t1), write_item(dict(c), t2)+ if p1.read_bytes() != p2.read_bytes():+ failures.append(f"file bytes differ: {c['kind']}")+ blank = {"kind": "noise", "type": "alpha", "tileable": True, "name": "Blank", "params": {},+ "grid": [[0.0] * 64 for _ in range(64)]}+ g = gate(blank, [])+ if g["ok"] or not any("faint" in r for r in g["reasons"]):+ failures.append(f"blank alpha not rejected as faint: {g}")+ flat = dict(blank, grid=[[0.5] * 64 for _ in range(64)])+ if gate(flat, [])["ok"]:+ failures.append("flat grey alpha passed")+ seam = dict(blank, grid=[[x / 63 for x in range(64)] for _ in range(64)])+ if not any("seam" in r for r in gate(seam, [])["reasons"]):+ failures.append(f"a ramp (seam at the wrap) passed: {gate(seam, [])}")+ hard = dict(blank, tileable=False, grid=[[1.0 if (x // 8 + y // 8) % 2 else 0.2 for x in range(64)] for y in range(64)])+ if gate(hard, [])["ok"]:+ failures.append("a stamp with hard edges passed")+ if args.cli:+ harsh = {"kind": "trims", "type": "brush", "tileable": False, "grid": None, "name": "Harsh", "params": {},+ "data": generate.brush_json("Harsh", "x", depth=-0.75, pinch=0.85, hardness=0.95, spacing=0.04)}+ with tempfile.TemporaryDirectory() as t:+ g = gate(harsh, [], work=t, cli=args.cli)+ if g["ok"] or not any("tears" in r for r in g["reasons"]):+ failures.append(f"a brush that tears the surface passed: {g}")+ good = generate.make("pores", d)+ if not gate(good, [])["ok"]:+ failures.append(f"a real pore alpha was rejected: {good['gate']}")+ dup = generate.make("pores", d)+ if gate(dup, [{"kind": "pores", "phash": good["gate"]["metrics"]["phash"], "date": "x", "name": "y"}])["ok"]:+ failures.append("a near-duplicate passed")+ for k in generate.KINDS: # every kind passes the data checks on some day of a week+ if not any(check_data(generate.make(k, d + datetime.timedelta(days=i)))[0] == [] for i in range(7)):+ failures.append(f"{k}: rejected every day of a week")+ if args.cli:+ with tempfile.TemporaryDirectory() as t:+ for c in a + [generate.make(k, d) for k in ("kelvinlet", "vdm", "trims")]:+ stage = Path(t) / c["kind"]+ write_item(c, stage)+ (stage / "LICENSE.txt").write_text(LICENSE_TEXT)+ try:+ make_pack(args.cli, stage, Path(t) / f"{c['kind']}.sfpack", f"insider-drop-test-{c['kind']}",+ "Insider Drop test", c["description"])+ except RuntimeError as e:+ failures.append(f"{c['kind']}: {e}")+ if (public_date("2026-11"), public_date("2026-12")) != ("2027-03-01", "2027-04-01"):+ failures.append(f"public dates: {public_date('2026-11')}, {public_date('2026-12')}")+ for f in failures:+ print("FAIL", f)+ print("drops selftest:", "FAILED" if failures else "ok")+ return 1 if failures else 0+++def main():+ p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ sub = p.add_subparsers(dest="cmd", required=True)+ s = sub.add_parser("daily")+ s.add_argument("--date", default=datetime.date.today().isoformat())+ s.add_argument("--out", required=True)+ s.add_argument("--history", help="history.json of earlier drops (read and updated)")+ s.add_argument("--app")+ s.add_argument("--cli")+ s.add_argument("--no-render", action="store_true")+ s.set_defaults(fn=cmd_daily)+ s = sub.add_parser("post")+ s.add_argument("drop", help="a day's folder (drop.json) or a bundle folder (bundle.json)")+ s.add_argument("--webhook-env", default="DISCORD_INSIDERS_WEBHOOK")+ s.set_defaults(fn=cmd_post)+ s = sub.add_parser("monthly")+ s.add_argument("--month", required=True)+ s.add_argument("--drops", required=True, help="the drops/ folder (drops/YYYY/MM/<date>/drop.json)")+ s.add_argument("--out", required=True)+ s.add_argument("--cli")+ s.set_defaults(fn=cmd_monthly)+ s = sub.add_parser("schedule")+ s.add_argument("--listing", required=True)+ s.add_argument("--bundle", required=True, help="the monthly output folder (bundle.json)")+ s.set_defaults(fn=cmd_schedule)+ s = sub.add_parser("due")+ s.add_argument("--listing", required=True)+ s.add_argument("--today")+ s.set_defaults(fn=cmd_due)+ s = sub.add_parser("release")+ s.add_argument("--listing", required=True)+ s.add_argument("--id", required=True)+ s.set_defaults(fn=cmd_release)+ s = sub.add_parser("dryrun")+ s.add_argument("--start", required=True)+ s.add_argument("--days", type=int, default=14)+ s.add_argument("--out", required=True)+ s.add_argument("--app")+ s.add_argument("--cli")+ s.set_defaults(fn=cmd_dryrun)+ s = sub.add_parser("selftest")+ s.add_argument("--cli")+ s.set_defaults(fn=cmd_selftest)+ args = p.parse_args()+ return args.fn(args)+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tools/drops/generate.py b/tools/drops/generate.pynew file mode 100644index 00000000..0f61a6d8--- /dev/null+++ b/tools/drops/generate.py@@ -0,0 +1,514 @@+# SculptForge - open source digital sculpting+# SPDX-License-Identifier: GPL-3.0-or-later+"""Candidate generators for the Insider daily drops.++Everything here is made from scratch by our own procedural code: tileable noise, scales, fabric weaves and skin+pores, wrinkle and trim stamps, hard-surface trim brushes, Kelvinlet clay presets and vector displacement maps+captured from procedural shapes. No third-party images or other apps' output go in.++`candidates(date)` is seeded by the date alone, so the same date always gives byte-identical files.+"""++import datetime+import hashlib+import json+import math+import random+import struct++import sfimage++ALPHA_SIZE = 512+VDM_SIZE = 192+KINDS = ["noise", "scales", "weave", "pores", "wrinkles", "trims", "kelvinlet", "vdm"]+PER_DAY = 6 # candidates per day; the gate keeps one+++def seed_for(date, salt=""):+ return int.from_bytes(hashlib.sha256(f"sculptforge-drop:{date.isoformat()}:{salt}".encode()).digest()[:8], "big")+++# --- Tileable building blocks (period divides the image, so every map wraps) ---++def _smooth(t):+ return t * t * t * (t * (t * 6 - 15) + 10)+++def value_noise(rng, size, period):+ lat = [[rng.random() for _ in range(period)] for _ in range(period)]+ idx, frac = [], []+ for x in range(size):+ p = x * period / size+ i = int(p)+ idx.append((i % period, (i + 1) % period))+ frac.append(_smooth(p - i))+ out = []+ for y in range(size):+ (j0, j1), fy = idx[y], frac[y]+ r0, r1 = lat[j0], lat[j1]+ row = []+ for x in range(size):+ (i0, i1), fx = idx[x], frac[x]+ a = r0[i0] + (r0[i1] - r0[i0]) * fx+ b = r1[i0] + (r1[i1] - r1[i0]) * fx+ row.append(a + (b - a) * fy)+ out.append(row)+ return out+++def fbm(rng, size, period, octaves, gain=0.5, mode="plain"):+ total = [[0.0] * size for _ in range(size)]+ amp, norm = 1.0, 0.0+ for o in range(octaves):+ n = value_noise(rng, size, period << o)+ for y in range(size):+ t, s = total[y], n[y]+ for x in range(size):+ v = s[x]+ if mode == "ridged":+ v = 1.0 - abs(2.0 * v - 1.0)+ v *= v+ elif mode == "billow":+ v = abs(2.0 * v - 1.0)+ t[x] += v * amp+ norm += amp+ amp *= gain+ return [[v / norm for v in row] for row in total]+++def worley(rng, size, cells, jitter=0.9):+ """F1 and F2 distances (in cell units) to jittered points on a cells x cells wrapping grid."""+ pts = [[(0.5 + (rng.random() - 0.5) * jitter, 0.5 + (rng.random() - 0.5) * jitter) for _ in range(cells)]+ for _ in range(cells)]+ f1 = [[0.0] * size for _ in range(size)]+ f2 = [[0.0] * size for _ in range(size)]+ ids = [[0] * size for _ in range(size)]+ s = cells / size+ for y in range(size):+ py = (y + 0.5) * s+ cy = int(py)+ for x in range(size):+ px = (x + 0.5) * s+ cx = int(px)+ d1 = d2 = 9.0+ best = 0+ for oy in (-1, 0, 1):+ gy = cy + oy+ row = pts[gy % cells]+ for ox in (-1, 0, 1):+ gx = cx + ox+ qx, qy = row[gx % cells]+ dx, dy = gx + qx - px, gy + qy - py+ d = dx * dx + dy * dy+ if d < d1:+ d2, d1, best = d1, d, (gy % cells) * cells + gx % cells+ elif d < d2:+ d2 = d+ f1[y][x], f2[y][x], ids[y][x] = math.sqrt(d1), math.sqrt(d2), best+ return f1, f2, ids+++def normalize(grid, lo_pct=0.01, hi_pct=0.99):+ vals = sorted(v for row in grid for v in row)+ lo, hi = vals[int(lo_pct * (len(vals) - 1))], vals[int(hi_pct * (len(vals) - 1))]+ k = 1.0 / max(hi - lo, 1e-6)+ return [[min(1.0, max(0.0, (v - lo) * k)) for v in row] for row in grid]+++def window(size, inner=0.55):+ """Radial falloff: 1 inside `inner`, smooth to 0 at the square's inscribed circle (a stamp fades out)."""+ out = []+ for y in range(size):+ v = (y + 0.5) / size * 2 - 1+ row = []+ for x in range(size):+ u = (x + 0.5) / size * 2 - 1+ r = math.sqrt(u * u + v * v)+ t = min(1.0, max(0.0, (r - inner) / (0.98 - inner)))+ row.append(1.0 - t * t * (3 - 2 * t))+ out.append(row)+ return out+++def mul(a, b):+ return [[x * y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]+++# --- Names and words ---++def pick(rng, items):+ return items[rng.randrange(len(items))]+++# --- Kinds ---++def make_noise(rng, size):+ variant = pick(rng, ["cloud", "ridged", "billow", "warped", "grain"])+ period = pick(rng, [2, 4, 4, 8])+ octaves = rng.randint(4, 6)+ if variant == "cloud":+ g = fbm(rng, size, period, octaves, 0.55)+ name, use = pick(rng, ["Soft Cloud", "Rolling Mist", "Clay Cloud"]), "breaking up large, smooth forms"+ elif variant == "ridged":+ g = fbm(rng, size, period, octaves, 0.5, "ridged")+ name, use = pick(rng, ["Ridged Stone", "Vein Rock", "Ridge Field"]), "rock veins and eroded ridges"+ elif variant == "billow":+ g = fbm(rng, size, period, octaves, 0.5, "billow")+ name, use = pick(rng, ["Billow Lumps", "Pitted Crust", "Lumpy Plaster"]), "pitted, lumpy plaster and crusts"+ elif variant == "warped":+ base = fbm(rng, size, period, octaves, 0.5)+ warp = fbm(rng, size, period, 3, 0.5)+ amt = rng.uniform(0.04, 0.12) * size+ g = [[base[int(y + (warp[y][x] - 0.5) * amt) % size][int(x + (warp[(y + size // 3) % size][x] - 0.5) * amt) % size]+ for x in range(size)] for y in range(size)]+ name, use = pick(rng, ["Warped Flow", "Swirl Grain", "Molten Drift"]), "flowing, molten or wind-worn surfaces"+ else:+ g = fbm(rng, size, period * 4, 3, 0.7)+ name, use = pick(rng, ["Fine Grain", "Sand Grain", "Stipple Grain"]), "fine grain on stone, sand or cast metal"+ return {"type": "alpha", "tileable": True, "grid": normalize(g), "name": f"{name} Noise",+ "description": f"Tileable noise alpha for {use}; use with Drag Stamp or Spray.", "params": {"variant": variant}}+++def make_scales(rng, size):+ variant = pick(rng, ["dome", "plate", "shingle"])+ cells = pick(rng, [6, 8, 10, 12, 16])+ if variant == "shingle":+ rows = cells+ g = []+ for y in range(size):+ fy = (y + 0.5) / size * rows+ j = int(fy)+ row = []+ for x in range(size):+ best = 0.0+ for dj in (0, 1): # a scale from this row or the one overlapping from below+ jj = j + dj+ off = 0.5 * (jj % 2)+ fx = (x + 0.5) / size * cells + off+ cx = math.floor(fx) + 0.5+ dx, dy = (fx - cx) * 2, (fy - jj) * 2 + 0.2+ r = math.sqrt(dx * dx + dy * dy)+ if r < 1.15:+ best = max(best, (1 - r / 1.15) ** 0.6 * (0.55 + 0.45 * (fy - j + dj * 0)))+ row.append(best)+ g.append(row)+ name, use = pick(rng, ["Fish Scales", "Overlap Scales", "Shingle Scales"]), "fish, snake bellies and armour"+ else:+ f1, f2, _ = worley(rng, size, cells, 0.8)+ if variant == "dome":+ g = [[max(0.0, 1 - a * 1.4) ** 0.7 for a in row] for row in f1]+ name, use = pick(rng, ["Round Scales", "Pebble Scales", "Bead Scales"]), "lizard skin and beaded hides"+ else:+ g = [[min(1.0, (b - a) * 3.0) ** 0.5 for a, b in zip(r1, r2)] for r1, r2 in zip(f1, f2)]+ name, use = pick(rng, ["Plate Scales", "Croc Plates", "Tile Hide"]), "crocodile plates and armoured hide"+ detail = fbm(rng, size, 8, 2)+ g = [[v * (0.9 + 0.1 * d) for v, d in zip(r, dr)] for r, dr in zip(g, detail)]+ return {"type": "alpha", "tileable": True, "grid": normalize(g), "name": name,+ "description": f"Tileable scale alpha for {use}; {cells} scales across.", "params": {"variant": variant, "cells": cells}}+++WEAVES = { # over/under matrices (1 = warp over weft), one repeat+ "Plain": [[1, 0], [0, 1]],+ "Twill": [[1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 1, 1], [1, 0, 0, 1]],+ "Basket": [[1, 1, 0, 0], [1, 1, 0, 0], [0, 0, 1, 1], [0, 0, 1, 1]],+ "Satin": [[1, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 1], [0, 1, 0, 0, 0], [0, 0, 0, 1, 0]],+ "Herringbone": [[1, 1, 0, 0, 0, 0, 1, 1], [0, 1, 1, 0, 0, 1, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0], [1, 0, 0, 1, 1, 0, 0, 1]],+}+++def make_weave(rng, size):+ kind = pick(rng, list(WEAVES))+ pat = WEAVES[kind]+ ph, pw = len(pat), len(pat[0])+ reps = pick(rng, [2, 3, 4, 6, 8])+ tx, ty = pw * reps, ph * reps * (pw // ph if pw > ph else 1)+ gap = rng.uniform(0.08, 0.2)+ fibre = fbm(rng, size, 16, 2)+ g = []+ for y in range(size):+ fy = (y + 0.5) / size * ty+ j = int(fy)+ ly = fy - j+ row = []+ for x in range(size):+ fx = (x + 0.5) / size * tx+ i = int(fx)+ lx = fx - i+ over = pat[j % ph][i % pw]+ across, along = (lx, ly) if over else (ly, lx) # the top thread's profile and length+ if across < gap / 2 or across > 1 - gap / 2:+ h = 0.15+ else:+ a = (across - gap / 2) / (1 - gap)+ h = 0.35 + 0.65 * math.sin(math.pi * a) ** 0.6 * (0.75 + 0.25 * math.sin(math.pi * along))+ row.append(h * (0.92 + 0.08 * fibre[y][x]))+ g.append(row)+ return {"type": "alpha", "tileable": True, "grid": normalize(g), "name": f"{kind} Weave {tx}",+ "description": f"Tileable {kind.lower()} weave alpha for cloth, straps and sacking; {tx} threads across.",+ "params": {"weave": kind, "threads": tx}}+++def make_pores(rng, size):+ cells = pick(rng, [24, 32, 40, 48])+ f1, _, ids = worley(rng, size, cells, 1.0)+ rad = rng.uniform(0.18, 0.3)+ skin = fbm(rng, size, 8, 4, 0.55)+ creases = rng.random() < 0.5+ g = []+ for y in range(size):+ row = []+ for x in range(size):+ d = f1[y][x]+ r = rad * (0.6 + 0.8 * ((ids[y][x] * 2654435761 % 1000) / 1000.0))+ pore = max(0.0, 1 - d / r) ** 1.5+ v = 0.25 * skin[y][x] + 0.75 * pore+ if creases:+ v += 0.15 * max(0.0, 1 - abs(skin[y][x] - 0.5) * 30)+ row.append(v)+ g.append(row)+ which = pick(rng, ["Fine", "Cheek", "Nose", "Back"]) if cells >= 32 else pick(rng, ["Coarse", "Orange Peel"])+ extra = " and fine creases" if creases else ""+ return {"type": "alpha", "tileable": True, "grid": normalize(g), "name": f"{which} Pores",+ "description": f"Tileable skin pore alpha{extra}; carve with low strength on faces and hands.",+ "params": {"cells": cells, "creases": creases}}+++def make_wrinkles(rng, size):+ variant = pick(rng, ["forehead", "crow", "knuckle"])+ lines = rng.randint(3, 7)+ width = rng.uniform(0.012, 0.03)+ g = [[0.0] * size for _ in range(size)]+ if variant == "crow":+ spread = rng.uniform(0.9, 1.6)+ base = [(-spread / 2 + spread * (k + rng.uniform(-0.25, 0.25)) / max(1, lines - 1), rng.uniform(0.5, 0.95),+ rng.uniform(0.02, 0.08), rng.uniform(3, 7)) for k in range(lines)]+ for y in range(size):+ v = (y + 0.5) / size * 2 - 1+ for x in range(size):+ u = (x + 0.5) / size * 2 - 1 + 0.9 # fan out from the left edge+ r = math.hypot(u, v)+ th = math.atan2(v, u)+ best = 0.0+ for th0, length, wob, fr in base:+ if r > length * 1.8:+ continue+ d = abs(th - th0 - wob * math.sin(fr * r)) * r+ w = width * (1.2 - r / (length * 1.8))+ if w > 0:+ best = max(best, math.exp(-(d / w) ** 2) * min(1.0, r * 4))+ g[y][x] = best+ name, use = "Crow's Feet Wrinkles", "eye corners and fanned creases"+ else:+ rows = [(-0.6 + 1.2 * (k + 0.5) / lines + rng.uniform(-0.05, 0.05), rng.uniform(0.02, 0.07),+ rng.uniform(2, 5), rng.uniform(0, 6.28), rng.uniform(0.5, 1.0)) for k in range(lines)]+ if variant == "knuckle":+ rows = [(y0, a * 2, f, p, s) for y0, a, f, p, s in rows]+ for y in range(size):+ v = (y + 0.5) / size * 2 - 1+ for x in range(size):+ u = (x + 0.5) / size * 2 - 1+ best = 0.0+ for y0, amp, fr, ph, strength in rows:+ c = y0 + amp * math.sin(fr * u + ph) * (1 + (0.5 * abs(u) if variant == "knuckle" else 0))+ slope = amp * fr * math.cos(fr * u + ph)+ d = abs(v - c) / math.sqrt(1 + slope * slope)+ taper = max(0.0, 1 - (u / 0.9) ** 2)+ best = max(best, strength * taper * math.exp(-(d / width) ** 2))+ g[y][x] = best+ name = "Forehead Wrinkles" if variant == "forehead" else "Knuckle Folds"+ use = "foreheads and long skin creases" if variant == "forehead" else "knuckles, elbows and bunched skin"+ g = mul(g, window(size, 0.5))+ return {"type": "alpha", "tileable": False, "grid": normalize(g, 0.0, 0.999), "name": f"{name} {lines}",+ "description": f"Wrinkle stamp alpha with {lines} creases for {use}; carve with Drag Stamp or a short stroke.",+ "params": {"variant": variant, "lines": lines}}+++def brush_json(name, description, **k):+ r = {"name": name, "description": description, "direction": "normal", "depth": 0.5, "plane": "none",+ "planeAmount": 0.5, "pinch": 0.0, "drag": 0.0, "smooth": 0.0, "hardness": 0.0, "tipSharpness": 0.0,+ "pattern": "none", "patternScale": 0.3, "patternAmount": 0.0, "spacing": 0.15, "jitter": 0.0,+ "pressureCurve": 1.0, "frontFacesOnly": False, "cavityMask": 0.0}+ r.update({key: round(v, 3) if isinstance(v, float) else v for key, v in k.items()})+ r.update({"author": "The SculptForge developer", "format": "sfbrush", "version": 1})+ return (json.dumps(r, indent=2) + "\n").encode()+++def make_trims(rng, size):+ if rng.random() < 0.55: # a hard-surface trim brush+ variant = pick(rng, ["panel", "seam", "bevel", "groove", "weld"])+ u = rng.uniform+ if variant == "panel":+ name, desc = "Panel Cut", "Cuts a crisp, narrow panel line into hard surfaces."+ p = dict(depth=-u(0.25, 0.45), pinch=u(0.3, 0.55), hardness=u(0.6, 0.8), spacing=u(0.05, 0.08))+ elif variant == "seam":+ name, desc = "Raised Seam", "Builds a raised, flat-topped seam along panel edges."+ p = dict(depth=u(0.25, 0.45), plane="flatten", planeAmount=u(0.6, 0.9), pinch=u(0.15, 0.4),+ hardness=u(0.6, 0.8), spacing=u(0.05, 0.1))+ elif variant == "bevel":+ name, desc = "Bevel Trim", "Flattens a hard edge into a narrow bevel; work along the edge."+ p = dict(depth=u(0.1, 0.3), plane="flatten", planeAmount=u(0.8, 1.0), hardness=u(0.85, 1.0),+ frontFacesOnly=True, spacing=u(0.06, 0.12))+ elif variant == "groove":+ name, desc = "Scraped Groove", "Scrapes a flat-bottomed groove for trims and inset strips."+ p = dict(depth=-u(0.25, 0.45), plane="scrape", planeAmount=u(0.6, 0.9), hardness=u(0.6, 0.85),+ spacing=u(0.05, 0.1))+ else:+ name, desc = "Weld Bead", "Lays a rippled weld bead along joins."+ p = dict(depth=u(0.4, 0.7), pinch=u(0.1, 0.3), pattern="ridges", patternScale=u(0.2, 0.4),+ patternAmount=u(0.4, 0.7), hardness=u(0.5, 0.7), spacing=u(0.08, 0.15))+ name = f"{name} {rng.randint(2, 9)}"+ return {"type": "brush", "tileable": False, "grid": None, "name": name, "description": desc,+ "data": brush_json(name, desc, **p), "params": {"variant": variant, **{k: v for k, v in p.items()}}}+ variant = pick(rng, ["rivets", "vents", "bolts"])+ g = [[0.0] * size for _ in range(size)]+ if variant == "rivets":+ n = rng.randint(4, 9)+ rr = rng.uniform(0.04, 0.07)+ rows = pick(rng, [1, 2])+ centers = [(-0.75 + 1.5 * i / (n - 1), (r - (rows - 1) / 2) * 0.3) for i in range(n) for r in range(rows)]+ name, use = f"Rivet Strip {n * rows}", "plating seams and armour edges"+ elif variant == "vents":+ n = rng.randint(3, 7)+ centers, rr = None, 0+ name, use = f"Vent Slots {n}", "intakes, grilles and machine housings"+ else:+ n = pick(rng, [4, 6])+ rr = rng.uniform(0.07, 0.1)+ centers = [(0.6 * math.cos(2 * math.pi * k / n), 0.6 * math.sin(2 * math.pi * k / n)) for k in range(n)]+ name, use = f"Hex Bolt Ring {n}", "flanges, hatches and wheel hubs"+ for y in range(size):+ v = (y + 0.5) / size * 2 - 1+ for x in range(size):+ u = (x + 0.5) / size * 2 - 1+ if variant == "vents":+ pitch = 1.4 / n+ k = round((v + 0.7 - pitch / 2) / pitch)+ cy = -0.7 + pitch / 2 + k * pitch+ if 0 <= k < n and abs(u) < 0.65:+ d = abs(v - cy) / (pitch * 0.3)+ end = max(0.0, (abs(u) - 0.55) / 0.1)+ g[y][x] = max(0.0, 1 - max(d, end) ** 4) if max(d, end) < 1 else 0.0+ continue+ best = 0.0+ for cx, cy in centers:+ dx, dy = u - cx, v - cy+ if variant == "bolts": # a hexagon: the largest of three projections+ d = max(abs(dx), abs(dx * 0.5 + dy * 0.866), abs(dx * 0.5 - dy * 0.866)) / rr+ best = max(best, 1.0 if d < 0.7 else max(0.0, (1 - d) / 0.3) if d < 1 else 0.0)+ else:+ d = math.hypot(dx, dy) / rr+ if d < 1:+ best = max(best, math.sqrt(1 - d * d))+ g[y][x] = best+ g = mul(g, window(size, 0.8))+ return {"type": "alpha", "tileable": False, "grid": g, "name": name,+ "description": f"Hard-surface trim alpha for {use}; stamp it with Drag Stamp.", "params": {"variant": variant}}+++def make_kelvinlet(rng, size):+ feel = pick(rng, [("Soft Clay", 0.2, 0.45, 0.0, 0.15), ("Firm Clay", 0.55, 0.75, 0.1, 0.3),+ ("Wet Clay", 0.85, 1.0, 0.0, 0.1), ("Rubber Clay", 0.0, 0.2, 0.2, 0.45),+ ("Stiff Wax", 0.6, 0.85, 0.5, 0.8)])+ label, s0, s1, h0, h1 = feel+ squash, sharp = round(rng.uniform(s0, s1), 2), round(rng.uniform(h0, h1), 2)+ spacing = round(rng.uniform(0.6, 1.4), 2)+ bulge = "bulges like real clay" if squash > 0.6 else "stays springy" if squash < 0.3 else "holds its volume"+ name = f"Kelvinlet {label}"+ desc = f"Kelvinlet brush preset: Squash {round(squash * 100)}, Sharpness {round(sharp * 100)}; the surface {bulge}."+ text = (f"# name: {name}\n# description: {desc}\n"+ f"kelvinlet_settings squash={squash:g} sharpness={sharp:g} clone_spacing={spacing:g}\n")+ return {"type": "macro", "tileable": False, "grid": None, "name": name, "description": desc,+ "data": text.encode(), "params": {"squash": squash, "sharpness": sharp, "clone_spacing": spacing}}+++def vdm_bytes(name, w, h, vecs):+ nb = name.encode()+ head = b"SFVDM1\n\0" + struct.pack("<III", w, h, len(nb)) + nb+ return head + struct.pack(f"<{len(vecs)}f", *vecs)+++def make_vdm(rng, size):+ """A procedural shape over the flat square; each texel's displacement (in brush radii) is captured as a VDM."""+ variant = pick(rng, ["claw", "twist", "lip", "knot", "sucker"])+ height = rng.uniform(0.5, 1.1)+ bend = rng.uniform(0.2, 0.6) * pick(rng, [-1, 1])+ twist = rng.uniform(1.5, 4.0)+ turns = rng.randint(3, 6)+ vecs, sig = [], []+ for y in range(size):+ v = 1 - (y + 0.5) / size * 2 # row 0 at the top (+v)+ srow = []+ for x in range(size):+ u = (x + 0.5) / size * 2 - 1+ r = math.hypot(u, v)+ t = max(0.0, 1 - r / 0.9)+ fade = t * t * (3 - 2 * t)+ dx = dy = dz = 0.0+ if variant == "claw": # a horn that hooks over: the tip moves sideways as it rises+ z = height * fade ** 1.6+ dz, dy = z, bend * (z / height) ** 2 * height+ dx, dy = -u * 0.3 * fade, dy - v * 0.3 * fade+ elif variant == "twist": # a spike twisted around its axis+ z = height * fade ** 2+ a = twist * fade+ ca, sa = math.cos(a) - 1, math.sin(a)+ dx, dy, dz = (u * ca - v * sa) * (1 - fade), (u * sa + v * ca) * (1 - fade), z+ elif variant == "lip": # a ridge whose top curls over (an overhanging lip)+ band = max(0.0, 1 - abs(v) / 0.35) * max(0.0, 1 - (u / 0.9) ** 4)+ b = band * band * (3 - 2 * band)+ dz = height * 0.7 * b+ dy = bend * b ** 2+ elif variant == "knot": # a lumpy knot: a dome with radial lobes+ lobes = 1 + 0.35 * math.cos(turns * math.atan2(v, u))+ z = height * 0.6 * fade ** 1.2 * lobes+ dz = z+ dx, dy = u * 0.15 * fade, v * 0.15 * fade+ else: # a sucker: a raised ring with a cupped centre+ ring = math.exp(-((r - 0.45) / 0.15) ** 2)+ cup = -0.35 * math.exp(-(r / 0.25) ** 2)+ dz = height * 0.5 * (ring + cup) * (1 if r < 0.9 else 0)+ dx, dy = -u * 0.1 * ring, -v * 0.1 * ring+ vecs += [dx, dy, dz]+ srow.append(math.sqrt(dx * dx + dy * dy + dz * dz))+ sig.append(srow)+ m = max(max(r) for r in sig) or 1.0+ names = {"claw": "Hooked Claw", "twist": "Twisted Spike", "lip": "Curled Lip", "knot": "Burl Knot",+ "sucker": "Sucker Cup"}+ uses = {"claw": "claws, thorns and hooked horns", "twist": "twisted horns and spiral spines",+ "lip": "overhanging brows, ledges and rolled rims", "knot": "tree burls and lumpy growths",+ "sucker": "tentacle suckers and pocked organic forms"}+ name = f"{names[variant]} {rng.randint(2, 9)}"+ return {"type": "vdm", "tileable": False, "grid": [[s / m for s in row] for row in sig], "name": name,+ "description": f"Vector displacement stamp for {uses[variant]}; drag it out on the surface.",+ "data": vdm_bytes(name, size, size, vecs),+ "params": {"variant": variant, "height": round(height, 3), "bend": round(bend, 3)}}+++MAKERS = {"noise": make_noise, "scales": make_scales, "weave": make_weave, "pores": make_pores,+ "wrinkles": make_wrinkles, "trims": make_trims, "kelvinlet": make_kelvinlet, "vdm": make_vdm}+++def kinds_for(date):+ """The day's candidate kinds: a shuffled rotation, so every kind comes up about equally often."""+ rng = random.Random(seed_for(date, "kinds"))+ kinds = KINDS[:]+ rng.shuffle(kinds)+ return kinds[:PER_DAY]+++def make(kind, date, index=0):+ """One candidate: deterministic for (kind, date, index)."""+ rng = random.Random(seed_for(date, f"{kind}:{index}"))+ size = VDM_SIZE if kind == "vdm" else ALPHA_SIZE+ c = MAKERS[kind](rng, size)+ c["kind"] = kind+ c["date"] = date.isoformat()+ return c+++def candidates(date):+ return [make(k, date) for k in kinds_for(date)]+++def parse_date(text):+ return datetime.date.fromisoformat(text)diff --git a/tools/drops/sfimage.py b/tools/drops/sfimage.pynew file mode 100644index 00000000..e3dbddd6--- /dev/null+++ b/tools/drops/sfimage.py@@ -0,0 +1,187 @@+# SculptForge - open source digital sculpting+# SPDX-License-Identifier: GPL-3.0-or-later+"""Small image helpers for the daily drops, standard library only.++A grid is a list of rows of floats (0..1, row 0 at the top). PNGs are 8-bit gray, RGB or RGBA,+non-interlaced: what the generator writes and `sculptforge --render` produces.+"""++import math+import struct+import zlib+++# --- PNG ---++def _chunk(kind, data):+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)+++def write_png(path, rows, channels=1):+ """rows: lists of 0..255 ints (channels interleaved). Deterministic bytes for the same pixels."""+ h = len(rows)+ w = len(rows[0]) // channels+ color = {1: 0, 3: 2, 4: 6}[channels]+ raw = b"".join(b"\x00" + bytes(r) for r in rows)+ data = (b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, color, 0, 0, 0)) ++ _chunk(b"IDAT", zlib.compress(raw, 9)) + _chunk(b"IEND", b""))+ with open(path, "wb") as f:+ f.write(data)+++def write_gray(path, grid):+ write_png(path, [[max(0, min(255, int(round(v * 255)))) for v in row] for row in grid], 1)+++def read_png(path):+ """(width, height, channels, rows of ints). Raises ValueError on anything but 8-bit, non-interlaced."""+ with open(path, "rb") as f:+ data = f.read()+ if data[:8] != b"\x89PNG\r\n\x1a\n":+ raise ValueError(f"{path}: not a PNG")+ pos, idat, w = 8, [], 0+ while pos < len(data):+ n, kind = struct.unpack(">I4s", data[pos:pos + 8])+ body = data[pos + 8:pos + 8 + n]+ pos += 12 + n+ if kind == b"IHDR":+ w, h, depth, color, _, _, interlace = struct.unpack(">IIBBBBB", body)+ if depth != 8 or interlace or color not in (0, 2, 4, 6):+ raise ValueError(f"{path}: unsupported PNG (depth {depth}, colour {color}, interlace {interlace})")+ ch = {0: 1, 2: 3, 4: 2, 6: 4}[color]+ elif kind == b"IDAT":+ idat.append(body)+ elif kind == b"IEND":+ break+ if not w:+ raise ValueError(f"{path}: no IHDR")+ raw = zlib.decompress(b"".join(idat))+ stride = w * ch+ rows, prev = [], bytearray(stride)+ for y in range(h):+ ft = raw[y * (stride + 1)]+ line = bytearray(raw[y * (stride + 1) + 1:(y + 1) * (stride + 1)])+ if ft == 1:+ for i in range(ch, stride):+ line[i] = (line[i] + line[i - ch]) & 255+ elif ft == 2:+ for i in range(stride):+ line[i] = (line[i] + prev[i]) & 255+ elif ft == 3:+ for i in range(stride):+ left = line[i - ch] if i >= ch else 0+ line[i] = (line[i] + ((left + prev[i]) >> 1)) & 255+ elif ft == 4:+ for i in range(stride):+ a = line[i - ch] if i >= ch else 0+ b = prev[i]+ c = prev[i - ch] if i >= ch else 0+ p = a + b - c+ pa, pb, pc = abs(p - a), abs(p - b), abs(p - c)+ line[i] = (line[i] + (a if pa <= pb and pa <= pc else b if pb <= pc else c)) & 255+ rows.append(line)+ prev = line+ return w, h, ch, rows+++def luminance(path):+ """A PNG as a gray grid 0..1."""+ w, h, ch, rows = read_png(path)+ if ch < 3:+ return [[row[x * ch] / 255.0 for x in range(w)] for row in rows]+ return [[(0.299 * row[x * ch] + 0.587 * row[x * ch + 1] + 0.114 * row[x * ch + 2]) / 255.0 for x in range(w)]+ for row in rows]+++def contact_sheet(path, images, cols=4, cell=(256, 192), pad=8, bg=(24, 26, 32)):+ """Tiles PNG files (nearest-neighbour scaled to `cell`) into one RGB PNG."""+ cw, chh = cell+ n = max(1, len(images))+ rows_n = (n + cols - 1) // cols+ W, H = cols * cw + (cols + 1) * pad, rows_n * chh + (rows_n + 1) * pad+ out = [bytearray(bg * W) for _ in range(H)]+ for i, p in enumerate(images):+ w, h, ch, rows = read_png(p)+ ox, oy = pad + (i % cols) * (cw + pad), pad + (i // cols) * (chh + pad)+ for y in range(chh):+ src = rows[y * h // chh]+ dst = out[oy + y]+ for x in range(cw):+ s = (x * w // cw) * ch+ rgb = (src[s],) * 3 if ch < 3 else (src[s], src[s + 1], src[s + 2])+ d = (ox + x) * 3+ dst[d:d + 3] = bytes(rgb)+ write_png(path, out, 3)+++# --- Measurements ---++def resample(grid, n):+ """Box-filtered n x n copy."""+ h, w = len(grid), len(grid[0])+ out = []+ for j in range(n):+ y0, y1 = j * h // n, max(j * h // n + 1, (j + 1) * h // n)+ row = []+ for i in range(n):+ x0, x1 = i * w // n, max(i * w // n + 1, (i + 1) * w // n)+ s = sum(sum(grid[y][x0:x1]) for y in range(y0, y1))+ row.append(s / ((y1 - y0) * (x1 - x0)))+ out.append(row)+ return out+++def phash(grid):+ """64-bit perceptual hash: the sign of the low 8 x 8 DCT terms of a 32 x 32 copy against their median."""+ n = 32+ g = resample(grid, n)+ cos = [[math.cos(math.pi * (2 * x + 1) * u / (2 * n)) for x in range(n)] for u in range(8)]+ rows = [[sum(g[y][x] * cos[u][x] for x in range(n)) for u in range(8)] for y in range(n)]+ coef = [sum(rows[y][u] * cos[v][y] for y in range(n)) for v in range(8) for u in range(8)]+ ac = coef[1:]+ med = sorted(ac)[len(ac) // 2]+ bits = 0+ for c in ac:+ bits = (bits << 1) | (1 if c > med else 0)+ return bits+++def hamming(a, b):+ return bin(a ^ b).count("1")+++def stats(grid):+ """Range, standard deviation, mean |gradient| (detail), the clipped fractions, non-finite count."""+ vals = [v for row in grid for v in row]+ bad = sum(1 for v in vals if not math.isfinite(v))+ if bad:+ return {"bad": bad, "range": 0.0, "std": 0.0, "detail": 0.0, "low": 0.0, "high": 0.0}+ n = len(vals)+ mean = sum(vals) / n+ std = math.sqrt(sum((v - mean) ** 2 for v in vals) / n)+ h, w = len(grid), len(grid[0])+ grad = sum(abs(grid[y][x + 1] - grid[y][x]) for y in range(h) for x in range(w - 1)) / (h * (w - 1))+ return {"bad": 0, "range": max(vals) - min(vals), "std": std, "detail": grad, "mean": mean,+ "low": sum(1 for v in vals if v <= 0.002) / n, "high": sum(1 for v in vals if v >= 0.998) / n}+++def seam_ratio(grid):+ """The jump across the wrap-around edge against the largest jump between neighbouring columns (or rows) inside:+ about 1 or less for a seamless tile (sharp structure inside is fine), large where the tile doesn't wrap."""+ h, w = len(grid), len(grid[0])+ cols = [sum(abs(grid[y][x + 1] - grid[y][x]) for y in range(h)) / h for x in range(w - 1)]+ rows = [sum(abs(grid[y + 1][x] - grid[y][x]) for x in range(w)) / w for y in range(h - 1)]+ edge_x = sum(abs(grid[y][0] - grid[y][w - 1]) for y in range(h)) / h+ edge_y = sum(abs(grid[0][x] - grid[h - 1][x]) for x in range(w)) / w+ return max(edge_x / max(max(cols), 1e-4), edge_y / max(max(rows), 1e-4))+++def border_mean(grid, band=3):+ h, w = len(grid), len(grid[0])+ vals = [grid[y][x] for y in range(h) for x in range(w) if x < band or y < band or x >= w - band or y >= h - band]+ return sum(vals) / len(vals)+++def mean_abs_diff(a, b):+ h, w = min(len(a), len(b)), min(len(a[0]), len(b[0]))+ return sum(abs(a[y][x] - b[y][x]) for y in range(h) for x in range(w)) / (h * w)