"""Projects and props on disk: projects//project.json + projects//props//. A project's folder name is its id in URLs. A named project's folder name IS its name (display names are sanitised into safe folder names); an untitled one lives in untitled-YYYYMMDD-HHMMSS/ and is shown as "Untitled" / "Untitled 2" until it is given a name (rename_project). Every change is a read-modify-write of project.json under one lock, written atomically. projects/.state.json remembers the project opened last. See ARCHITECTURE.md "Project / prop schema". A project has at most one DRAFT prop: the Images workbench before it has a picture. Jobs may run on it; the page's props list shows only the other props. The draft becomes a normal prop (at the end of the list) the moment it gets its first chosen picture: an import, a picked candidate, or the first picture of a generation job (_pack). A prop's views (images.views) are the pictures, or parts of one picture, that show it from its sides: with two or more, Pixal3D makes one 3D model from all of them (adapters/pixal3d.py). They count only while the chosen picture is one of theirs (effective_views): another chosen picture is made into 3D alone, and the views wait for the artist to pick one of theirs again. mesh.source records what the model was made from (mesh_source), so a 3D model is out of date as soon as that changes. Saved models go to exports// (spellcast/exports.py); renaming a project renames that folder too. projects//temp/ is scratch space for the tools: a job that needs some gets a folder of its own there (work_dir) and removes it when it ends; what a stopped tool or a closed hub left behind is swept away later (clear_work_dirs). Nothing in it belongs to the project: its files are never served (resolve_file). """ from __future__ import annotations import copy import datetime import itertools import json import logging import math import os import re import secrets import shutil import struct import threading import time import unicodedata import zipfile from contextlib import contextmanager from dataclasses import dataclass, field from pathlib import Path, PurePosixPath, PureWindowsPath from typing import IO, Any, Callable, Collection, Iterable, Iterator from . import paths from .settings import atomic_write_json log = logging.getLogger(__name__) MAX_UPLOAD_BYTES = 50 * 1024 * 1024 MAX_THUMB_BYTES = 2 * 1024 * 1024 MAX_PROJECT_NAME = 60 MAX_PROP_NAME = 80 UNTITLED = "Untitled" NO_IMAGE_YET = "No image yet: import or generate one first." # The stages, in pipeline order. STAGE_IDS: tuple[str, ...] = tuple(stage for stage, _tool in paths.STAGES) # Every stage can have a thumbnail of the prop in the form that stage gave it. THUMB_STAGES = STAGE_IDS # The result of a stage that its thumbnail shows: a new one makes the thumbnail out of date. _THUMB_SOURCE: dict[str, str] = {"images": "chosen", "mesh": "glb", "omnitexture": "glb", "retopo": "obj", "projection": "glb"} _STATE_FILE = ".state.json" # {"last_opened": project id} _TRASH = ".trash" # empty untitled projects are moved here, never erased _TEMP = "temp" # projects//temp/: the tools' scratch space (ProjectStore.work_dir) # Words that end a prop name taken from a prompt ("wooden barrel with iron bands" -> "Wooden barrel"), and # prompt parts that describe the picture rather than the thing in it. _NAME_STOP_WORDS = frozenset({"with", "on", "in", "for", "and", "at", "from", "made", "that", "wearing", "holding", "against", "under", "over", "by", "of"}) _QUALITY_TAGS = frozenset({"masterpiece", "best quality", "high quality", "highest quality", "top quality", "ultra detailed", "highly detailed", "detailed", "highres", "absurdres", "4k", "8k", "hd", "uhd", "hdr", "photorealistic", "realistic", "3d", "3d render", "render", "game asset", "concept art", "white background", "simple background"}) # The UV unwrap of the clean meshes (xatlas's chart cost, 0..1 as Instant Meshes' viewer shows it): the top, its # largest islands, a little more stretch accepted for them. 0.5 was the default before: in a project that does not # say it was written since (_UV_DEFAULT_KEY), a prop holding 0.5 takes this one - once, so a 0.5 picked later in # Instant Meshes' viewer stays. UV_LENIENCY = 1.0 _OLD_UV_LENIENCY = 0.5 _UV_DEFAULT_KEY = "uv_leniency_default" # The side of a prop's textures, the 3D model's and the bake's alike. Each stage lays its texture into the next # one's (3D model, Omni-Texture, bake), and at 2048 every laying lost detail: the models looked soft. 2048 was the # default before, and a new prop copies the last one's settings: in a project that does not say it was written since # (_TEXTURE_DEFAULT_KEY), a prop holding 2048 takes this one - once, so a 2048 picked later stays. TEXTURE_SIZE = 4096 _OLD_TEXTURE_SIZE = 2048 _TEXTURE_DEFAULT_KEY = "texture_size_default" # Per editable stage (a stage with a tool): the settings a new prop starts with, and its result keys. # A new stage needs one entry here (and a tool in paths.STAGES); the stages without a tool get {}. STAGE_DEFAULTS: dict[str, dict[str, dict[str, Any]]] = { "images": { # Shared by the image generators: prompt (sent as typed), width, height (the Shape, at 1K), seed, # batch_count ("Variations"). # Forge Neo's own: negative_prompt ("Avoid"), checkpoint, sampler, scheduler, steps, # cfg_scale, denoising_strength. Qwen-Image's own: transparent (a picture with its own alpha; off by default, # the 3D stage removes an opaque picture's background itself) and qwen_steps # (IMAGES_NUMBERS), namespaced so Forge's steps never leak in. Qwen-Image is sampled without guidance, so it # has no CFG and no Avoid (adapters/qwen.py). qwen_steps = that adapter's DEFAULT_STEPS, the hub's one place # for it (the adapters import this module, so it cannot be imported here; tests/test_qwen_hub.py compares). "settings": {"prompt": "", "negative_prompt": "", "checkpoint": None, "sampler": None, "scheduler": None, "steps": 25, "cfg_scale": 6.0, "width": 1024, "height": 1024, "seed": -1, "batch_count": 1, "denoising_strength": 0.65, "transparent": False, "tileable": False, "qwen_steps": 25, # resolution: Qwen-Image's pictures are the Shape's sides times this (1, 1.5 or 2: the panel's # 1K / 1.5K / 2K; adapters/qwen.py RESOLUTIONS) "resolution": 1, # first_block_cache: Qwen-Image's First-Block Cache (adapters/qwen.py): on half of the # refinement steps the engine reuses its middle layers' work, ~35 % faster, the same picture # with slightly less fine detail. A tick, not a number: the share it skips is the engine's. # None = the card decides (the launcher's FIRST_BLOCK_CACHE_AUTO_BELOW: on for the GTX 10xx, # whose pictures take ~2.5 minutes without it, off for newer cards); True / False = the # artist's tick. "first_block_cache": None, # qwen_model: which Qwen-Image 2.1 draws the prop's pictures (QWEN_MODELS): "turbo", the # default for every card - Qwen-Image-2.1-Turbo, its own fixed 8 steps, so qwen_steps and # first_block_cache are not read for it - or "full", the full model at qwen_steps, which the # artist downloads first from the Images page (spellcast/model_downloads.py) - or "flux3", # FLUX.3 Image Klein (not Qwen-Image: the same launcher serves it), its own 16 steps and opaque # pictures (transparent is not read for it), also a download of its own. A prop saved before # there was a choice gets "turbo". "qwen_model": "turbo"}, # references: the example pictures of "Describe + example" (reference/reference_NNN., at most # MAX_REFERENCES; Forge uses the first). views: the pictures (or parts of one) that show the prop from each # side, for a multi-view 3D model (see set_views). Results like chosen, never settings, so they never pass # to the next prop. "outputs": {"references": [], "candidates": [], "chosen": None, "views": []}, }, "mesh": { # resolution: the voxel grid, 1536 ("High") by default, 1024 ("Standard"); multi-view props too. # geometry: whose networks make the shape (GEOMETRIES; the page's "Shape"): "pixal3d", Pixal3D's own, or # "hi3d", Hi3D v1.0 refining Pixal3D's coarse shape from the front picture (finer carved detail, slower). The # texture is Pixal3D's either way. A new prop takes its project's Shape, the one picked last in it (the # project's "geometry", Pixal3D until one is: ProjectStore._geometry); a prop saved before there was a choice # keeps "pixal3d". "settings": {"seed": 0, "resolution": 1536, "decimation_target": 300000, "texture_size": TEXTURE_SIZE, "geometry": "pixal3d"}, # imported: {"materials", "warnings", "skipped", "overrides"} when the mesh is the artist's own model. # geometry: the one that made the mesh (None: imported, or none yet). textured: False for a model made # without its texture (the 3D stage's second button; a job's "textured": false): the shape with its UVs # and flat maps on them, for Omni-Texture to paint (mesh_textured). "outputs": {"glb": None, "source": None, "imported": None, "geometry": None, "textured": True}, }, "omnitexture": { # chosen: the artist wants this prop's colour texture painted anew (a click on its tile in the Omni-Texture # stage). Never inherited by a new prop (_new_prop). Only a chosen prop's fresh result is used (high_poly). "settings": {"chosen": False}, # glb: a copy of the 3D model with the new texture (omnitexture/ot_NNN/...), made from source_mesh; views: # the pictures the image generator painted; projected: what went onto the model with the lighting taken off # (the albedo add-on; empty without it); layers: per view, its share of the texture alone (the page shows # one on the model while the pointer is over its picture); sheets: the views painted together in one # picture - per sheet its folder (what the image generator was given and answered) and its views' folders. # steps: the result, the repaints of what the artist masked on it and the pictures taken off it again # (each a glb in a folder of its own), oldest first: Ctrl+Z and Ctrl+Y on the page walk them # (omnitexture_step), "glb" is the one shown. A new mesh.glb makes it stale (apply_stage_patch). # repaints: what the steps' models hold of them (adapters/omnitexture.py: each the model it made, the model # it went onto - "under" -, picture, layer, fade, "hidden" when the artist hid it); bases: the results made # again from the job's - composed from fewer of the views (a view taken off), each its model and the views # it holds; or, "hidden", the 3D model's own texture while the artist hides the painted views: the views # it lists are not on it, "shown" is the model that holds them. # A result without views is the 3D model's own texture (omnitexture_own): the artist masked or painted # the prop without an Omni-Texture job. painted: a hand painting was saved into one of the result's models. "outputs": {"glb": None, "source_mesh": None, "views": [], "projected": [], "layers": [], "sheets": [], "steps": [], "repaints": [], "bases": [], "stale": False, "stats": None, "painted": False}, }, "retopo": { # method: the tool that makes the prop's clean meshes (RETOPO_METHODS; TriFlow until the artist picks # another: DEFAULT_RETOPO_METHOD). sizes: how many thousand vertices each of them gets, one clean mesh per # size (RETOPO_MAX_SIZES at most, the boxes on the prop's tile). The rest of the first two lines # are Instant Meshes' viewer's settings: its polygon count (target_vertices), rosy/posy (the Output mesh: # 4/4 quads, 6/3 triangles, 2/4 quad-dominant), extrinsic (Smooth flow) and align_to_boundaries (Follow # borders), and an Accept there stores the viewer's values of all of them (adapters/imesh.py # VIEWER_SETTINGS). lato2_* and triflow_* are LATO.2's and TriFlow's (RETOPO_NUMBERS). "settings": {"method": paths.TRIFLOW, "sizes": [2], "target_vertices": 5000, "pure_quad": False, "crease_angle": -1, "smooth_iter": 2, "uv_leniency": UV_LENIENCY, "rosy": 4, "posy": 4, "extrinsic": True, "align_to_boundaries": False, "lato2_seed": 0, "triflow_quad_ratio": 0.95, "triflow_seed": 0}, # variants: the clean meshes `method` made from the 3D model `source`, [{"size", "obj", "stats"}], one per # size (retopo/k/; _variants_patch). obj and stats: the variant the rest of the # app uses - the one picked, else the first - and accepted: the artist picked it (or it is the only size). # kept (only while there are some): {method: the clean meshes that method made, set aside while the prop is # set to another method} (switch_retopo_method). "outputs": {"obj": None, "method": None, "source": None, "session_id": None, "stale": False, "accepted": False, "variants": []}, }, "projection": { # quality = supersampling 1/2/3 (Fast/Good/Best); ray_distance None = automatic, else % of the diagonal. # Checked by adapters/projection.py; keep in sync with launchers/spellbake/settings.py. "settings": {"texture_size": TEXTURE_SIZE, "quality": 2, "ray_distance": None, "ao": True, "height": False, "hard_edge_angle": 60, "tangent_basis": "mikk", "normal_y": "opengl", "repack_uvs": True, "export_obj": True, "export_fbx": True}, "outputs": {"glb": None, "fbx": None, "obj": None, "maps": [], "source_mesh": None, "source_retopo": None, "stale": False, "stats": None}, }, } EDITABLE_STAGES: tuple[str, ...] = tuple(STAGE_DEFAULTS) DEFAULT_STAGE_SETTINGS: dict[str, dict[str, Any]] = {k: v["settings"] for k, v in STAGE_DEFAULTS.items()} _STAGE_OUTPUTS: dict[str, dict[str, Any]] = {k: v["outputs"] for k, v in STAGE_DEFAULTS.items()} # The result key of a stage whose change makes an existing projection (bake) out of date. _PROJECTION_INPUTS: dict[str, str] = {"mesh": "glb", "omnitexture": "glb", "retopo": "obj"} # omnitexture/ot_NNN folders kept per prop after a new Omni-Texture: the newest and the one before it (the bakes # keep two the same way: launchers/imesh_server.py KEEP_BAKES). KEEP_OMNITEXTURES = 2 OMNITEXTURE_FOLDER = "omnitexture" # in a prop's folder: its results, each in a folder ot_NNN OMNITEXTURE_MASK = f"{OMNITEXTURE_FOLDER}/mask.png" # what the artist masked, until its repaint job takes it # A step that is no model: the result taken off its prop as a whole (the page's x on its painted views). While it is # the step shown the prop has no result - it shows, bakes and saves its 3D model - and Ctrl+Z steps back to it. TAKEN_OFF = "" _OMNITEXTURE_DIR = re.compile(r"^ot_(\d+)$") # A repaint keeps its pictures beside the model it made, in ot_NNN/retouch/. The prop's record of it names two. RETOUCH_FOLDER = "retouch" REPAINT_PICTURE = "projected.png" # what went onto the model, as the camera saw it REPAINT_LAYER = "layer.webp" # its share of the texture alone: the page shows it on the model REPAINT_MASK = "mask.png" # what the artist masked # A step painted by hand on the page (PUT .../omnitexture/paint) keeps beside its model the model as it was made # and what the hand painted: its model is the one as made with the paint over its texture. UNPAINTED_MODEL = "unpainted.glb" HAND_PAINT = "hand-paint.png" # RGBA of the texture's size, alpha 255 where painted by hand # The retopology methods (paths.STAGE_TOOLS): a prop's retopo.settings.method picks the tool that makes its clean # meshes, and retopo.method says which one made the clean meshes it has. RETOPO_METHODS: tuple[str, ...] = paths.STAGE_TOOLS["retopo"] # The method every new prop starts with until the artist picks another on the Retopo page (then that one, in every # project: ProjectStore.retopo_default; never inherited from the prop before), and the one of a prop that names none # (rules.js retopoMethod says the same). A prop that picked keeps its own. DEFAULT_RETOPO_METHOD = paths.TRIFLOW # The method that made a clean mesh which does not say (made before there were other methods). FIRST_RETOPO_METHOD = paths.IMESH # A prop's sizes (retopo.settings.sizes): thousands of vertices, one clean mesh each, at most RETOPO_MAX_SIZES of # them, each from RETOPO_MIN_SIZE to RETOPO_MAX_SIZE with up to RETOPO_SIZE_DECIMALS decimals (0.25 = 250 vertices). # rules.js RETOPO_SIZES says the same (tests/test_web.py compares them). RETOPO_MAX_SIZES = 3 RETOPO_MIN_SIZE = 0.1 RETOPO_MAX_SIZE = 99 RETOPO_SIZE_DECIMALS = 2 # The clean meshes stay with the prop while it is set to another method (retopo.kept[method], see # switch_retopo_method), so going back to its method shows them again without making them again: only those whose # every variant has fewer vertices than this (their stats say how many). The same number as rules.js # RETOPO_KEEP_VERTICES. RETOPO_KEEP_VERTICES = 50_000 # What the clean meshes are in prop.retopo: these keys move to retopo.kept[method] and back. _RETOPO_RESULT_KEYS: tuple[str, ...] = ("obj", "method", "source", "stale", "accepted", "stats", "saved_from", "variants") # LATO.2's and TriFlow's numbers in retopo.settings: (whole number?, lowest, highest, the page's name for it). # Keep in sync with adapters/lato2.py and adapters/triflow.py, which check them again. RETOPO_NUMBERS: dict[str, tuple[bool, float, float, str]] = { "lato2_seed": (True, 0, 2 ** 31 - 1, "LATO.2's Seed"), "triflow_quad_ratio": (False, 0.0, 1.0, "TriFlow's Quads"), "triflow_seed": (True, 0, 2 ** 31 - 1, "TriFlow's Seed"), } # Retopo settings that are none any more, dropped from a project when it is read and from what a page sends: LATO.2's # vertices and TriFlow's triangles, which the sizes replace. _RETIRED_RETOPO_SETTINGS: tuple[str, ...] = ("lato2_vertices", "triflow_faces") # Qwen-Image's numbers in images.settings, the same way. Keep in sync with adapters/qwen.py, which checks them again. IMAGES_NUMBERS: dict[str, tuple[bool, float, float, str]] = { "qwen_steps": (True, 1, 100, "Steps"), "resolution": (False, 1, 2, "Resolution"), } # The built-in image generator's models (images.settings.qwen_model; adapters/qwen.py QWEN_MODELS checks it again), # the default first: Qwen-Image 2.1's two (install/models.py QWEN_MODELS) and FLUX.3 Image Klein. QWEN_MODELS: tuple[str, ...] = ("turbo", "full", "flux3") # Images settings that are none any more, dropped from a project when it is read and from what a page sends. # qwen_cfg: Qwen-Image's guidance (6.0 in every project: no page ever showed it) until it was sampled Qwen's own # way, without any. A prop that still has it was saved under that recipe, whose default was 20 steps: see # _normalize_images_settings. object_mode: "3D-ready framing", which added words about one centred object to every # prompt; prompts go to the image generators as the artist typed them now. from_sketch: the Sketch tab (until # 2026-10-31), whose painting was the one picture a generation was shown; the artist paints on Render Images' viewport # now ("Re-Render Viewport": the job's from_viewport). _RETIRED_IMAGES_SETTINGS: tuple[str, ...] = ("qwen_cfg", "object_mode", "from_sketch") # A job's own, never saved with the prop: the picture "Re-Render Viewport" starts from (saved, it would be re-rendered # in every later generation), how far the page showed it slid (adapters/qwen.py viewport_shift), and the picture a # Smart Mask was brushed over (adapters/images_common.py masked_change). _JOB_IMAGES_SETTINGS: tuple[str, ...] = ("from_viewport", "viewport_shift", "viewport_mask_of") # The 3D stage's geometries (mesh.settings.geometry; adapters/pixal3d.py sends it, launchers/pixal3d_server.py # GEOMETRIES checks it again), in the page's order. rules.js GEOMETRIES says the same. GEOMETRIES: tuple[str, ...] = ("hi3d", "pixal3d") DEFAULT_GEOMETRY = "pixal3d" # a new project's Shape for its props (a pick changes the project's: default_geometry) # The geometry of a prop that names none (or none there is): saved before there was a choice, so Pixal3D made it. FIRST_GEOMETRY = "pixal3d" _QWEN_STEPS_WITH_GUIDANCE = 20 MAX_REFERENCES = 10 # example pictures of a prop (Qwen-Image takes up to 10) # The picture the page's "Re-Render Viewport" sends when the artist painted marks over it, or painted on the empty # viewport (set_viewport): one file, replaced; a generation's from_viewport names it (or one of the prop's own # pictures when there are no marks). VIEWPORT_FILE = "viewport/viewport.png" # Smart Mask's upload beside it: where the artist brushed, white on black, the picture's size; one file, replaced. # Read by a job that names the picture it was brushed over (viewport_mask_of). VIEWPORT_MASK = "viewport/mask.png" MAX_VIEWPORT_BYTES = 16 * 1024 * 1024 # The artist's painting on a bake (PUT .../projection/paint): the base colour map as raw RGBA, 4096 px at most. MAX_PAINT_SIZE = 4096 MAX_PAINT_BYTES = MAX_PAINT_SIZE * MAX_PAINT_SIZE * 4 + 1024 BAKED_AGAIN = "This prop was baked again meanwhile, so the painting on the old textures was not saved." NOT_A_STEP = "That step of this prop's Omni-Texture is no longer kept, so the painting was not saved on it." # A bake's own base colour map, kept beside it (maps/) before the first painting is saved over it: one copy, never # replaced, gone with the bake's folder. Putting it back as maps/basecolor.png takes the painting off. UNPAINTED_BASECOLOR = "basecolor.unpainted.png" def retopo_method(settings: Any) -> str: """The retopology method retopo.settings choose (DEFAULT_RETOPO_METHOD when they name none that exists).""" method = settings.get("method") if isinstance(settings, dict) else None return method if method in RETOPO_METHODS else DEFAULT_RETOPO_METHOD def chosen_tool(stage: str, settings: Any) -> str | None: """The tool a prop's `stage` settings choose to run it (retopo: its method), or None when the stage's tools are not chosen per prop.""" return retopo_method(settings) if stage == "retopo" else None def _setting_number(key: str, value: Any) -> int | float: """One of RETOPO_NUMBERS or IMAGES_NUMBERS checked -> the value (a whole number as int). ProjectError in artist words.""" whole, low, high, name = RETOPO_NUMBERS.get(key) or IMAGES_NUMBERS[key] if whole: problem = f"{name} must be a whole number from {low:,} to {high:,}." ok = isinstance(value, int) or (isinstance(value, float) and value.is_integer()) else: problem = f"{name} must be a number from {low:g} to {high:g}." ok = isinstance(value, (int, float)) and value == value # not NaN if isinstance(value, bool) or not ok or not low <= value <= high: raise ProjectError(problem) return int(value) if whole else float(value) def _retopo_size(value: Any) -> int | float | None: """A size as the hub keeps it - rounded to RETOPO_SIZE_DECIMALS decimals, a whole one an int (2, never 2.0: the folders of older projects stay as they are) - or None when `value` is no number from RETOPO_MIN_SIZE to RETOPO_MAX_SIZE. Every size the hub takes in goes through here, so sizes compare as numbers everywhere after.""" if isinstance(value, bool) or not isinstance(value, (int, float)): return None size = round(float(value), RETOPO_SIZE_DECIMALS) if not RETOPO_MIN_SIZE <= size <= RETOPO_MAX_SIZE: # NaN too return None return int(size) if size.is_integer() else size def check_retopo_sizes(value: Any) -> list[int | float]: """retopo.settings.sizes checked -> the sizes (_retopo_size), each once, in the order given (an empty list too: the artist erased every box). ProjectError (400) in the artist's words.""" sizes = [_retopo_size(v) for v in value] if isinstance(value, list) else None if sizes is None or len(sizes) > RETOPO_MAX_SIZES or None in sizes: raise ProjectError(f"A prop has up to {RETOPO_MAX_SIZES} sizes, each a number of thousands of vertices from " f"{RETOPO_MIN_SIZE:g} to {RETOPO_MAX_SIZE:g}. Type them again in the boxes on its tile.") return list(dict.fromkeys(sizes)) def check_size_boxes(value: Any) -> list[int | float | None]: """retopo.settings.size_boxes checked: what each box on the prop's tile holds, in its place (None: empty), so a size typed into the second box stays there; `sizes` is what they ask for. ProjectError (400).""" boxes = value if isinstance(value, list) and len(value) <= RETOPO_MAX_SIZES else None checked = None if boxes is None else [None if v is None else _retopo_size(v) for v in boxes] if checked is None or any(c is None and v is not None for c, v in zip(checked, boxes)): raise ProjectError("The boxes on a prop's tile hold sizes or nothing. Type them again.") return checked def retopo_skipped(prop: dict[str, Any]) -> bool: """The artist emptied every box on the prop's tile in Retopo: no clean mesh is made of it, it is not baked, and Export all saves its detailed model. rules.js retopoSkipped says the same.""" sizes = ((prop.get("retopo") or {}).get("settings") or {}).get("sizes") return isinstance(sizes, list) and not sizes def retopo_sizes(settings: Any) -> list[int | float]: """The sizes retopo.settings ask for, in the order of the prop's boxes ([] when they are not valid).""" try: return check_retopo_sizes(settings.get("sizes") if isinstance(settings, dict) else None) except ProjectError: return [] def retopo_size_name(size: float) -> str: """A size as the page, the progress words and the folders write it: 0.25 -> "0.25k", 2 -> "2k", 12.5 -> "12.5k". rules.js retopoSizeName writes the same (tests/test_web.py compares them).""" return f"{size:g}k" def retopo_size_of(vertices: Any) -> int | float: """The size a clean mesh of `vertices` vertices stands for - its thousands to two significant digits, within the sizes (740 -> 0.74, 5,234 -> 5.2, 22,053 -> 22, 96 -> 0.1): one made before there were sizes, or shaped in Instant Meshes' viewer. One that does not say: the default size.""" if isinstance(vertices, bool) or not isinstance(vertices, (int, float)) or vertices != vertices: return DEFAULT_STAGE_SETTINGS["retopo"]["sizes"][0] thousands = float(f"{vertices / 1000:.2g}") size = _retopo_size(min(max(thousands, RETOPO_MIN_SIZE), RETOPO_MAX_SIZE)) assert size is not None # within the sizes return size # A prop's placement (prop["placement"], set with the Move / Rotate gizmo of the Retopo and Export pages): where its # model stands in the files of the export folder - {"move": [x, y, z], "turn": [x, y, z, w]}, a point p of the model # going to R p + t in the model's own axes (Y up, the front along +Z) and units, `turn` the unit quaternion of R. # None: the model as it was made (centred on its middle). Nothing but the saved files (exports.py) uses it: the bake, # the paintings and every stage's own view are of the model as made. PLACEMENT_REACH = 1000.0 # how far a model (about 1 across) may be moved, in its units def check_placement(value: Any) -> dict[str, list[float]] | None: """A placement a page sends (PATCH), checked -> as the hub stores it (the quaternion made unit length, w not negative), or None when it moves nothing. ProjectError (400) in the artist's words.""" if value is None: return None problem = ProjectError("The model's placement did not arrive whole. Reload the page (F5) and place it again.") if not isinstance(value, dict) or set(value) != {"move", "turn"}: raise problem move, turn = value["move"], value["turn"] numbers = [*move, *turn] if isinstance(move, list) and isinstance(turn, list) else [] if (len(numbers), len(move) if isinstance(move, list) else 0) != (7, 3) or not all( isinstance(n, (int, float)) and not isinstance(n, bool) and math.isfinite(n) for n in numbers): raise problem length = math.sqrt(sum(float(n) ** 2 for n in turn)) if length < 1e-6 or any(abs(n) > PLACEMENT_REACH for n in move): raise problem sign = -1.0 if turn[3] < 0 else 1.0 move = [round(float(n), 6) for n in move] turn = [round(sign * float(n) / length, 9) + 0.0 for n in turn] # (+ 0.0: no "-0.0" in the file) if not any(move) and turn[:3] == [0.0, 0.0, 0.0]: return None return {"move": move, "turn": turn} def check_retopo_settings(changes: dict[str, Any]) -> dict[str, Any]: """Retopo settings a page sends (PATCH), checked -> a copy with the numbers as the hub stores them. Only the method, the sizes and LATO.2's and TriFlow's numbers are checked here; Instant Meshes checks its own when it runs. A setting that is none any more (_RETIRED_RETOPO_SETTINGS, from a page loaded before the update) is left out. ProjectError (400) in the artist's words.""" out = {key: value for key, value in changes.items() if key not in _RETIRED_RETOPO_SETTINGS} if "method" in out and out["method"] not in RETOPO_METHODS: raise ProjectError(f"The retopology method must be one of: {', '.join(RETOPO_METHODS)}. " f"Reload the page and pick it again.") if "sizes" in out: out["sizes"] = check_retopo_sizes(out["sizes"]) if "size_boxes" in out: out["size_boxes"] = check_size_boxes(out["size_boxes"]) for key in [key for key in RETOPO_NUMBERS if key in out]: out[key] = _setting_number(key, out[key]) return out def _normalize_retopo_settings(settings: dict[str, Any], old_uv_default: bool = False) -> None: """An older or hand-edited project's retopo settings, repaired in place: a method, sizes or LATO.2 / TriFlow number that is not valid becomes the default; the settings that are none any more go. `old_uv_default`: the project is from before UV_LENIENCY was the default.""" defaults = DEFAULT_STAGE_SETTINGS["retopo"] for key in _RETIRED_RETOPO_SETTINGS: settings.pop(key, None) if settings.get("method") not in RETOPO_METHODS: settings["method"] = defaults["method"] try: settings["sizes"] = check_retopo_sizes(settings.get("sizes")) except ProjectError: settings["sizes"] = list(defaults["sizes"]) if "size_boxes" in settings: try: settings["size_boxes"] = check_size_boxes(settings["size_boxes"]) except ProjectError: del settings["size_boxes"] for key in RETOPO_NUMBERS: try: settings[key] = _setting_number(key, settings.get(key)) except ProjectError: settings[key] = defaults[key] # The page never showed the leniency, and a new prop copies the last one's settings, so the old default # would stay in a project for good. if old_uv_default and settings.get("uv_leniency") == _OLD_UV_LENIENCY: settings["uv_leniency"] = UV_LENIENCY def check_images_settings(changes: dict[str, Any]) -> dict[str, Any]: """Images settings a page sends (PATCH), checked -> a copy with the numbers as the hub stores them. Only Qwen-Image's own settings are checked here (transparent, first_block_cache, qwen_model, IMAGES_NUMBERS); the generators check the rest when they run. A setting that is none any more (_RETIRED_IMAGES_SETTINGS, from a page loaded before the update) is left out, whatever its value, and so is a job's own (_JOB_IMAGES_SETTINGS). ProjectError (400) in the artist's words.""" out = {key: value for key, value in changes.items() if key not in _RETIRED_IMAGES_SETTINGS and key not in _JOB_IMAGES_SETTINGS} if "transparent" in out and not isinstance(out["transparent"], bool): raise ProjectError('"Transparent background" must be on or off. Reload the page and set it again.') if "tileable" in out and not isinstance(out["tileable"], bool): raise ProjectError('"Tileable" must be on or off. Reload the page and set it again.') cache = out.get("first_block_cache") if cache is not None and not isinstance(cache, bool): raise ProjectError('"Faster drawing" must be on or off. Reload the page and set it again.') if "qwen_model" in out and out["qwen_model"] not in QWEN_MODELS: raise ProjectError("The model must be Turbo, Full or FLUX.3 Klein. Reload the page and pick it again.") if "use_references" in out and not isinstance(out["use_references"], bool): raise ProjectError("Describe or Describe + example must be picked. Reload the page and pick it again.") for key in [key for key in IMAGES_NUMBERS if key in out]: out[key] = _setting_number(key, out[key]) return out def _normalize_images_settings(settings: dict[str, Any]) -> None: """An older or hand-edited project's images settings, repaired in place like _normalize_retopo_settings; the settings that are none any more (_RETIRED_IMAGES_SETTINGS) are dropped, so a new prop does not inherit them. negative_prompt stays whichever generator runs: it is Forge Neo's "Avoid", and Qwen-Image does not read it.""" defaults = DEFAULT_STAGE_SETTINGS["images"] # A prop saved while Qwen-Image was sampled with guidance (it still has qwen_cfg) at that recipe's default steps # follows the default of today's recipe: every prop stored the default, and a new prop takes the last one's # settings, so the old number would otherwise stay in the project for good. Any other number is the artist's # and stays. Once the project is saved, qwen_cfg is gone and its steps are whatever the artist sets. if "qwen_cfg" in settings and settings.get("qwen_steps") == _QWEN_STEPS_WITH_GUIDANCE: settings["qwen_steps"] = defaults["qwen_steps"] for key in _RETIRED_IMAGES_SETTINGS: settings.pop(key, None) for key in ("transparent", "tileable"): if not isinstance(settings.get(key), bool): settings[key] = defaults[key] if not isinstance(settings.get("first_block_cache"), bool): settings["first_block_cache"] = defaults["first_block_cache"] # None: the card decides # qwen_model: a prop from before there was a choice (or a value that is none) draws with the Turbo, the default if settings.get("qwen_model") not in QWEN_MODELS: settings["qwen_model"] = defaults["qwen_model"] # use_references: false = the page's "Describe" mode, which keeps the example pictures but makes the pictures # from the words alone (images_common.reference_files); missing = they go along ("Describe + example"). if "use_references" in settings and not isinstance(settings["use_references"], bool): del settings["use_references"] for key in IMAGES_NUMBERS: try: settings[key] = _setting_number(key, settings.get(key)) except ProjectError: settings[key] = defaults[key] def default_geometry(project_geometry: Any = None) -> str: """A new prop's geometry: its project's (`project_geometry`: the project's "geometry", the Shape picked last in it), Hi3D only where its code is on this PC; else DEFAULT_GEOMETRY, Pixal3D's, which this Spellcast3D can always make. So Hi3D sticks within a project once picked there (until Pixal3D is picked again) and never beyond it: another project starts on Pixal3D (before 2026-11-03 the Shape picked last stuck for the whole installation).""" if project_geometry == "hi3d" and paths.hi3d_code_here(): return project_geometry return DEFAULT_GEOMETRY def mesh_textured(prop: dict[str, Any]) -> bool: """The prop's 3D model has a texture of its own: not one made without it (mesh.textured; rules.js meshTextured says the same).""" return (prop.get("mesh") or {}).get("textured") is not False def mesh_geometry(settings: Any) -> str: """The geometry mesh.settings choose (GEOMETRIES): FIRST_GEOMETRY when they name none that exists (a prop saved before there was a choice; rules.js meshGeometry says the same).""" geometry = settings.get("geometry") if isinstance(settings, dict) else None return geometry if geometry in GEOMETRIES else FIRST_GEOMETRY def check_mesh_settings(changes: dict[str, Any]) -> dict[str, Any]: """Mesh settings a page sends (PATCH), checked -> a copy. Only the geometry is checked here; the 3D generator checks the numbers when it runs. ProjectError (400) in the artist's words.""" out = dict(changes) if "geometry" in out and out["geometry"] not in GEOMETRIES: raise ProjectError("The shape must be made by Hi3D or Pixal3D. Reload the page and pick it again.") return out def retouch_folder(glb: str) -> str: """The folder the repaint that made the step `glb` keeps its pictures in (relative to the prop's, as `glb`).""" return f"{glb.rsplit('/', 1)[0]}/{RETOUCH_FOLDER}" def repaint_record(glb: str, fade: float = 1.0, layer: str = REPAINT_LAYER, under: str | None = None, hidden: bool = False) -> dict[str, Any]: """What a prop keeps of the repaint that made the model `glb` (omnitexture.repaints): that model, the model it went onto (`under`; None: no longer known), the picture that went on, the `layer` the page shows on the model while the pointer is over that picture, and how many times as far as a seam the repaint's edge fades into what is around it. `hidden`: the artist hid it (the eye on its picture) - it keeps its place among the repaints and puts nothing on: its model is the one it went onto, with what was painted by hand on its step. The model's FILE is there for a step and for the model the prop shows; a repaint put on again for a later one's sake has the record and its pictures alone (adapters/omnitexture.py _put_on_again).""" folder = retouch_folder(glb) return {"glb": glb, "under": under, "picture": f"{folder}/{REPAINT_PICTURE}", "layer": f"{folder}/{layer}", "fade": fade, **({"hidden": True} if hidden else {})} def _step_before(steps: list[str], step: str) -> str | None: """The step before `step`: what a repaint recorded before "under" was went onto (they followed each other).""" return steps[steps.index(step) - 1] if step in steps[1:] else None # How much detail a prop's Omni-Texture gets (omnitexture.settings.detail): as Qwen-Image paints it, the first, or # its painted views made larger by a network before they lie on the model (adapters/omnitexture_detail.py). OMNITEXTURE_DETAILS = ("original", "upscaled", "detailed") OMNITEXTURE_DETAIL = "detailed" # ... until the artist picks another (rules.js OMNI_DETAIL_UNSET) # The detail and its boldness are the project's, one for all its props (the page's "General Render Settings"): kept # in the project's "omnitexture" and in every prop's settings, which the jobs read. Set on one prop, they are set # on all (patch_prop). OMNITEXTURE_SHARED = ("detail", "detail_boldness") # omnitexture.settings.detail_boldness: how freely the "detailed" kind redraws the views (launchers/detail_worker.py # lessened), up to OMNITEXTURE_BOLDEST - bolder redraws faces - and OMNITEXTURE_BOLDNESS unless set. rules.js # OMNI_BOLDNESS says the same. OMNITEXTURE_BOLDNESS, OMNITEXTURE_BOLDEST = 0.25, 0.5 def check_omnitexture_settings(changes: dict[str, Any]) -> dict[str, Any]: """Omni-Texture settings a page sends (PATCH), checked -> a copy. ProjectError (400) in the artist's words.""" out = dict(changes) if "chosen" in out and not isinstance(out["chosen"], bool): raise ProjectError("A prop is either chosen for Omni-Texture or not. Reload the page and click it again.") if "detail" in out and out["detail"] not in OMNITEXTURE_DETAILS: raise ProjectError("That is not a detail Omni-Texture knows. Reload the page and pick one again.") if "detail_boldness" in out: bold = out["detail_boldness"] if isinstance(bold, bool) or not isinstance(bold, (int, float)) or not 0 <= bold <= 1: raise ProjectError("That is not a boldness Omni-Texture knows. Reload the page and set it again.") out["detail_boldness"] = round(min(float(bold), OMNITEXTURE_BOLDEST), 2) return out def _omnitexture_shared(data: dict[str, Any]) -> dict[str, Any]: """The project's detail and boldness (OMNITEXTURE_SHARED): as its file has them; for a file from before they were the project's, what its props that name one agree on; else OMNITEXTURE_DETAIL at OMNITEXTURE_BOLDNESS.""" kept = data.get("omnitexture") if isinstance(data.get("omnitexture"), dict) else {} named = [(prop.get("omnitexture") or {}).get("settings") or {} for prop in data["props"]] def one(key: str, known: Callable[[Any], bool], unset: Any) -> Any: if known(kept.get(key)): return kept[key] agreed = {settings[key] for settings in named if known(settings.get(key))} return agreed.pop() if len(agreed) == 1 else unset def boldness(value: Any) -> bool: return isinstance(value, (int, float)) and not isinstance(value, bool) and 0 <= value <= OMNITEXTURE_BOLDEST return {"detail": one("detail", lambda value: isinstance(value, str) and value in OMNITEXTURE_DETAILS, OMNITEXTURE_DETAIL), "detail_boldness": one("detail_boldness", boldness, OMNITEXTURE_BOLDNESS)} def omnitexture_fresh(prop: dict[str, Any]) -> bool: """The prop's Omni-Texture was made from the 3D model it has now (a new mesh.glb makes it stale; Pixal3D always writes the same path, so the flag says what the path cannot). rules.js omnitextureFresh gives the same.""" block = prop.get("omnitexture") or {} if not block.get("glb") or block.get("stale"): return False source = block.get("source_mesh") return not source or source == (prop.get("mesh") or {}).get("glb") def omnitexture_own(prop: dict[str, Any]) -> bool: """The prop's result is its 3D model's own texture: no Omni-Texture job painted a view onto it, only the artist did - by hand, or by masking a part and having that painted again (adapters/omnitexture.py begin_own). rules.js omniOwn gives the same.""" block = prop.get("omnitexture") or {} return bool(block.get("glb")) and not block.get("views") def omnitexture_used(prop: dict[str, Any]) -> bool: """The Projection stage bakes the prop's result and Export all saves it in place of the 3D model: a fresh Omni-Texture of a prop chosen for one (unchosen, it is kept but not used), or the 3D model's own texture once the artist painted or repainted something on it, chosen or not. rules.js omnitextureUsed gives the same.""" block = prop.get("omnitexture") or {} if not omnitexture_fresh(prop): return False if omnitexture_own(prop): return block.get("painted") is True or bool(block.get("repaints")) return (block.get("settings") or {}).get("chosen") is True def high_poly(prop: dict[str, Any]) -> str | None: """The detailed model the prop's bake reads (relative to its folder): its Omni-Texture while used (omnitexture_used), else its 3D model. Retopo always reads the 3D model. rules.js highPoly gives the same.""" return prop["omnitexture"]["glb"] if omnitexture_used(prop) else (prop.get("mesh") or {}).get("glb") def _normalize_mesh(block: dict[str, Any], saved: dict[str, Any], says_geometry: bool) -> None: """An older or hand-edited project's mesh block, repaired in place: settings that name no geometry (`saved`, as the file has them) keep Pixal3D's (mesh_geometry), and a model whose block did not say which made it (`says_geometry` false: made before there was a choice) was Pixal3D's.""" block["settings"]["geometry"] = mesh_geometry(saved) block["textured"] = block.get("textured") is not False if not says_geometry: block["geometry"] = FIRST_GEOMETRY if block.get("glb") and not block.get("imported") else None elif block["geometry"] not in GEOMETRIES: block["geometry"] = None def _normalize_references(block: dict[str, Any]) -> None: """images.references as project.json has it, in place: the prop's own example pictures (reference/...), each once, at most MAX_REFERENCES. The one "reference" of older projects (Forge's img2img picture) becomes the first.""" old = block.pop("reference", None) raw = block.get("references") if isinstance(block.get("references"), list) else [] refs = [rel for rel in ([old] if old else []) + raw if _is_reference_path(rel)] block["references"] = list(dict.fromkeys(refs))[:MAX_REFERENCES] def _is_reference_path(rel: Any) -> bool: """reference/: where add_references stores the example pictures.""" if not isinstance(rel, str) or ":" in rel or "\\" in rel: return False parts = rel.split("/") return len(parts) == 2 and parts[0] == "reference" and parts[1] not in ("", ".", "..") def retopo_fresh(prop: dict[str, Any]) -> bool: """The prop's clean mesh (retopo.obj) was made from the 3D model it has now, by the method it is set to: a new 3D model, or another method picked, makes it "to do" again (another method: the clean mesh waits in retopo.kept, see switch_retopo_method; one too big for that stays until it is replaced). rules.js retopoFresh must give the same (tests/test_web.py compares them).""" retopo = prop.get("retopo") or {} if not retopo.get("obj") or retopo.get("stale"): return False source = retopo.get("source") if source and source != (prop.get("mesh") or {}).get("glb"): return False made_by = retopo.get("method") or FIRST_RETOPO_METHOD return made_by == ((retopo.get("settings") or {}).get("method") or DEFAULT_RETOPO_METHOD) def retopo_missing_sizes(prop: dict[str, Any], sizes: list[int | float] | None = None) -> list[int | float]: """The sizes (the prop's own, unless given) it has no clean mesh of yet: those without a variant while its clean meshes are up to date (retopo_fresh), else all of them. rules.js retopoMissing gives the same (tests/test_web.py compares them).""" block = prop.get("retopo") or {} wanted = retopo_sizes(block.get("settings")) if sizes is None else sizes if not retopo_fresh(prop): return list(wanted) made = {variant.get("size") for variant in block.get("variants") or [] if isinstance(variant, dict)} return [size for size in wanted if size not in made] def _variants_patch(block: dict[str, Any], patch: dict[str, Any]) -> dict[str, Any]: """New clean meshes (patch "variants": [{"size", "obj", "stats"}], a job's or the viewer's) as the patch that makes them the prop's. They join the variants the prop has when those are up to date and of the same method and 3D model (one of the same size or file is replaced), else they replace them. The variant the prop then uses (obj, stats): the one `patch["picked"]` names (the viewer's Accept), else the new one of a prop with one size, else the one picked before when it was not made again, else the first of the prop's sizes; accepted for the first three. Only "variants" changes while the prop keeps using the same file: a bake made from it stays fresh.""" method = patch.get("method") if patch.get("method") in RETOPO_METHODS else FIRST_RETOPO_METHOD made = [dict(variant) for variant in patch["variants"]] if not made: return {} remade = {variant["size"] for variant in made} joins = bool(block.get("obj")) and not block.get("stale") and block.get("source") == patch.get("source") \ and (block.get("method") or FIRST_RETOPO_METHOD) == method files = {variant["obj"] for variant in made} old = [variant for variant in (block.get("variants") or [] if joins else []) if variant["size"] not in remade and variant["obj"] not in files] variants = sorted(old + made, key=lambda variant: variant["size"]) by_size = {variant["size"]: variant for variant in variants} sizes = retopo_sizes(block.get("settings")) picked = patch.get("picked") if picked is None and len(sizes) == 1 and sizes[0] in remade: picked = sizes[0] before = next((variant for variant in old if variant["obj"] == block.get("obj")), None) if picked in by_size: used, accepted = by_size[picked], True elif before is not None and block.get("accepted"): used, accepted = before, True else: used = next((by_size[size] for size in sizes if size in by_size), variants[0]) accepted = False if used is before and accepted == bool(block.get("accepted")): return {"variants": variants} rest = {key: value for key, value in patch.items() if key not in ("variants", "picked")} return {**rest, "variants": variants, "obj": used["obj"], "stats": used.get("stats"), "accepted": accepted} def _use_the_only_size(prop: dict[str, Any]) -> None: """A prop that asks for one size and has its clean mesh, up to date, uses that one, picked: there is nothing for the artist to choose (a job's result says so itself, _variants_patch; this is for sizes or a method saved since, and a project from before there were picks). In place; a bake made from another clean mesh is out of date, and the thumbnail of another one goes.""" block = prop["retopo"] sizes = retopo_sizes(block.get("settings")) variant = next((v for v in block.get("variants") or [] if v["size"] == sizes[0]), None) \ if len(sizes) == 1 and retopo_fresh(prop) else None if variant is None or (block.get("obj") == variant["obj"] and block.get("accepted") is True): return if block.get("obj") != variant["obj"]: prop["thumbs"].pop("retopo", None) if (prop.get("projection") or {}).get("glb"): prop["projection"]["stale"] = True block.update(obj=variant["obj"], stats=variant.get("stats"), accepted=True) def retopo_keepable(result: dict[str, Any]) -> bool: """The clean meshes are small enough to stay with the prop while it is set to another method: the stats of every variant say fewer than RETOPO_KEEP_VERTICES vertices (one that does not say how many is not kept).""" def small(variant: Any) -> bool: vertices = (variant.get("stats") or {}).get("vertices") if isinstance(variant, dict) else None return isinstance(vertices, (int, float)) and not isinstance(vertices, bool) and vertices < RETOPO_KEEP_VERTICES variants = result.get("variants") or [] return bool(result.get("obj")) and bool(variants) and all(small(variant) for variant in variants) def _take_retopo_result(block: dict[str, Any]) -> dict[str, Any]: """The prop's clean mesh, taken out of prop.retopo (its _RETOPO_RESULT_KEYS): the block is left without one.""" result = {key: block.pop(key) for key in _RETOPO_RESULT_KEYS if key in block} block.update({key: copy.deepcopy(default) for key, default in _STAGE_OUTPUTS["retopo"].items() if key in _RETOPO_RESULT_KEYS}) return result def _kept_retopos(block: dict[str, Any]) -> dict[str, Any]: """retopo.kept: {method: the clean mesh that method made, set aside while the prop is set to another}.""" return block["kept"] if isinstance(block.get("kept"), dict) else {} def _set_kept_retopos(block: dict[str, Any], kept: dict[str, Any]) -> None: if kept: block["kept"] = kept else: block.pop("kept", None) def _normalize_variants(result: dict[str, Any]) -> None: """An older or hand-edited project's clean meshes (prop.retopo, or one of retopo.kept), repaired in place: the variants are {"size", "obj", "stats"}, one per size, smallest first, and only while there is a clean mesh (obj). One from before there were sizes (its obj in no variant) becomes the variant of the size its vertex count stands for (retopo_size_of).""" variants: dict[int | float, dict[str, Any]] = {} for variant in result.get("variants") if isinstance(result.get("variants"), list) else []: size = _retopo_size(variant.get("size")) if isinstance(variant, dict) else None if size is not None and isinstance(variant.get("obj"), str) and variant["obj"] and size not in variants: stats = variant.get("stats") variants[size] = {"size": size, "obj": variant["obj"], "stats": stats if isinstance(stats, dict) else None} obj = result.get("obj") if obj and all(variant["obj"] != obj for variant in variants.values()): stats = result.get("stats") if isinstance(result.get("stats"), dict) else None size = retopo_size_of((stats or {}).get("vertices")) variants[size] = {"size": size, "obj": obj, "stats": stats} result["variants"] = sorted(variants.values(), key=lambda variant: variant["size"]) if obj else [] def switch_retopo_method(block: dict[str, Any], method: str) -> bool: """prop.retopo once the prop is set to `method`, in place -> True when the prop's clean mesh is another one now. Each method keeps its own clean mesh: the one `method` made before (retopo.kept) is the prop's again, and the one the prop had waits there under its own method when it is small enough (retopo_keepable). One that is too big stays the prop's clean mesh, "to do" again, until another method's replaces it. Nothing is deleted on disk (each method writes its own file). rules.js retopoSwitched must give the same (tests/test_web.py compares them).""" kept = _kept_retopos(block) back = kept.get(method) back = back if isinstance(back, dict) and back.get("obj") else None made_by = (block.get("method") or FIRST_RETOPO_METHOD) if block.get("obj") else None if made_by == method or (not back and not retopo_keepable(block)): return False keep = retopo_keepable(block) result = _take_retopo_result(block) if keep: kept[made_by] = result kept.pop(method, None) block.update(back or {}) _set_kept_retopos(block, kept) return True def _make_room_for_retopo(block: dict[str, Any], method: str) -> None: """A new clean mesh made by `method` is about to become the prop's: the one that method made before is replaced (also a kept one), one of another method is set aside when it is small enough (else it is replaced too).""" kept = _kept_retopos(block) kept.pop(method, None) if block.get("obj") and (block.get("method") or FIRST_RETOPO_METHOD) != method and retopo_keepable(block): made_by = block.get("method") or FIRST_RETOPO_METHOD kept[made_by] = _take_retopo_result(block) _set_kept_retopos(block, kept) def _switch_retopo(prop: dict[str, Any]) -> None: """The prop was set to another retopology method (switch_retopo_method). When its clean mesh is another one now, the retopo thumbnail goes (it shows the other one), and the bake is out of date unless it was made from the clean mesh that is back: a kept clean mesh remembers whether its bake was up to date (bake_stale).""" block, bake = prop["retopo"], prop.get("projection") or {} had, made_by = block.get("obj"), block.get("method") or FIRST_RETOPO_METHOD if not switch_retopo_method(block, retopo_method(block.get("settings"))): return prop["thumbs"].pop("retopo", None) bake_stale = block.pop("bake_stale", True) if not bake.get("glb"): return aside = _kept_retopos(block).get(made_by) if had else None if aside and bake.get("source_retopo") == had: aside["bake_stale"] = bool(bake.get("stale")) if block.get("obj"): bake["stale"] = bool(bake_stale) if bake.get("source_retopo") == block["obj"] else True # The artist's own 3D model ("+" in the 3D stage, or a drop there): uploaded files, or .zip files # that are unpacked, land in mesh/import_NNN/ and Instant Meshes converts the model into # mesh/imported_NNN.glb. Models in order of preference when several arrive at once; keep in sync # with instant_meshes_brush.assets.SUFFIXES. Every other kind of file is left out. MAX_MODEL_UPLOAD_BYTES = 1024 ** 3 MODEL_SUFFIXES: tuple[str, ...] = (".fbx", ".glb", ".gltf", ".obj", ".dae", ".ply", ".stl", ".off") MODEL_COMPANION_SUFFIXES = frozenset({ ".mtl", ".bin", ".png", ".jpg", ".jpeg", ".tga", ".tif", ".tiff", ".bmp", ".webp", ".dds", ".psd", ".exr"}) # EXR is not read, but the import then names the texture it could not use MAX_IMPORT_FILES = 5000 _MAX_IMPORT_PATH = 180 # characters of a saved file's path inside the import folder _MAX_IMPORT_NAME = 100 # characters of one folder or file name in it _COPY_CHUNK = 1024 * 1024 _IMPORT_ENTRY = re.compile(r"^import(?:ed)?_(\d+)(?:\.glb)?$") _PATH_UNSAFE_CHARS = re.compile(r'[<>:"|?*\x00-\x1f]') # The sides a view shows, in the order a multi-view 3D model takes them (the front first). "left": the prop's # own left side, so it faces image-left; "right": it faces image-right. Keep in sync with static/js/stages/rules.js. VIEW_ORDER: tuple[str, ...] = ("front", "left", "back", "right") VIEW_NAMES = {"front": "Front", "left": "← Left", "back": "Back", "right": "Right →"} MIN_VIEW_SIZE = 16 # pixels: a smaller part of a picture is no view of anything MAX_IMAGE_UPLOADS = 16 # pictures in one upload (each read into memory) # The page's state of a project: the stage the artist had open. The rows-of-cards version kept the active # row's index and one card position per row instead (_OLD_UI_KEYS); a project saved by it opens at that stage, # read with the stages of its time (_OLD_UI_ROWS: before Omni-Texture), never with today's list. DEFAULT_UI: dict[str, Any] = {"stage": "images"} _OLD_UI_KEYS = ("unlocked_row", "active_row", "positions") _OLD_UI_ROWS: tuple[str, ...] = ("images", "mesh", "retopo", "projection", "rig") PROP_ID_RE = re.compile(r"^p_[0-9a-f]{6}$") # A deleted prop's folder in its project's deleted/ (delete_prop): _